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