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