1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple interprocedural pass which walks the
11 // call-graph, looking for functions which do not access or only read
12 // non-local memory, and marking them readnone/readonly. It does the
13 // same with function arguments independently, marking them readonly/
14 // readnone/nocapture. Finally, well-known library call declarations
15 // are marked with all attributes that are consistent with the
16 // function's standard definition. This pass is implemented as a
17 // bottom-up traversal of the call-graph.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/Analysis/CallGraphSCCPass.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InstIterator.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 using namespace llvm;
36
37 #define DEBUG_TYPE "functionattrs"
38
39 STATISTIC(NumReadNone, "Number of functions marked readnone");
40 STATISTIC(NumReadOnly, "Number of functions marked readonly");
41 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
42 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
43 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
44 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
45 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
46
47 namespace {
48 struct FunctionAttrs : public CallGraphSCCPass {
49 static char ID; // Pass identification, replacement for typeid
FunctionAttrs__anon4eb4aa3b0111::FunctionAttrs50 FunctionAttrs() : CallGraphSCCPass(ID), AA(nullptr) {
51 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
52 }
53
54 // runOnSCC - Analyze the SCC, performing the transformation if possible.
55 bool runOnSCC(CallGraphSCC &SCC) override;
56
57 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
58 bool AddReadAttrs(const CallGraphSCC &SCC);
59
60 // AddArgumentAttrs - Deduce nocapture attributes for the SCC.
61 bool AddArgumentAttrs(const CallGraphSCC &SCC);
62
63 // IsFunctionMallocLike - Does this function allocate new memory?
64 bool IsFunctionMallocLike(Function *F,
65 SmallPtrSet<Function*, 8> &) const;
66
67 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
68 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
69
70 // Utility methods used by inferPrototypeAttributes to add attributes
71 // and maintain annotation statistics.
72
setDoesNotAccessMemory__anon4eb4aa3b0111::FunctionAttrs73 void setDoesNotAccessMemory(Function &F) {
74 if (!F.doesNotAccessMemory()) {
75 F.setDoesNotAccessMemory();
76 ++NumAnnotated;
77 }
78 }
79
setOnlyReadsMemory__anon4eb4aa3b0111::FunctionAttrs80 void setOnlyReadsMemory(Function &F) {
81 if (!F.onlyReadsMemory()) {
82 F.setOnlyReadsMemory();
83 ++NumAnnotated;
84 }
85 }
86
setDoesNotThrow__anon4eb4aa3b0111::FunctionAttrs87 void setDoesNotThrow(Function &F) {
88 if (!F.doesNotThrow()) {
89 F.setDoesNotThrow();
90 ++NumAnnotated;
91 }
92 }
93
setDoesNotCapture__anon4eb4aa3b0111::FunctionAttrs94 void setDoesNotCapture(Function &F, unsigned n) {
95 if (!F.doesNotCapture(n)) {
96 F.setDoesNotCapture(n);
97 ++NumAnnotated;
98 }
99 }
100
setOnlyReadsMemory__anon4eb4aa3b0111::FunctionAttrs101 void setOnlyReadsMemory(Function &F, unsigned n) {
102 if (!F.onlyReadsMemory(n)) {
103 F.setOnlyReadsMemory(n);
104 ++NumAnnotated;
105 }
106 }
107
setDoesNotAlias__anon4eb4aa3b0111::FunctionAttrs108 void setDoesNotAlias(Function &F, unsigned n) {
109 if (!F.doesNotAlias(n)) {
110 F.setDoesNotAlias(n);
111 ++NumAnnotated;
112 }
113 }
114
115 // inferPrototypeAttributes - Analyze the name and prototype of the
116 // given function and set any applicable attributes. Returns true
117 // if any attributes were set and false otherwise.
118 bool inferPrototypeAttributes(Function &F);
119
120 // annotateLibraryCalls - Adds attributes to well-known standard library
121 // call declarations.
122 bool annotateLibraryCalls(const CallGraphSCC &SCC);
123
getAnalysisUsage__anon4eb4aa3b0111::FunctionAttrs124 void getAnalysisUsage(AnalysisUsage &AU) const override {
125 AU.setPreservesCFG();
126 AU.addRequired<AliasAnalysis>();
127 AU.addRequired<TargetLibraryInfoWrapperPass>();
128 CallGraphSCCPass::getAnalysisUsage(AU);
129 }
130
131 private:
132 AliasAnalysis *AA;
133 TargetLibraryInfo *TLI;
134 };
135 }
136
137 char FunctionAttrs::ID = 0;
138 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
139 "Deduce function attributes", false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)140 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
141 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
142 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
143 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
144 "Deduce function attributes", false, false)
145
146 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
147
148
149 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
AddReadAttrs(const CallGraphSCC & SCC)150 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
151 SmallPtrSet<Function*, 8> SCCNodes;
152
153 // Fill SCCNodes with the elements of the SCC. Used for quickly
154 // looking up whether a given CallGraphNode is in this SCC.
155 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
156 SCCNodes.insert((*I)->getFunction());
157
158 // Check if any of the functions in the SCC read or write memory. If they
159 // write memory then they can't be marked readnone or readonly.
160 bool ReadsMemory = false;
161 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
162 Function *F = (*I)->getFunction();
163
164 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
165 // External node or node we don't want to optimize - assume it may write
166 // memory and give up.
167 return false;
168
169 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(F);
170 if (MRB == AliasAnalysis::DoesNotAccessMemory)
171 // Already perfect!
172 continue;
173
174 // Definitions with weak linkage may be overridden at linktime with
175 // something that writes memory, so treat them like declarations.
176 if (F->isDeclaration() || F->mayBeOverridden()) {
177 if (!AliasAnalysis::onlyReadsMemory(MRB))
178 // May write memory. Just give up.
179 return false;
180
181 ReadsMemory = true;
182 continue;
183 }
184
185 // Scan the function body for instructions that may read or write memory.
186 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
187 Instruction *I = &*II;
188
189 // Some instructions can be ignored even if they read or write memory.
190 // Detect these now, skipping to the next instruction if one is found.
191 CallSite CS(cast<Value>(I));
192 if (CS) {
193 // Ignore calls to functions in the same SCC.
194 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
195 continue;
196 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(CS);
197 // If the call doesn't access arbitrary memory, we may be able to
198 // figure out something.
199 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
200 // If the call does access argument pointees, check each argument.
201 if (AliasAnalysis::doesAccessArgPointees(MRB))
202 // Check whether all pointer arguments point to local memory, and
203 // ignore calls that only access local memory.
204 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
205 CI != CE; ++CI) {
206 Value *Arg = *CI;
207 if (Arg->getType()->isPointerTy()) {
208 AAMDNodes AAInfo;
209 I->getAAMetadata(AAInfo);
210
211 AliasAnalysis::Location Loc(Arg,
212 AliasAnalysis::UnknownSize, AAInfo);
213 if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
214 if (MRB & AliasAnalysis::Mod)
215 // Writes non-local memory. Give up.
216 return false;
217 if (MRB & AliasAnalysis::Ref)
218 // Ok, it reads non-local memory.
219 ReadsMemory = true;
220 }
221 }
222 }
223 continue;
224 }
225 // The call could access any memory. If that includes writes, give up.
226 if (MRB & AliasAnalysis::Mod)
227 return false;
228 // If it reads, note it.
229 if (MRB & AliasAnalysis::Ref)
230 ReadsMemory = true;
231 continue;
232 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
233 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
234 if (!LI->isVolatile()) {
235 AliasAnalysis::Location Loc = AA->getLocation(LI);
236 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
237 continue;
238 }
239 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
240 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
241 if (!SI->isVolatile()) {
242 AliasAnalysis::Location Loc = AA->getLocation(SI);
243 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
244 continue;
245 }
246 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
247 // Ignore vaargs on local memory.
248 AliasAnalysis::Location Loc = AA->getLocation(VI);
249 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
250 continue;
251 }
252
253 // Any remaining instructions need to be taken seriously! Check if they
254 // read or write memory.
255 if (I->mayWriteToMemory())
256 // Writes memory. Just give up.
257 return false;
258
259 // If this instruction may read memory, remember that.
260 ReadsMemory |= I->mayReadFromMemory();
261 }
262 }
263
264 // Success! Functions in this SCC do not access memory, or only read memory.
265 // Give them the appropriate attribute.
266 bool MadeChange = false;
267 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
268 Function *F = (*I)->getFunction();
269
270 if (F->doesNotAccessMemory())
271 // Already perfect!
272 continue;
273
274 if (F->onlyReadsMemory() && ReadsMemory)
275 // No change.
276 continue;
277
278 MadeChange = true;
279
280 // Clear out any existing attributes.
281 AttrBuilder B;
282 B.addAttribute(Attribute::ReadOnly)
283 .addAttribute(Attribute::ReadNone);
284 F->removeAttributes(AttributeSet::FunctionIndex,
285 AttributeSet::get(F->getContext(),
286 AttributeSet::FunctionIndex, B));
287
288 // Add in the new attribute.
289 F->addAttribute(AttributeSet::FunctionIndex,
290 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
291
292 if (ReadsMemory)
293 ++NumReadOnly;
294 else
295 ++NumReadNone;
296 }
297
298 return MadeChange;
299 }
300
301 namespace {
302 // For a given pointer Argument, this retains a list of Arguments of functions
303 // in the same SCC that the pointer data flows into. We use this to build an
304 // SCC of the arguments.
305 struct ArgumentGraphNode {
306 Argument *Definition;
307 SmallVector<ArgumentGraphNode*, 4> Uses;
308 };
309
310 class ArgumentGraph {
311 // We store pointers to ArgumentGraphNode objects, so it's important that
312 // that they not move around upon insert.
313 typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
314
315 ArgumentMapTy ArgumentMap;
316
317 // There is no root node for the argument graph, in fact:
318 // void f(int *x, int *y) { if (...) f(x, y); }
319 // is an example where the graph is disconnected. The SCCIterator requires a
320 // single entry point, so we maintain a fake ("synthetic") root node that
321 // uses every node. Because the graph is directed and nothing points into
322 // the root, it will not participate in any SCCs (except for its own).
323 ArgumentGraphNode SyntheticRoot;
324
325 public:
ArgumentGraph()326 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
327
328 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
329
begin()330 iterator begin() { return SyntheticRoot.Uses.begin(); }
end()331 iterator end() { return SyntheticRoot.Uses.end(); }
getEntryNode()332 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
333
operator [](Argument * A)334 ArgumentGraphNode *operator[](Argument *A) {
335 ArgumentGraphNode &Node = ArgumentMap[A];
336 Node.Definition = A;
337 SyntheticRoot.Uses.push_back(&Node);
338 return &Node;
339 }
340 };
341
342 // This tracker checks whether callees are in the SCC, and if so it does not
343 // consider that a capture, instead adding it to the "Uses" list and
344 // continuing with the analysis.
345 struct ArgumentUsesTracker : public CaptureTracker {
ArgumentUsesTracker__anon4eb4aa3b0211::ArgumentUsesTracker346 ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
347 : Captured(false), SCCNodes(SCCNodes) {}
348
tooManyUses__anon4eb4aa3b0211::ArgumentUsesTracker349 void tooManyUses() override { Captured = true; }
350
captured__anon4eb4aa3b0211::ArgumentUsesTracker351 bool captured(const Use *U) override {
352 CallSite CS(U->getUser());
353 if (!CS.getInstruction()) { Captured = true; return true; }
354
355 Function *F = CS.getCalledFunction();
356 if (!F || !SCCNodes.count(F)) { Captured = true; return true; }
357
358 bool Found = false;
359 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
360 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
361 PI != PE; ++PI, ++AI) {
362 if (AI == AE) {
363 assert(F->isVarArg() && "More params than args in non-varargs call");
364 Captured = true;
365 return true;
366 }
367 if (PI == U) {
368 Uses.push_back(AI);
369 Found = true;
370 break;
371 }
372 }
373 assert(Found && "Capturing call-site captured nothing?");
374 (void)Found;
375 return false;
376 }
377
378 bool Captured; // True only if certainly captured (used outside our SCC).
379 SmallVector<Argument*, 4> Uses; // Uses within our SCC.
380
381 const SmallPtrSet<Function*, 8> &SCCNodes;
382 };
383 }
384
385 namespace llvm {
386 template<> struct GraphTraits<ArgumentGraphNode*> {
387 typedef ArgumentGraphNode NodeType;
388 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorType;
389
getEntryNodellvm::GraphTraits390 static inline NodeType *getEntryNode(NodeType *A) { return A; }
child_beginllvm::GraphTraits391 static inline ChildIteratorType child_begin(NodeType *N) {
392 return N->Uses.begin();
393 }
child_endllvm::GraphTraits394 static inline ChildIteratorType child_end(NodeType *N) {
395 return N->Uses.end();
396 }
397 };
398 template<> struct GraphTraits<ArgumentGraph*>
399 : public GraphTraits<ArgumentGraphNode*> {
getEntryNodellvm::GraphTraits400 static NodeType *getEntryNode(ArgumentGraph *AG) {
401 return AG->getEntryNode();
402 }
nodes_beginllvm::GraphTraits403 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
404 return AG->begin();
405 }
nodes_endllvm::GraphTraits406 static ChildIteratorType nodes_end(ArgumentGraph *AG) {
407 return AG->end();
408 }
409 };
410 }
411
412 // Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
413 static Attribute::AttrKind
determinePointerReadAttrs(Argument * A,const SmallPtrSet<Argument *,8> & SCCNodes)414 determinePointerReadAttrs(Argument *A,
415 const SmallPtrSet<Argument*, 8> &SCCNodes) {
416
417 SmallVector<Use*, 32> Worklist;
418 SmallSet<Use*, 32> Visited;
419 int Count = 0;
420
421 // inalloca arguments are always clobbered by the call.
422 if (A->hasInAllocaAttr())
423 return Attribute::None;
424
425 bool IsRead = false;
426 // We don't need to track IsWritten. If A is written to, return immediately.
427
428 for (Use &U : A->uses()) {
429 if (Count++ >= 20)
430 return Attribute::None;
431
432 Visited.insert(&U);
433 Worklist.push_back(&U);
434 }
435
436 while (!Worklist.empty()) {
437 Use *U = Worklist.pop_back_val();
438 Instruction *I = cast<Instruction>(U->getUser());
439 Value *V = U->get();
440
441 switch (I->getOpcode()) {
442 case Instruction::BitCast:
443 case Instruction::GetElementPtr:
444 case Instruction::PHI:
445 case Instruction::Select:
446 case Instruction::AddrSpaceCast:
447 // The original value is not read/written via this if the new value isn't.
448 for (Use &UU : I->uses())
449 if (Visited.insert(&UU).second)
450 Worklist.push_back(&UU);
451 break;
452
453 case Instruction::Call:
454 case Instruction::Invoke: {
455 bool Captures = true;
456
457 if (I->getType()->isVoidTy())
458 Captures = false;
459
460 auto AddUsersToWorklistIfCapturing = [&] {
461 if (Captures)
462 for (Use &UU : I->uses())
463 if (Visited.insert(&UU).second)
464 Worklist.push_back(&UU);
465 };
466
467 CallSite CS(I);
468 if (CS.doesNotAccessMemory()) {
469 AddUsersToWorklistIfCapturing();
470 continue;
471 }
472
473 Function *F = CS.getCalledFunction();
474 if (!F) {
475 if (CS.onlyReadsMemory()) {
476 IsRead = true;
477 AddUsersToWorklistIfCapturing();
478 continue;
479 }
480 return Attribute::None;
481 }
482
483 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
484 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
485 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
486 if (A->get() == V) {
487 if (AI == AE) {
488 assert(F->isVarArg() &&
489 "More params than args in non-varargs call.");
490 return Attribute::None;
491 }
492 Captures &= !CS.doesNotCapture(A - B);
493 if (SCCNodes.count(AI))
494 continue;
495 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
496 return Attribute::None;
497 if (!CS.doesNotAccessMemory(A - B))
498 IsRead = true;
499 }
500 }
501 AddUsersToWorklistIfCapturing();
502 break;
503 }
504
505 case Instruction::Load:
506 IsRead = true;
507 break;
508
509 case Instruction::ICmp:
510 case Instruction::Ret:
511 break;
512
513 default:
514 return Attribute::None;
515 }
516 }
517
518 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
519 }
520
521 /// AddArgumentAttrs - Deduce nocapture attributes for the SCC.
AddArgumentAttrs(const CallGraphSCC & SCC)522 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
523 bool Changed = false;
524
525 SmallPtrSet<Function*, 8> SCCNodes;
526
527 // Fill SCCNodes with the elements of the SCC. Used for quickly
528 // looking up whether a given CallGraphNode is in this SCC.
529 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
530 Function *F = (*I)->getFunction();
531 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
532 !F->hasFnAttribute(Attribute::OptimizeNone))
533 SCCNodes.insert(F);
534 }
535
536 ArgumentGraph AG;
537
538 AttrBuilder B;
539 B.addAttribute(Attribute::NoCapture);
540
541 // Check each function in turn, determining which pointer arguments are not
542 // captured.
543 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
544 Function *F = (*I)->getFunction();
545
546 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
547 // External node or function we're trying not to optimize - only a problem
548 // for arguments that we pass to it.
549 continue;
550
551 // Definitions with weak linkage may be overridden at linktime with
552 // something that captures pointers, so treat them like declarations.
553 if (F->isDeclaration() || F->mayBeOverridden())
554 continue;
555
556 // Functions that are readonly (or readnone) and nounwind and don't return
557 // a value can't capture arguments. Don't analyze them.
558 if (F->onlyReadsMemory() && F->doesNotThrow() &&
559 F->getReturnType()->isVoidTy()) {
560 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
561 A != E; ++A) {
562 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
563 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
564 ++NumNoCapture;
565 Changed = true;
566 }
567 }
568 continue;
569 }
570
571 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
572 A != E; ++A) {
573 if (!A->getType()->isPointerTy()) continue;
574 bool HasNonLocalUses = false;
575 if (!A->hasNoCaptureAttr()) {
576 ArgumentUsesTracker Tracker(SCCNodes);
577 PointerMayBeCaptured(A, &Tracker);
578 if (!Tracker.Captured) {
579 if (Tracker.Uses.empty()) {
580 // If it's trivially not captured, mark it nocapture now.
581 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo()+1, B));
582 ++NumNoCapture;
583 Changed = true;
584 } else {
585 // If it's not trivially captured and not trivially not captured,
586 // then it must be calling into another function in our SCC. Save
587 // its particulars for Argument-SCC analysis later.
588 ArgumentGraphNode *Node = AG[A];
589 for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
590 UE = Tracker.Uses.end(); UI != UE; ++UI) {
591 Node->Uses.push_back(AG[*UI]);
592 if (*UI != A)
593 HasNonLocalUses = true;
594 }
595 }
596 }
597 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
598 }
599 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
600 // Can we determine that it's readonly/readnone without doing an SCC?
601 // Note that we don't allow any calls at all here, or else our result
602 // will be dependent on the iteration order through the functions in the
603 // SCC.
604 SmallPtrSet<Argument*, 8> Self;
605 Self.insert(A);
606 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
607 if (R != Attribute::None) {
608 AttrBuilder B;
609 B.addAttribute(R);
610 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
611 Changed = true;
612 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
613 }
614 }
615 }
616 }
617
618 // The graph we've collected is partial because we stopped scanning for
619 // argument uses once we solved the argument trivially. These partial nodes
620 // show up as ArgumentGraphNode objects with an empty Uses list, and for
621 // these nodes the final decision about whether they capture has already been
622 // made. If the definition doesn't have a 'nocapture' attribute by now, it
623 // captures.
624
625 for (scc_iterator<ArgumentGraph*> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
626 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
627 if (ArgumentSCC.size() == 1) {
628 if (!ArgumentSCC[0]->Definition) continue; // synthetic root node
629
630 // eg. "void f(int* x) { if (...) f(x); }"
631 if (ArgumentSCC[0]->Uses.size() == 1 &&
632 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
633 Argument *A = ArgumentSCC[0]->Definition;
634 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
635 ++NumNoCapture;
636 Changed = true;
637 }
638 continue;
639 }
640
641 bool SCCCaptured = false;
642 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
643 I != E && !SCCCaptured; ++I) {
644 ArgumentGraphNode *Node = *I;
645 if (Node->Uses.empty()) {
646 if (!Node->Definition->hasNoCaptureAttr())
647 SCCCaptured = true;
648 }
649 }
650 if (SCCCaptured) continue;
651
652 SmallPtrSet<Argument*, 8> ArgumentSCCNodes;
653 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
654 // quickly looking up whether a given Argument is in this ArgumentSCC.
655 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
656 ArgumentSCCNodes.insert((*I)->Definition);
657 }
658
659 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
660 I != E && !SCCCaptured; ++I) {
661 ArgumentGraphNode *N = *I;
662 for (SmallVectorImpl<ArgumentGraphNode*>::iterator UI = N->Uses.begin(),
663 UE = N->Uses.end(); UI != UE; ++UI) {
664 Argument *A = (*UI)->Definition;
665 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
666 continue;
667 SCCCaptured = true;
668 break;
669 }
670 }
671 if (SCCCaptured) continue;
672
673 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
674 Argument *A = ArgumentSCC[i]->Definition;
675 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
676 ++NumNoCapture;
677 Changed = true;
678 }
679
680 // We also want to compute readonly/readnone. With a small number of false
681 // negatives, we can assume that any pointer which is captured isn't going
682 // to be provably readonly or readnone, since by definition we can't
683 // analyze all uses of a captured pointer.
684 //
685 // The false negatives happen when the pointer is captured by a function
686 // that promises readonly/readnone behaviour on the pointer, then the
687 // pointer's lifetime ends before anything that writes to arbitrary memory.
688 // Also, a readonly/readnone pointer may be returned, but returning a
689 // pointer is capturing it.
690
691 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
692 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
693 Argument *A = ArgumentSCC[i]->Definition;
694 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
695 if (K == Attribute::ReadNone)
696 continue;
697 if (K == Attribute::ReadOnly) {
698 ReadAttr = Attribute::ReadOnly;
699 continue;
700 }
701 ReadAttr = K;
702 break;
703 }
704
705 if (ReadAttr != Attribute::None) {
706 AttrBuilder B;
707 B.addAttribute(ReadAttr);
708 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
709 Argument *A = ArgumentSCC[i]->Definition;
710 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
711 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
712 Changed = true;
713 }
714 }
715 }
716
717 return Changed;
718 }
719
720 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
721 /// or a pointer that doesn't alias any other pointer visible to the caller.
IsFunctionMallocLike(Function * F,SmallPtrSet<Function *,8> & SCCNodes) const722 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
723 SmallPtrSet<Function*, 8> &SCCNodes) const {
724 SmallSetVector<Value *, 8> FlowsToReturn;
725 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
726 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
727 FlowsToReturn.insert(Ret->getReturnValue());
728
729 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
730 Value *RetVal = FlowsToReturn[i];
731
732 if (Constant *C = dyn_cast<Constant>(RetVal)) {
733 if (!C->isNullValue() && !isa<UndefValue>(C))
734 return false;
735
736 continue;
737 }
738
739 if (isa<Argument>(RetVal))
740 return false;
741
742 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
743 switch (RVI->getOpcode()) {
744 // Extend the analysis by looking upwards.
745 case Instruction::BitCast:
746 case Instruction::GetElementPtr:
747 case Instruction::AddrSpaceCast:
748 FlowsToReturn.insert(RVI->getOperand(0));
749 continue;
750 case Instruction::Select: {
751 SelectInst *SI = cast<SelectInst>(RVI);
752 FlowsToReturn.insert(SI->getTrueValue());
753 FlowsToReturn.insert(SI->getFalseValue());
754 continue;
755 }
756 case Instruction::PHI: {
757 PHINode *PN = cast<PHINode>(RVI);
758 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
759 FlowsToReturn.insert(PN->getIncomingValue(i));
760 continue;
761 }
762
763 // Check whether the pointer came from an allocation.
764 case Instruction::Alloca:
765 break;
766 case Instruction::Call:
767 case Instruction::Invoke: {
768 CallSite CS(RVI);
769 if (CS.paramHasAttr(0, Attribute::NoAlias))
770 break;
771 if (CS.getCalledFunction() &&
772 SCCNodes.count(CS.getCalledFunction()))
773 break;
774 } // fall-through
775 default:
776 return false; // Did not come from an allocation.
777 }
778
779 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
780 return false;
781 }
782
783 return true;
784 }
785
786 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
AddNoAliasAttrs(const CallGraphSCC & SCC)787 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
788 SmallPtrSet<Function*, 8> SCCNodes;
789
790 // Fill SCCNodes with the elements of the SCC. Used for quickly
791 // looking up whether a given CallGraphNode is in this SCC.
792 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
793 SCCNodes.insert((*I)->getFunction());
794
795 // Check each function in turn, determining which functions return noalias
796 // pointers.
797 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
798 Function *F = (*I)->getFunction();
799
800 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
801 // External node or node we don't want to optimize - skip it;
802 return false;
803
804 // Already noalias.
805 if (F->doesNotAlias(0))
806 continue;
807
808 // Definitions with weak linkage may be overridden at linktime, so
809 // treat them like declarations.
810 if (F->isDeclaration() || F->mayBeOverridden())
811 return false;
812
813 // We annotate noalias return values, which are only applicable to
814 // pointer types.
815 if (!F->getReturnType()->isPointerTy())
816 continue;
817
818 if (!IsFunctionMallocLike(F, SCCNodes))
819 return false;
820 }
821
822 bool MadeChange = false;
823 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
824 Function *F = (*I)->getFunction();
825 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
826 continue;
827
828 F->setDoesNotAlias(0);
829 ++NumNoAlias;
830 MadeChange = true;
831 }
832
833 return MadeChange;
834 }
835
836 /// inferPrototypeAttributes - Analyze the name and prototype of the
837 /// given function and set any applicable attributes. Returns true
838 /// if any attributes were set and false otherwise.
inferPrototypeAttributes(Function & F)839 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
840 if (F.hasFnAttribute(Attribute::OptimizeNone))
841 return false;
842
843 FunctionType *FTy = F.getFunctionType();
844 LibFunc::Func TheLibFunc;
845 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
846 return false;
847
848 switch (TheLibFunc) {
849 case LibFunc::strlen:
850 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
851 return false;
852 setOnlyReadsMemory(F);
853 setDoesNotThrow(F);
854 setDoesNotCapture(F, 1);
855 break;
856 case LibFunc::strchr:
857 case LibFunc::strrchr:
858 if (FTy->getNumParams() != 2 ||
859 !FTy->getParamType(0)->isPointerTy() ||
860 !FTy->getParamType(1)->isIntegerTy())
861 return false;
862 setOnlyReadsMemory(F);
863 setDoesNotThrow(F);
864 break;
865 case LibFunc::strtol:
866 case LibFunc::strtod:
867 case LibFunc::strtof:
868 case LibFunc::strtoul:
869 case LibFunc::strtoll:
870 case LibFunc::strtold:
871 case LibFunc::strtoull:
872 if (FTy->getNumParams() < 2 ||
873 !FTy->getParamType(1)->isPointerTy())
874 return false;
875 setDoesNotThrow(F);
876 setDoesNotCapture(F, 2);
877 setOnlyReadsMemory(F, 1);
878 break;
879 case LibFunc::strcpy:
880 case LibFunc::stpcpy:
881 case LibFunc::strcat:
882 case LibFunc::strncat:
883 case LibFunc::strncpy:
884 case LibFunc::stpncpy:
885 if (FTy->getNumParams() < 2 ||
886 !FTy->getParamType(1)->isPointerTy())
887 return false;
888 setDoesNotThrow(F);
889 setDoesNotCapture(F, 2);
890 setOnlyReadsMemory(F, 2);
891 break;
892 case LibFunc::strxfrm:
893 if (FTy->getNumParams() != 3 ||
894 !FTy->getParamType(0)->isPointerTy() ||
895 !FTy->getParamType(1)->isPointerTy())
896 return false;
897 setDoesNotThrow(F);
898 setDoesNotCapture(F, 1);
899 setDoesNotCapture(F, 2);
900 setOnlyReadsMemory(F, 2);
901 break;
902 case LibFunc::strcmp: //0,1
903 case LibFunc::strspn: // 0,1
904 case LibFunc::strncmp: // 0,1
905 case LibFunc::strcspn: //0,1
906 case LibFunc::strcoll: //0,1
907 case LibFunc::strcasecmp: // 0,1
908 case LibFunc::strncasecmp: //
909 if (FTy->getNumParams() < 2 ||
910 !FTy->getParamType(0)->isPointerTy() ||
911 !FTy->getParamType(1)->isPointerTy())
912 return false;
913 setOnlyReadsMemory(F);
914 setDoesNotThrow(F);
915 setDoesNotCapture(F, 1);
916 setDoesNotCapture(F, 2);
917 break;
918 case LibFunc::strstr:
919 case LibFunc::strpbrk:
920 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
921 return false;
922 setOnlyReadsMemory(F);
923 setDoesNotThrow(F);
924 setDoesNotCapture(F, 2);
925 break;
926 case LibFunc::strtok:
927 case LibFunc::strtok_r:
928 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
929 return false;
930 setDoesNotThrow(F);
931 setDoesNotCapture(F, 2);
932 setOnlyReadsMemory(F, 2);
933 break;
934 case LibFunc::scanf:
935 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
936 return false;
937 setDoesNotThrow(F);
938 setDoesNotCapture(F, 1);
939 setOnlyReadsMemory(F, 1);
940 break;
941 case LibFunc::setbuf:
942 case LibFunc::setvbuf:
943 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
944 return false;
945 setDoesNotThrow(F);
946 setDoesNotCapture(F, 1);
947 break;
948 case LibFunc::strdup:
949 case LibFunc::strndup:
950 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
951 !FTy->getParamType(0)->isPointerTy())
952 return false;
953 setDoesNotThrow(F);
954 setDoesNotAlias(F, 0);
955 setDoesNotCapture(F, 1);
956 setOnlyReadsMemory(F, 1);
957 break;
958 case LibFunc::stat:
959 case LibFunc::statvfs:
960 if (FTy->getNumParams() < 2 ||
961 !FTy->getParamType(0)->isPointerTy() ||
962 !FTy->getParamType(1)->isPointerTy())
963 return false;
964 setDoesNotThrow(F);
965 setDoesNotCapture(F, 1);
966 setDoesNotCapture(F, 2);
967 setOnlyReadsMemory(F, 1);
968 break;
969 case LibFunc::sscanf:
970 if (FTy->getNumParams() < 2 ||
971 !FTy->getParamType(0)->isPointerTy() ||
972 !FTy->getParamType(1)->isPointerTy())
973 return false;
974 setDoesNotThrow(F);
975 setDoesNotCapture(F, 1);
976 setDoesNotCapture(F, 2);
977 setOnlyReadsMemory(F, 1);
978 setOnlyReadsMemory(F, 2);
979 break;
980 case LibFunc::sprintf:
981 if (FTy->getNumParams() < 2 ||
982 !FTy->getParamType(0)->isPointerTy() ||
983 !FTy->getParamType(1)->isPointerTy())
984 return false;
985 setDoesNotThrow(F);
986 setDoesNotCapture(F, 1);
987 setDoesNotCapture(F, 2);
988 setOnlyReadsMemory(F, 2);
989 break;
990 case LibFunc::snprintf:
991 if (FTy->getNumParams() != 3 ||
992 !FTy->getParamType(0)->isPointerTy() ||
993 !FTy->getParamType(2)->isPointerTy())
994 return false;
995 setDoesNotThrow(F);
996 setDoesNotCapture(F, 1);
997 setDoesNotCapture(F, 3);
998 setOnlyReadsMemory(F, 3);
999 break;
1000 case LibFunc::setitimer:
1001 if (FTy->getNumParams() != 3 ||
1002 !FTy->getParamType(1)->isPointerTy() ||
1003 !FTy->getParamType(2)->isPointerTy())
1004 return false;
1005 setDoesNotThrow(F);
1006 setDoesNotCapture(F, 2);
1007 setDoesNotCapture(F, 3);
1008 setOnlyReadsMemory(F, 2);
1009 break;
1010 case LibFunc::system:
1011 if (FTy->getNumParams() != 1 ||
1012 !FTy->getParamType(0)->isPointerTy())
1013 return false;
1014 // May throw; "system" is a valid pthread cancellation point.
1015 setDoesNotCapture(F, 1);
1016 setOnlyReadsMemory(F, 1);
1017 break;
1018 case LibFunc::malloc:
1019 if (FTy->getNumParams() != 1 ||
1020 !FTy->getReturnType()->isPointerTy())
1021 return false;
1022 setDoesNotThrow(F);
1023 setDoesNotAlias(F, 0);
1024 break;
1025 case LibFunc::memcmp:
1026 if (FTy->getNumParams() != 3 ||
1027 !FTy->getParamType(0)->isPointerTy() ||
1028 !FTy->getParamType(1)->isPointerTy())
1029 return false;
1030 setOnlyReadsMemory(F);
1031 setDoesNotThrow(F);
1032 setDoesNotCapture(F, 1);
1033 setDoesNotCapture(F, 2);
1034 break;
1035 case LibFunc::memchr:
1036 case LibFunc::memrchr:
1037 if (FTy->getNumParams() != 3)
1038 return false;
1039 setOnlyReadsMemory(F);
1040 setDoesNotThrow(F);
1041 break;
1042 case LibFunc::modf:
1043 case LibFunc::modff:
1044 case LibFunc::modfl:
1045 if (FTy->getNumParams() < 2 ||
1046 !FTy->getParamType(1)->isPointerTy())
1047 return false;
1048 setDoesNotThrow(F);
1049 setDoesNotCapture(F, 2);
1050 break;
1051 case LibFunc::memcpy:
1052 case LibFunc::memccpy:
1053 case LibFunc::memmove:
1054 if (FTy->getNumParams() < 2 ||
1055 !FTy->getParamType(1)->isPointerTy())
1056 return false;
1057 setDoesNotThrow(F);
1058 setDoesNotCapture(F, 2);
1059 setOnlyReadsMemory(F, 2);
1060 break;
1061 case LibFunc::memalign:
1062 if (!FTy->getReturnType()->isPointerTy())
1063 return false;
1064 setDoesNotAlias(F, 0);
1065 break;
1066 case LibFunc::mkdir:
1067 if (FTy->getNumParams() == 0 ||
1068 !FTy->getParamType(0)->isPointerTy())
1069 return false;
1070 setDoesNotThrow(F);
1071 setDoesNotCapture(F, 1);
1072 setOnlyReadsMemory(F, 1);
1073 break;
1074 case LibFunc::mktime:
1075 if (FTy->getNumParams() == 0 ||
1076 !FTy->getParamType(0)->isPointerTy())
1077 return false;
1078 setDoesNotThrow(F);
1079 setDoesNotCapture(F, 1);
1080 break;
1081 case LibFunc::realloc:
1082 if (FTy->getNumParams() != 2 ||
1083 !FTy->getParamType(0)->isPointerTy() ||
1084 !FTy->getReturnType()->isPointerTy())
1085 return false;
1086 setDoesNotThrow(F);
1087 setDoesNotAlias(F, 0);
1088 setDoesNotCapture(F, 1);
1089 break;
1090 case LibFunc::read:
1091 if (FTy->getNumParams() != 3 ||
1092 !FTy->getParamType(1)->isPointerTy())
1093 return false;
1094 // May throw; "read" is a valid pthread cancellation point.
1095 setDoesNotCapture(F, 2);
1096 break;
1097 case LibFunc::rewind:
1098 if (FTy->getNumParams() < 1 ||
1099 !FTy->getParamType(0)->isPointerTy())
1100 return false;
1101 setDoesNotThrow(F);
1102 setDoesNotCapture(F, 1);
1103 break;
1104 case LibFunc::rmdir:
1105 case LibFunc::remove:
1106 case LibFunc::realpath:
1107 if (FTy->getNumParams() < 1 ||
1108 !FTy->getParamType(0)->isPointerTy())
1109 return false;
1110 setDoesNotThrow(F);
1111 setDoesNotCapture(F, 1);
1112 setOnlyReadsMemory(F, 1);
1113 break;
1114 case LibFunc::rename:
1115 if (FTy->getNumParams() < 2 ||
1116 !FTy->getParamType(0)->isPointerTy() ||
1117 !FTy->getParamType(1)->isPointerTy())
1118 return false;
1119 setDoesNotThrow(F);
1120 setDoesNotCapture(F, 1);
1121 setDoesNotCapture(F, 2);
1122 setOnlyReadsMemory(F, 1);
1123 setOnlyReadsMemory(F, 2);
1124 break;
1125 case LibFunc::readlink:
1126 if (FTy->getNumParams() < 2 ||
1127 !FTy->getParamType(0)->isPointerTy() ||
1128 !FTy->getParamType(1)->isPointerTy())
1129 return false;
1130 setDoesNotThrow(F);
1131 setDoesNotCapture(F, 1);
1132 setDoesNotCapture(F, 2);
1133 setOnlyReadsMemory(F, 1);
1134 break;
1135 case LibFunc::write:
1136 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1137 return false;
1138 // May throw; "write" is a valid pthread cancellation point.
1139 setDoesNotCapture(F, 2);
1140 setOnlyReadsMemory(F, 2);
1141 break;
1142 case LibFunc::bcopy:
1143 if (FTy->getNumParams() != 3 ||
1144 !FTy->getParamType(0)->isPointerTy() ||
1145 !FTy->getParamType(1)->isPointerTy())
1146 return false;
1147 setDoesNotThrow(F);
1148 setDoesNotCapture(F, 1);
1149 setDoesNotCapture(F, 2);
1150 setOnlyReadsMemory(F, 1);
1151 break;
1152 case LibFunc::bcmp:
1153 if (FTy->getNumParams() != 3 ||
1154 !FTy->getParamType(0)->isPointerTy() ||
1155 !FTy->getParamType(1)->isPointerTy())
1156 return false;
1157 setDoesNotThrow(F);
1158 setOnlyReadsMemory(F);
1159 setDoesNotCapture(F, 1);
1160 setDoesNotCapture(F, 2);
1161 break;
1162 case LibFunc::bzero:
1163 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1164 return false;
1165 setDoesNotThrow(F);
1166 setDoesNotCapture(F, 1);
1167 break;
1168 case LibFunc::calloc:
1169 if (FTy->getNumParams() != 2 ||
1170 !FTy->getReturnType()->isPointerTy())
1171 return false;
1172 setDoesNotThrow(F);
1173 setDoesNotAlias(F, 0);
1174 break;
1175 case LibFunc::chmod:
1176 case LibFunc::chown:
1177 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1178 return false;
1179 setDoesNotThrow(F);
1180 setDoesNotCapture(F, 1);
1181 setOnlyReadsMemory(F, 1);
1182 break;
1183 case LibFunc::ctermid:
1184 case LibFunc::clearerr:
1185 case LibFunc::closedir:
1186 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1187 return false;
1188 setDoesNotThrow(F);
1189 setDoesNotCapture(F, 1);
1190 break;
1191 case LibFunc::atoi:
1192 case LibFunc::atol:
1193 case LibFunc::atof:
1194 case LibFunc::atoll:
1195 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1196 return false;
1197 setDoesNotThrow(F);
1198 setOnlyReadsMemory(F);
1199 setDoesNotCapture(F, 1);
1200 break;
1201 case LibFunc::access:
1202 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1203 return false;
1204 setDoesNotThrow(F);
1205 setDoesNotCapture(F, 1);
1206 setOnlyReadsMemory(F, 1);
1207 break;
1208 case LibFunc::fopen:
1209 if (FTy->getNumParams() != 2 ||
1210 !FTy->getReturnType()->isPointerTy() ||
1211 !FTy->getParamType(0)->isPointerTy() ||
1212 !FTy->getParamType(1)->isPointerTy())
1213 return false;
1214 setDoesNotThrow(F);
1215 setDoesNotAlias(F, 0);
1216 setDoesNotCapture(F, 1);
1217 setDoesNotCapture(F, 2);
1218 setOnlyReadsMemory(F, 1);
1219 setOnlyReadsMemory(F, 2);
1220 break;
1221 case LibFunc::fdopen:
1222 if (FTy->getNumParams() != 2 ||
1223 !FTy->getReturnType()->isPointerTy() ||
1224 !FTy->getParamType(1)->isPointerTy())
1225 return false;
1226 setDoesNotThrow(F);
1227 setDoesNotAlias(F, 0);
1228 setDoesNotCapture(F, 2);
1229 setOnlyReadsMemory(F, 2);
1230 break;
1231 case LibFunc::feof:
1232 case LibFunc::free:
1233 case LibFunc::fseek:
1234 case LibFunc::ftell:
1235 case LibFunc::fgetc:
1236 case LibFunc::fseeko:
1237 case LibFunc::ftello:
1238 case LibFunc::fileno:
1239 case LibFunc::fflush:
1240 case LibFunc::fclose:
1241 case LibFunc::fsetpos:
1242 case LibFunc::flockfile:
1243 case LibFunc::funlockfile:
1244 case LibFunc::ftrylockfile:
1245 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1246 return false;
1247 setDoesNotThrow(F);
1248 setDoesNotCapture(F, 1);
1249 break;
1250 case LibFunc::ferror:
1251 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1252 return false;
1253 setDoesNotThrow(F);
1254 setDoesNotCapture(F, 1);
1255 setOnlyReadsMemory(F);
1256 break;
1257 case LibFunc::fputc:
1258 case LibFunc::fstat:
1259 case LibFunc::frexp:
1260 case LibFunc::frexpf:
1261 case LibFunc::frexpl:
1262 case LibFunc::fstatvfs:
1263 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1264 return false;
1265 setDoesNotThrow(F);
1266 setDoesNotCapture(F, 2);
1267 break;
1268 case LibFunc::fgets:
1269 if (FTy->getNumParams() != 3 ||
1270 !FTy->getParamType(0)->isPointerTy() ||
1271 !FTy->getParamType(2)->isPointerTy())
1272 return false;
1273 setDoesNotThrow(F);
1274 setDoesNotCapture(F, 3);
1275 break;
1276 case LibFunc::fread:
1277 if (FTy->getNumParams() != 4 ||
1278 !FTy->getParamType(0)->isPointerTy() ||
1279 !FTy->getParamType(3)->isPointerTy())
1280 return false;
1281 setDoesNotThrow(F);
1282 setDoesNotCapture(F, 1);
1283 setDoesNotCapture(F, 4);
1284 break;
1285 case LibFunc::fwrite:
1286 if (FTy->getNumParams() != 4 ||
1287 !FTy->getParamType(0)->isPointerTy() ||
1288 !FTy->getParamType(3)->isPointerTy())
1289 return false;
1290 setDoesNotThrow(F);
1291 setDoesNotCapture(F, 1);
1292 setDoesNotCapture(F, 4);
1293 break;
1294 case LibFunc::fputs:
1295 if (FTy->getNumParams() < 2 ||
1296 !FTy->getParamType(0)->isPointerTy() ||
1297 !FTy->getParamType(1)->isPointerTy())
1298 return false;
1299 setDoesNotThrow(F);
1300 setDoesNotCapture(F, 1);
1301 setDoesNotCapture(F, 2);
1302 setOnlyReadsMemory(F, 1);
1303 break;
1304 case LibFunc::fscanf:
1305 case LibFunc::fprintf:
1306 if (FTy->getNumParams() < 2 ||
1307 !FTy->getParamType(0)->isPointerTy() ||
1308 !FTy->getParamType(1)->isPointerTy())
1309 return false;
1310 setDoesNotThrow(F);
1311 setDoesNotCapture(F, 1);
1312 setDoesNotCapture(F, 2);
1313 setOnlyReadsMemory(F, 2);
1314 break;
1315 case LibFunc::fgetpos:
1316 if (FTy->getNumParams() < 2 ||
1317 !FTy->getParamType(0)->isPointerTy() ||
1318 !FTy->getParamType(1)->isPointerTy())
1319 return false;
1320 setDoesNotThrow(F);
1321 setDoesNotCapture(F, 1);
1322 setDoesNotCapture(F, 2);
1323 break;
1324 case LibFunc::getc:
1325 case LibFunc::getlogin_r:
1326 case LibFunc::getc_unlocked:
1327 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1328 return false;
1329 setDoesNotThrow(F);
1330 setDoesNotCapture(F, 1);
1331 break;
1332 case LibFunc::getenv:
1333 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1334 return false;
1335 setDoesNotThrow(F);
1336 setOnlyReadsMemory(F);
1337 setDoesNotCapture(F, 1);
1338 break;
1339 case LibFunc::gets:
1340 case LibFunc::getchar:
1341 setDoesNotThrow(F);
1342 break;
1343 case LibFunc::getitimer:
1344 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1345 return false;
1346 setDoesNotThrow(F);
1347 setDoesNotCapture(F, 2);
1348 break;
1349 case LibFunc::getpwnam:
1350 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1351 return false;
1352 setDoesNotThrow(F);
1353 setDoesNotCapture(F, 1);
1354 setOnlyReadsMemory(F, 1);
1355 break;
1356 case LibFunc::ungetc:
1357 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1358 return false;
1359 setDoesNotThrow(F);
1360 setDoesNotCapture(F, 2);
1361 break;
1362 case LibFunc::uname:
1363 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1364 return false;
1365 setDoesNotThrow(F);
1366 setDoesNotCapture(F, 1);
1367 break;
1368 case LibFunc::unlink:
1369 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1370 return false;
1371 setDoesNotThrow(F);
1372 setDoesNotCapture(F, 1);
1373 setOnlyReadsMemory(F, 1);
1374 break;
1375 case LibFunc::unsetenv:
1376 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1377 return false;
1378 setDoesNotThrow(F);
1379 setDoesNotCapture(F, 1);
1380 setOnlyReadsMemory(F, 1);
1381 break;
1382 case LibFunc::utime:
1383 case LibFunc::utimes:
1384 if (FTy->getNumParams() != 2 ||
1385 !FTy->getParamType(0)->isPointerTy() ||
1386 !FTy->getParamType(1)->isPointerTy())
1387 return false;
1388 setDoesNotThrow(F);
1389 setDoesNotCapture(F, 1);
1390 setDoesNotCapture(F, 2);
1391 setOnlyReadsMemory(F, 1);
1392 setOnlyReadsMemory(F, 2);
1393 break;
1394 case LibFunc::putc:
1395 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1396 return false;
1397 setDoesNotThrow(F);
1398 setDoesNotCapture(F, 2);
1399 break;
1400 case LibFunc::puts:
1401 case LibFunc::printf:
1402 case LibFunc::perror:
1403 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1404 return false;
1405 setDoesNotThrow(F);
1406 setDoesNotCapture(F, 1);
1407 setOnlyReadsMemory(F, 1);
1408 break;
1409 case LibFunc::pread:
1410 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1411 return false;
1412 // May throw; "pread" is a valid pthread cancellation point.
1413 setDoesNotCapture(F, 2);
1414 break;
1415 case LibFunc::pwrite:
1416 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1417 return false;
1418 // May throw; "pwrite" is a valid pthread cancellation point.
1419 setDoesNotCapture(F, 2);
1420 setOnlyReadsMemory(F, 2);
1421 break;
1422 case LibFunc::putchar:
1423 setDoesNotThrow(F);
1424 break;
1425 case LibFunc::popen:
1426 if (FTy->getNumParams() != 2 ||
1427 !FTy->getReturnType()->isPointerTy() ||
1428 !FTy->getParamType(0)->isPointerTy() ||
1429 !FTy->getParamType(1)->isPointerTy())
1430 return false;
1431 setDoesNotThrow(F);
1432 setDoesNotAlias(F, 0);
1433 setDoesNotCapture(F, 1);
1434 setDoesNotCapture(F, 2);
1435 setOnlyReadsMemory(F, 1);
1436 setOnlyReadsMemory(F, 2);
1437 break;
1438 case LibFunc::pclose:
1439 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1440 return false;
1441 setDoesNotThrow(F);
1442 setDoesNotCapture(F, 1);
1443 break;
1444 case LibFunc::vscanf:
1445 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1446 return false;
1447 setDoesNotThrow(F);
1448 setDoesNotCapture(F, 1);
1449 setOnlyReadsMemory(F, 1);
1450 break;
1451 case LibFunc::vsscanf:
1452 if (FTy->getNumParams() != 3 ||
1453 !FTy->getParamType(1)->isPointerTy() ||
1454 !FTy->getParamType(2)->isPointerTy())
1455 return false;
1456 setDoesNotThrow(F);
1457 setDoesNotCapture(F, 1);
1458 setDoesNotCapture(F, 2);
1459 setOnlyReadsMemory(F, 1);
1460 setOnlyReadsMemory(F, 2);
1461 break;
1462 case LibFunc::vfscanf:
1463 if (FTy->getNumParams() != 3 ||
1464 !FTy->getParamType(1)->isPointerTy() ||
1465 !FTy->getParamType(2)->isPointerTy())
1466 return false;
1467 setDoesNotThrow(F);
1468 setDoesNotCapture(F, 1);
1469 setDoesNotCapture(F, 2);
1470 setOnlyReadsMemory(F, 2);
1471 break;
1472 case LibFunc::valloc:
1473 if (!FTy->getReturnType()->isPointerTy())
1474 return false;
1475 setDoesNotThrow(F);
1476 setDoesNotAlias(F, 0);
1477 break;
1478 case LibFunc::vprintf:
1479 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1480 return false;
1481 setDoesNotThrow(F);
1482 setDoesNotCapture(F, 1);
1483 setOnlyReadsMemory(F, 1);
1484 break;
1485 case LibFunc::vfprintf:
1486 case LibFunc::vsprintf:
1487 if (FTy->getNumParams() != 3 ||
1488 !FTy->getParamType(0)->isPointerTy() ||
1489 !FTy->getParamType(1)->isPointerTy())
1490 return false;
1491 setDoesNotThrow(F);
1492 setDoesNotCapture(F, 1);
1493 setDoesNotCapture(F, 2);
1494 setOnlyReadsMemory(F, 2);
1495 break;
1496 case LibFunc::vsnprintf:
1497 if (FTy->getNumParams() != 4 ||
1498 !FTy->getParamType(0)->isPointerTy() ||
1499 !FTy->getParamType(2)->isPointerTy())
1500 return false;
1501 setDoesNotThrow(F);
1502 setDoesNotCapture(F, 1);
1503 setDoesNotCapture(F, 3);
1504 setOnlyReadsMemory(F, 3);
1505 break;
1506 case LibFunc::open:
1507 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1508 return false;
1509 // May throw; "open" is a valid pthread cancellation point.
1510 setDoesNotCapture(F, 1);
1511 setOnlyReadsMemory(F, 1);
1512 break;
1513 case LibFunc::opendir:
1514 if (FTy->getNumParams() != 1 ||
1515 !FTy->getReturnType()->isPointerTy() ||
1516 !FTy->getParamType(0)->isPointerTy())
1517 return false;
1518 setDoesNotThrow(F);
1519 setDoesNotAlias(F, 0);
1520 setDoesNotCapture(F, 1);
1521 setOnlyReadsMemory(F, 1);
1522 break;
1523 case LibFunc::tmpfile:
1524 if (!FTy->getReturnType()->isPointerTy())
1525 return false;
1526 setDoesNotThrow(F);
1527 setDoesNotAlias(F, 0);
1528 break;
1529 case LibFunc::times:
1530 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1531 return false;
1532 setDoesNotThrow(F);
1533 setDoesNotCapture(F, 1);
1534 break;
1535 case LibFunc::htonl:
1536 case LibFunc::htons:
1537 case LibFunc::ntohl:
1538 case LibFunc::ntohs:
1539 setDoesNotThrow(F);
1540 setDoesNotAccessMemory(F);
1541 break;
1542 case LibFunc::lstat:
1543 if (FTy->getNumParams() != 2 ||
1544 !FTy->getParamType(0)->isPointerTy() ||
1545 !FTy->getParamType(1)->isPointerTy())
1546 return false;
1547 setDoesNotThrow(F);
1548 setDoesNotCapture(F, 1);
1549 setDoesNotCapture(F, 2);
1550 setOnlyReadsMemory(F, 1);
1551 break;
1552 case LibFunc::lchown:
1553 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1554 return false;
1555 setDoesNotThrow(F);
1556 setDoesNotCapture(F, 1);
1557 setOnlyReadsMemory(F, 1);
1558 break;
1559 case LibFunc::qsort:
1560 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1561 return false;
1562 // May throw; places call through function pointer.
1563 setDoesNotCapture(F, 4);
1564 break;
1565 case LibFunc::dunder_strdup:
1566 case LibFunc::dunder_strndup:
1567 if (FTy->getNumParams() < 1 ||
1568 !FTy->getReturnType()->isPointerTy() ||
1569 !FTy->getParamType(0)->isPointerTy())
1570 return false;
1571 setDoesNotThrow(F);
1572 setDoesNotAlias(F, 0);
1573 setDoesNotCapture(F, 1);
1574 setOnlyReadsMemory(F, 1);
1575 break;
1576 case LibFunc::dunder_strtok_r:
1577 if (FTy->getNumParams() != 3 ||
1578 !FTy->getParamType(1)->isPointerTy())
1579 return false;
1580 setDoesNotThrow(F);
1581 setDoesNotCapture(F, 2);
1582 setOnlyReadsMemory(F, 2);
1583 break;
1584 case LibFunc::under_IO_getc:
1585 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1586 return false;
1587 setDoesNotThrow(F);
1588 setDoesNotCapture(F, 1);
1589 break;
1590 case LibFunc::under_IO_putc:
1591 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1592 return false;
1593 setDoesNotThrow(F);
1594 setDoesNotCapture(F, 2);
1595 break;
1596 case LibFunc::dunder_isoc99_scanf:
1597 if (FTy->getNumParams() < 1 ||
1598 !FTy->getParamType(0)->isPointerTy())
1599 return false;
1600 setDoesNotThrow(F);
1601 setDoesNotCapture(F, 1);
1602 setOnlyReadsMemory(F, 1);
1603 break;
1604 case LibFunc::stat64:
1605 case LibFunc::lstat64:
1606 case LibFunc::statvfs64:
1607 if (FTy->getNumParams() < 1 ||
1608 !FTy->getParamType(0)->isPointerTy() ||
1609 !FTy->getParamType(1)->isPointerTy())
1610 return false;
1611 setDoesNotThrow(F);
1612 setDoesNotCapture(F, 1);
1613 setDoesNotCapture(F, 2);
1614 setOnlyReadsMemory(F, 1);
1615 break;
1616 case LibFunc::dunder_isoc99_sscanf:
1617 if (FTy->getNumParams() < 1 ||
1618 !FTy->getParamType(0)->isPointerTy() ||
1619 !FTy->getParamType(1)->isPointerTy())
1620 return false;
1621 setDoesNotThrow(F);
1622 setDoesNotCapture(F, 1);
1623 setDoesNotCapture(F, 2);
1624 setOnlyReadsMemory(F, 1);
1625 setOnlyReadsMemory(F, 2);
1626 break;
1627 case LibFunc::fopen64:
1628 if (FTy->getNumParams() != 2 ||
1629 !FTy->getReturnType()->isPointerTy() ||
1630 !FTy->getParamType(0)->isPointerTy() ||
1631 !FTy->getParamType(1)->isPointerTy())
1632 return false;
1633 setDoesNotThrow(F);
1634 setDoesNotAlias(F, 0);
1635 setDoesNotCapture(F, 1);
1636 setDoesNotCapture(F, 2);
1637 setOnlyReadsMemory(F, 1);
1638 setOnlyReadsMemory(F, 2);
1639 break;
1640 case LibFunc::fseeko64:
1641 case LibFunc::ftello64:
1642 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1643 return false;
1644 setDoesNotThrow(F);
1645 setDoesNotCapture(F, 1);
1646 break;
1647 case LibFunc::tmpfile64:
1648 if (!FTy->getReturnType()->isPointerTy())
1649 return false;
1650 setDoesNotThrow(F);
1651 setDoesNotAlias(F, 0);
1652 break;
1653 case LibFunc::fstat64:
1654 case LibFunc::fstatvfs64:
1655 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1656 return false;
1657 setDoesNotThrow(F);
1658 setDoesNotCapture(F, 2);
1659 break;
1660 case LibFunc::open64:
1661 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1662 return false;
1663 // May throw; "open" is a valid pthread cancellation point.
1664 setDoesNotCapture(F, 1);
1665 setOnlyReadsMemory(F, 1);
1666 break;
1667 case LibFunc::gettimeofday:
1668 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1669 !FTy->getParamType(1)->isPointerTy())
1670 return false;
1671 // Currently some platforms have the restrict keyword on the arguments to
1672 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1673 // arguments.
1674 setDoesNotThrow(F);
1675 setDoesNotCapture(F, 1);
1676 setDoesNotCapture(F, 2);
1677 break;
1678 default:
1679 // Didn't mark any attributes.
1680 return false;
1681 }
1682
1683 return true;
1684 }
1685
1686 /// annotateLibraryCalls - Adds attributes to well-known standard library
1687 /// call declarations.
annotateLibraryCalls(const CallGraphSCC & SCC)1688 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1689 bool MadeChange = false;
1690
1691 // Check each function in turn annotating well-known library function
1692 // declarations with attributes.
1693 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1694 Function *F = (*I)->getFunction();
1695
1696 if (F && F->isDeclaration())
1697 MadeChange |= inferPrototypeAttributes(*F);
1698 }
1699
1700 return MadeChange;
1701 }
1702
runOnSCC(CallGraphSCC & SCC)1703 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1704 AA = &getAnalysis<AliasAnalysis>();
1705 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1706
1707 bool Changed = annotateLibraryCalls(SCC);
1708 Changed |= AddReadAttrs(SCC);
1709 Changed |= AddArgumentAttrs(SCC);
1710 Changed |= AddNoAliasAttrs(SCC);
1711 return Changed;
1712 }
1713