1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file implements interprocedural passes which walk the
11 /// call-graph deducing and/or propagating function attributes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/FunctionAttrs.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AssumptionCache.h"
26 #include "llvm/Analysis/BasicAliasAnalysis.h"
27 #include "llvm/Analysis/CFG.h"
28 #include "llvm/Analysis/CGSCCPassManager.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/CallGraphSCCPass.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/LazyCallGraph.h"
33 #include "llvm/Analysis/MemoryBuiltins.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/IR/Argument.h"
37 #include "llvm/IR/Attributes.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/InstIterator.h"
43 #include "llvm/IR/InstrTypes.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/PassManager.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/IR/Use.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Transforms/IPO.h"
62 #include "llvm/Transforms/Utils/Local.h"
63 #include <cassert>
64 #include <iterator>
65 #include <map>
66 #include <vector>
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "function-attrs"
71 
72 STATISTIC(NumReadNone, "Number of functions marked readnone");
73 STATISTIC(NumReadOnly, "Number of functions marked readonly");
74 STATISTIC(NumWriteOnly, "Number of functions marked writeonly");
75 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
76 STATISTIC(NumReturned, "Number of arguments marked returned");
77 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
78 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
79 STATISTIC(NumWriteOnlyArg, "Number of arguments marked writeonly");
80 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
81 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
82 STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
83 STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
84 STATISTIC(NumNoFree, "Number of functions marked as nofree");
85 STATISTIC(NumWillReturn, "Number of functions marked as willreturn");
86 STATISTIC(NumNoSync, "Number of functions marked as nosync");
87 
88 STATISTIC(NumThinLinkNoRecurse,
89           "Number of functions marked as norecurse during thinlink");
90 STATISTIC(NumThinLinkNoUnwind,
91           "Number of functions marked as nounwind during thinlink");
92 
93 static cl::opt<bool> EnableNonnullArgPropagation(
94     "enable-nonnull-arg-prop", cl::init(true), cl::Hidden,
95     cl::desc("Try to propagate nonnull argument attributes from callsites to "
96              "caller functions."));
97 
98 static cl::opt<bool> DisableNoUnwindInference(
99     "disable-nounwind-inference", cl::Hidden,
100     cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
101 
102 static cl::opt<bool> DisableNoFreeInference(
103     "disable-nofree-inference", cl::Hidden,
104     cl::desc("Stop inferring nofree attribute during function-attrs pass"));
105 
106 static cl::opt<bool> DisableThinLTOPropagation(
107     "disable-thinlto-funcattrs", cl::init(true), cl::Hidden,
108     cl::desc("Don't propagate function-attrs in thinLTO"));
109 
110 namespace {
111 
112 using SCCNodeSet = SmallSetVector<Function *, 8>;
113 
114 } // end anonymous namespace
115 
116 /// Returns the memory access attribute for function F using AAR for AA results,
117 /// where SCCNodes is the current SCC.
118 ///
119 /// If ThisBody is true, this function may examine the function body and will
120 /// return a result pertaining to this copy of the function. If it is false, the
121 /// result will be based only on AA results for the function declaration; it
122 /// will be assumed that some other (perhaps less optimized) version of the
123 /// function may be selected at link time.
124 static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
125                                                   AAResults &AAR,
126                                                   const SCCNodeSet &SCCNodes) {
127   FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
128   if (MRB == FMRB_DoesNotAccessMemory)
129     // Already perfect!
130     return MAK_ReadNone;
131 
132   if (!ThisBody) {
133     if (AliasAnalysis::onlyReadsMemory(MRB))
134       return MAK_ReadOnly;
135 
136     if (AliasAnalysis::doesNotReadMemory(MRB))
137       return MAK_WriteOnly;
138 
139     // Conservatively assume it reads and writes to memory.
140     return MAK_MayWrite;
141   }
142 
143   // Scan the function body for instructions that may read or write memory.
144   bool ReadsMemory = false;
145   bool WritesMemory = false;
146   for (Instruction &I : instructions(F)) {
147     // Some instructions can be ignored even if they read or write memory.
148     // Detect these now, skipping to the next instruction if one is found.
149     if (auto *Call = dyn_cast<CallBase>(&I)) {
150       // Ignore calls to functions in the same SCC, as long as the call sites
151       // don't have operand bundles.  Calls with operand bundles are allowed to
152       // have memory effects not described by the memory effects of the call
153       // target.
154       if (!Call->hasOperandBundles() && Call->getCalledFunction() &&
155           SCCNodes.count(Call->getCalledFunction()))
156         continue;
157       FunctionModRefBehavior MRB = AAR.getModRefBehavior(Call);
158       ModRefInfo MRI = createModRefInfo(MRB);
159 
160       // If the call doesn't access memory, we're done.
161       if (isNoModRef(MRI))
162         continue;
163 
164       // A pseudo probe call shouldn't change any function attribute since it
165       // doesn't translate to a real instruction. It comes with a memory access
166       // tag to prevent itself being removed by optimizations and not block
167       // other instructions being optimized.
168       if (isa<PseudoProbeInst>(I))
169         continue;
170 
171       if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
172         // The call could access any memory. If that includes writes, note it.
173         if (isModSet(MRI))
174           WritesMemory = true;
175         // If it reads, note it.
176         if (isRefSet(MRI))
177           ReadsMemory = true;
178         continue;
179       }
180 
181       // Check whether all pointer arguments point to local memory, and
182       // ignore calls that only access local memory.
183       for (const Use &U : Call->args()) {
184         const Value *Arg = U;
185         if (!Arg->getType()->isPtrOrPtrVectorTy())
186           continue;
187 
188         MemoryLocation Loc =
189             MemoryLocation::getBeforeOrAfter(Arg, I.getAAMetadata());
190 
191         // Skip accesses to local or constant memory as they don't impact the
192         // externally visible mod/ref behavior.
193         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
194           continue;
195 
196         if (isModSet(MRI))
197           // Writes non-local memory.
198           WritesMemory = true;
199         if (isRefSet(MRI))
200           // Ok, it reads non-local memory.
201           ReadsMemory = true;
202       }
203       continue;
204     } else if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
205       // Ignore non-volatile loads from local memory. (Atomic is okay here.)
206       if (!LI->isVolatile()) {
207         MemoryLocation Loc = MemoryLocation::get(LI);
208         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
209           continue;
210       }
211     } else if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
212       // Ignore non-volatile stores to local memory. (Atomic is okay here.)
213       if (!SI->isVolatile()) {
214         MemoryLocation Loc = MemoryLocation::get(SI);
215         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
216           continue;
217       }
218     } else if (VAArgInst *VI = dyn_cast<VAArgInst>(&I)) {
219       // Ignore vaargs on local memory.
220       MemoryLocation Loc = MemoryLocation::get(VI);
221       if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
222         continue;
223     }
224 
225     // Any remaining instructions need to be taken seriously!  Check if they
226     // read or write memory.
227     //
228     // Writes memory, remember that.
229     WritesMemory |= I.mayWriteToMemory();
230 
231     // If this instruction may read memory, remember that.
232     ReadsMemory |= I.mayReadFromMemory();
233   }
234 
235   if (WritesMemory) {
236     if (!ReadsMemory)
237       return MAK_WriteOnly;
238     else
239       return MAK_MayWrite;
240   }
241 
242   return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
243 }
244 
245 MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
246                                                        AAResults &AAR) {
247   return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
248 }
249 
250 /// Deduce readonly/readnone attributes for the SCC.
251 template <typename AARGetterT>
252 static void addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter,
253                          SmallSet<Function *, 8> &Changed) {
254   // Check if any of the functions in the SCC read or write memory.  If they
255   // write memory then they can't be marked readnone or readonly.
256   bool ReadsMemory = false;
257   bool WritesMemory = false;
258   for (Function *F : SCCNodes) {
259     // Call the callable parameter to look up AA results for this function.
260     AAResults &AAR = AARGetter(*F);
261 
262     // Non-exact function definitions may not be selected at link time, and an
263     // alternative version that writes to memory may be selected.  See the
264     // comment on GlobalValue::isDefinitionExact for more details.
265     switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
266                                       AAR, SCCNodes)) {
267     case MAK_MayWrite:
268       return;
269     case MAK_ReadOnly:
270       ReadsMemory = true;
271       break;
272     case MAK_WriteOnly:
273       WritesMemory = true;
274       break;
275     case MAK_ReadNone:
276       // Nothing to do!
277       break;
278     }
279   }
280 
281   // If the SCC contains both functions that read and functions that write, then
282   // we cannot add readonly attributes.
283   if (ReadsMemory && WritesMemory)
284     return;
285 
286   // Success!  Functions in this SCC do not access memory, or only read memory.
287   // Give them the appropriate attribute.
288 
289   for (Function *F : SCCNodes) {
290     if (F->doesNotAccessMemory())
291       // Already perfect!
292       continue;
293 
294     if (F->onlyReadsMemory() && ReadsMemory)
295       // No change.
296       continue;
297 
298     if (F->doesNotReadMemory() && WritesMemory)
299       continue;
300 
301     Changed.insert(F);
302 
303     // Clear out any existing attributes.
304     AttrBuilder AttrsToRemove;
305     AttrsToRemove.addAttribute(Attribute::ReadOnly);
306     AttrsToRemove.addAttribute(Attribute::ReadNone);
307     AttrsToRemove.addAttribute(Attribute::WriteOnly);
308 
309     if (!WritesMemory && !ReadsMemory) {
310       // Clear out any "access range attributes" if readnone was deduced.
311       AttrsToRemove.addAttribute(Attribute::ArgMemOnly);
312       AttrsToRemove.addAttribute(Attribute::InaccessibleMemOnly);
313       AttrsToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
314     }
315     F->removeFnAttrs(AttrsToRemove);
316 
317     // Add in the new attribute.
318     if (WritesMemory && !ReadsMemory)
319       F->addFnAttr(Attribute::WriteOnly);
320     else
321       F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
322 
323     if (WritesMemory && !ReadsMemory)
324       ++NumWriteOnly;
325     else if (ReadsMemory)
326       ++NumReadOnly;
327     else
328       ++NumReadNone;
329   }
330 }
331 
332 // Compute definitive function attributes for a function taking into account
333 // prevailing definitions and linkage types
334 static FunctionSummary *calculatePrevailingSummary(
335     ValueInfo VI,
336     DenseMap<ValueInfo, FunctionSummary *> &CachedPrevailingSummary,
337     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
338         IsPrevailing) {
339 
340   if (CachedPrevailingSummary.count(VI))
341     return CachedPrevailingSummary[VI];
342 
343   /// At this point, prevailing symbols have been resolved. The following leads
344   /// to returning a conservative result:
345   /// - Multiple instances with local linkage. Normally local linkage would be
346   ///   unique per module
347   ///   as the GUID includes the module path. We could have a guid alias if
348   ///   there wasn't any distinguishing path when each file was compiled, but
349   ///   that should be rare so we'll punt on those.
350 
351   /// These next 2 cases should not happen and will assert:
352   /// - Multiple instances with external linkage. This should be caught in
353   ///   symbol resolution
354   /// - Non-existent FunctionSummary for Aliasee. This presents a hole in our
355   ///   knowledge meaning we have to go conservative.
356 
357   /// Otherwise, we calculate attributes for a function as:
358   ///   1. If we have a local linkage, take its attributes. If there's somehow
359   ///      multiple, bail and go conservative.
360   ///   2. If we have an external/WeakODR/LinkOnceODR linkage check that it is
361   ///      prevailing, take its attributes.
362   ///   3. If we have a Weak/LinkOnce linkage the copies can have semantic
363   ///      differences. However, if the prevailing copy is known it will be used
364   ///      so take its attributes. If the prevailing copy is in a native file
365   ///      all IR copies will be dead and propagation will go conservative.
366   ///   4. AvailableExternally summaries without a prevailing copy are known to
367   ///      occur in a couple of circumstances:
368   ///      a. An internal function gets imported due to its caller getting
369   ///         imported, it becomes AvailableExternally but no prevailing
370   ///         definition exists. Because it has to get imported along with its
371   ///         caller the attributes will be captured by propagating on its
372   ///         caller.
373   ///      b. C++11 [temp.explicit]p10 can generate AvailableExternally
374   ///         definitions of explicitly instanced template declarations
375   ///         for inlining which are ultimately dropped from the TU. Since this
376   ///         is localized to the TU the attributes will have already made it to
377   ///         the callers.
378   ///      These are edge cases and already captured by their callers so we
379   ///      ignore these for now. If they become relevant to optimize in the
380   ///      future this can be revisited.
381   ///   5. Otherwise, go conservative.
382 
383   CachedPrevailingSummary[VI] = nullptr;
384   FunctionSummary *Local = nullptr;
385   FunctionSummary *Prevailing = nullptr;
386 
387   for (const auto &GVS : VI.getSummaryList()) {
388     if (!GVS->isLive())
389       continue;
390 
391     FunctionSummary *FS = dyn_cast<FunctionSummary>(GVS->getBaseObject());
392     // Virtual and Unknown (e.g. indirect) calls require going conservative
393     if (!FS || FS->fflags().HasUnknownCall)
394       return nullptr;
395 
396     const auto &Linkage = GVS->linkage();
397     if (GlobalValue::isLocalLinkage(Linkage)) {
398       if (Local) {
399         LLVM_DEBUG(
400             dbgs()
401             << "ThinLTO FunctionAttrs: Multiple Local Linkage, bailing on "
402                "function "
403             << VI.name() << " from " << FS->modulePath() << ". Previous module "
404             << Local->modulePath() << "\n");
405         return nullptr;
406       }
407       Local = FS;
408     } else if (GlobalValue::isExternalLinkage(Linkage)) {
409       assert(IsPrevailing(VI.getGUID(), GVS.get()));
410       Prevailing = FS;
411       break;
412     } else if (GlobalValue::isWeakODRLinkage(Linkage) ||
413                GlobalValue::isLinkOnceODRLinkage(Linkage) ||
414                GlobalValue::isWeakAnyLinkage(Linkage) ||
415                GlobalValue::isLinkOnceAnyLinkage(Linkage)) {
416       if (IsPrevailing(VI.getGUID(), GVS.get())) {
417         Prevailing = FS;
418         break;
419       }
420     } else if (GlobalValue::isAvailableExternallyLinkage(Linkage)) {
421       // TODO: Handle these cases if they become meaningful
422       continue;
423     }
424   }
425 
426   if (Local) {
427     assert(!Prevailing);
428     CachedPrevailingSummary[VI] = Local;
429   } else if (Prevailing) {
430     assert(!Local);
431     CachedPrevailingSummary[VI] = Prevailing;
432   }
433 
434   return CachedPrevailingSummary[VI];
435 }
436 
437 bool llvm::thinLTOPropagateFunctionAttrs(
438     ModuleSummaryIndex &Index,
439     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
440         IsPrevailing) {
441   // TODO: implement addNoAliasAttrs once
442   // there's more information about the return type in the summary
443   if (DisableThinLTOPropagation)
444     return false;
445 
446   DenseMap<ValueInfo, FunctionSummary *> CachedPrevailingSummary;
447   bool Changed = false;
448 
449   auto PropagateAttributes = [&](std::vector<ValueInfo> &SCCNodes) {
450     // Assume we can propagate unless we discover otherwise
451     FunctionSummary::FFlags InferredFlags;
452     InferredFlags.NoRecurse = (SCCNodes.size() == 1);
453     InferredFlags.NoUnwind = true;
454 
455     for (auto &V : SCCNodes) {
456       FunctionSummary *CallerSummary =
457           calculatePrevailingSummary(V, CachedPrevailingSummary, IsPrevailing);
458 
459       // Function summaries can fail to contain information such as declarations
460       if (!CallerSummary)
461         return;
462 
463       if (CallerSummary->fflags().MayThrow)
464         InferredFlags.NoUnwind = false;
465 
466       for (const auto &Callee : CallerSummary->calls()) {
467         FunctionSummary *CalleeSummary = calculatePrevailingSummary(
468             Callee.first, CachedPrevailingSummary, IsPrevailing);
469 
470         if (!CalleeSummary)
471           return;
472 
473         if (!CalleeSummary->fflags().NoRecurse)
474           InferredFlags.NoRecurse = false;
475 
476         if (!CalleeSummary->fflags().NoUnwind)
477           InferredFlags.NoUnwind = false;
478 
479         if (!InferredFlags.NoUnwind && !InferredFlags.NoRecurse)
480           break;
481       }
482     }
483 
484     if (InferredFlags.NoUnwind || InferredFlags.NoRecurse) {
485       Changed = true;
486       for (auto &V : SCCNodes) {
487         if (InferredFlags.NoRecurse) {
488           LLVM_DEBUG(dbgs() << "ThinLTO FunctionAttrs: Propagated NoRecurse to "
489                             << V.name() << "\n");
490           ++NumThinLinkNoRecurse;
491         }
492 
493         if (InferredFlags.NoUnwind) {
494           LLVM_DEBUG(dbgs() << "ThinLTO FunctionAttrs: Propagated NoUnwind to "
495                             << V.name() << "\n");
496           ++NumThinLinkNoUnwind;
497         }
498 
499         for (auto &S : V.getSummaryList()) {
500           if (auto *FS = dyn_cast<FunctionSummary>(S.get())) {
501             if (InferredFlags.NoRecurse)
502               FS->setNoRecurse();
503 
504             if (InferredFlags.NoUnwind)
505               FS->setNoUnwind();
506           }
507         }
508       }
509     }
510   };
511 
512   // Call propagation functions on each SCC in the Index
513   for (scc_iterator<ModuleSummaryIndex *> I = scc_begin(&Index); !I.isAtEnd();
514        ++I) {
515     std::vector<ValueInfo> Nodes(*I);
516     PropagateAttributes(Nodes);
517   }
518   return Changed;
519 }
520 
521 namespace {
522 
523 /// For a given pointer Argument, this retains a list of Arguments of functions
524 /// in the same SCC that the pointer data flows into. We use this to build an
525 /// SCC of the arguments.
526 struct ArgumentGraphNode {
527   Argument *Definition;
528   SmallVector<ArgumentGraphNode *, 4> Uses;
529 };
530 
531 class ArgumentGraph {
532   // We store pointers to ArgumentGraphNode objects, so it's important that
533   // that they not move around upon insert.
534   using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
535 
536   ArgumentMapTy ArgumentMap;
537 
538   // There is no root node for the argument graph, in fact:
539   //   void f(int *x, int *y) { if (...) f(x, y); }
540   // is an example where the graph is disconnected. The SCCIterator requires a
541   // single entry point, so we maintain a fake ("synthetic") root node that
542   // uses every node. Because the graph is directed and nothing points into
543   // the root, it will not participate in any SCCs (except for its own).
544   ArgumentGraphNode SyntheticRoot;
545 
546 public:
547   ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
548 
549   using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
550 
551   iterator begin() { return SyntheticRoot.Uses.begin(); }
552   iterator end() { return SyntheticRoot.Uses.end(); }
553   ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
554 
555   ArgumentGraphNode *operator[](Argument *A) {
556     ArgumentGraphNode &Node = ArgumentMap[A];
557     Node.Definition = A;
558     SyntheticRoot.Uses.push_back(&Node);
559     return &Node;
560   }
561 };
562 
563 /// This tracker checks whether callees are in the SCC, and if so it does not
564 /// consider that a capture, instead adding it to the "Uses" list and
565 /// continuing with the analysis.
566 struct ArgumentUsesTracker : public CaptureTracker {
567   ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
568 
569   void tooManyUses() override { Captured = true; }
570 
571   bool captured(const Use *U) override {
572     CallBase *CB = dyn_cast<CallBase>(U->getUser());
573     if (!CB) {
574       Captured = true;
575       return true;
576     }
577 
578     Function *F = CB->getCalledFunction();
579     if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
580       Captured = true;
581       return true;
582     }
583 
584     assert(!CB->isCallee(U) && "callee operand reported captured?");
585     const unsigned UseIndex = CB->getDataOperandNo(U);
586     if (UseIndex >= CB->arg_size()) {
587       // Data operand, but not a argument operand -- must be a bundle operand
588       assert(CB->hasOperandBundles() && "Must be!");
589 
590       // CaptureTracking told us that we're being captured by an operand bundle
591       // use.  In this case it does not matter if the callee is within our SCC
592       // or not -- we've been captured in some unknown way, and we have to be
593       // conservative.
594       Captured = true;
595       return true;
596     }
597 
598     if (UseIndex >= F->arg_size()) {
599       assert(F->isVarArg() && "More params than args in non-varargs call");
600       Captured = true;
601       return true;
602     }
603 
604     Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
605     return false;
606   }
607 
608   // True only if certainly captured (used outside our SCC).
609   bool Captured = false;
610 
611   // Uses within our SCC.
612   SmallVector<Argument *, 4> Uses;
613 
614   const SCCNodeSet &SCCNodes;
615 };
616 
617 } // end anonymous namespace
618 
619 namespace llvm {
620 
621 template <> struct GraphTraits<ArgumentGraphNode *> {
622   using NodeRef = ArgumentGraphNode *;
623   using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
624 
625   static NodeRef getEntryNode(NodeRef A) { return A; }
626   static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
627   static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
628 };
629 
630 template <>
631 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
632   static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
633 
634   static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
635     return AG->begin();
636   }
637 
638   static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
639 };
640 
641 } // end namespace llvm
642 
643 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
644 static Attribute::AttrKind
645 determinePointerAccessAttrs(Argument *A,
646                             const SmallPtrSet<Argument *, 8> &SCCNodes) {
647   SmallVector<Use *, 32> Worklist;
648   SmallPtrSet<Use *, 32> Visited;
649 
650   // inalloca arguments are always clobbered by the call.
651   if (A->hasInAllocaAttr() || A->hasPreallocatedAttr())
652     return Attribute::None;
653 
654   bool IsRead = false;
655   bool IsWrite = false;
656 
657   for (Use &U : A->uses()) {
658     Visited.insert(&U);
659     Worklist.push_back(&U);
660   }
661 
662   while (!Worklist.empty()) {
663     if (IsWrite && IsRead)
664       // No point in searching further..
665       return Attribute::None;
666 
667     Use *U = Worklist.pop_back_val();
668     Instruction *I = cast<Instruction>(U->getUser());
669 
670     switch (I->getOpcode()) {
671     case Instruction::BitCast:
672     case Instruction::GetElementPtr:
673     case Instruction::PHI:
674     case Instruction::Select:
675     case Instruction::AddrSpaceCast:
676       // The original value is not read/written via this if the new value isn't.
677       for (Use &UU : I->uses())
678         if (Visited.insert(&UU).second)
679           Worklist.push_back(&UU);
680       break;
681 
682     case Instruction::Call:
683     case Instruction::Invoke: {
684       bool Captures = true;
685 
686       if (I->getType()->isVoidTy())
687         Captures = false;
688 
689       auto AddUsersToWorklistIfCapturing = [&] {
690         if (Captures)
691           for (Use &UU : I->uses())
692             if (Visited.insert(&UU).second)
693               Worklist.push_back(&UU);
694       };
695 
696       CallBase &CB = cast<CallBase>(*I);
697       if (CB.isCallee(U)) {
698         IsRead = true;
699         Captures = false; // See comment in CaptureTracking for context
700         continue;
701       }
702       if (CB.doesNotAccessMemory()) {
703         AddUsersToWorklistIfCapturing();
704         continue;
705       }
706 
707       Function *F = CB.getCalledFunction();
708       if (!F) {
709         if (CB.onlyReadsMemory()) {
710           IsRead = true;
711           AddUsersToWorklistIfCapturing();
712           continue;
713         }
714         return Attribute::None;
715       }
716 
717       // Given we've explictily handled the callee operand above, what's left
718       // must be a data operand (e.g. argument or operand bundle)
719       const unsigned UseIndex = CB.getDataOperandNo(U);
720       const bool IsOperandBundleUse = UseIndex >= CB.arg_size();
721 
722       if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
723         assert(F->isVarArg() && "More params than args in non-varargs call");
724         return Attribute::None;
725       }
726 
727       Captures &= !CB.doesNotCapture(UseIndex);
728 
729       // Since the optimizer (by design) cannot see the data flow corresponding
730       // to a operand bundle use, these cannot participate in the optimistic SCC
731       // analysis.  Instead, we model the operand bundle uses as arguments in
732       // call to a function external to the SCC.
733       if (IsOperandBundleUse ||
734           !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
735 
736         // The accessors used on call site here do the right thing for calls and
737         // invokes with operand bundles.
738 
739         if (!CB.onlyReadsMemory() && !CB.onlyReadsMemory(UseIndex))
740           return Attribute::None;
741         if (!CB.doesNotAccessMemory(UseIndex))
742           IsRead = true;
743       }
744 
745       AddUsersToWorklistIfCapturing();
746       break;
747     }
748 
749     case Instruction::Load:
750       // A volatile load has side effects beyond what readonly can be relied
751       // upon.
752       if (cast<LoadInst>(I)->isVolatile())
753         return Attribute::None;
754 
755       IsRead = true;
756       break;
757 
758     case Instruction::Store:
759       if (cast<StoreInst>(I)->getValueOperand() == *U)
760         // untrackable capture
761         return Attribute::None;
762 
763       // A volatile store has side effects beyond what writeonly can be relied
764       // upon.
765       if (cast<StoreInst>(I)->isVolatile())
766         return Attribute::None;
767 
768       IsWrite = true;
769       break;
770 
771     case Instruction::ICmp:
772     case Instruction::Ret:
773       break;
774 
775     default:
776       return Attribute::None;
777     }
778   }
779 
780   if (IsWrite && IsRead)
781     return Attribute::None;
782   else if (IsRead)
783     return Attribute::ReadOnly;
784   else if (IsWrite)
785     return Attribute::WriteOnly;
786   else
787     return Attribute::ReadNone;
788 }
789 
790 /// Deduce returned attributes for the SCC.
791 static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes,
792                                      SmallSet<Function *, 8> &Changed) {
793   // Check each function in turn, determining if an argument is always returned.
794   for (Function *F : SCCNodes) {
795     // We can infer and propagate function attributes only when we know that the
796     // definition we'll get at link time is *exactly* the definition we see now.
797     // For more details, see GlobalValue::mayBeDerefined.
798     if (!F->hasExactDefinition())
799       continue;
800 
801     if (F->getReturnType()->isVoidTy())
802       continue;
803 
804     // There is nothing to do if an argument is already marked as 'returned'.
805     if (llvm::any_of(F->args(),
806                      [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
807       continue;
808 
809     auto FindRetArg = [&]() -> Value * {
810       Value *RetArg = nullptr;
811       for (BasicBlock &BB : *F)
812         if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
813           // Note that stripPointerCasts should look through functions with
814           // returned arguments.
815           Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
816           if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
817             return nullptr;
818 
819           if (!RetArg)
820             RetArg = RetVal;
821           else if (RetArg != RetVal)
822             return nullptr;
823         }
824 
825       return RetArg;
826     };
827 
828     if (Value *RetArg = FindRetArg()) {
829       auto *A = cast<Argument>(RetArg);
830       A->addAttr(Attribute::Returned);
831       ++NumReturned;
832       Changed.insert(F);
833     }
834   }
835 }
836 
837 /// If a callsite has arguments that are also arguments to the parent function,
838 /// try to propagate attributes from the callsite's arguments to the parent's
839 /// arguments. This may be important because inlining can cause information loss
840 /// when attribute knowledge disappears with the inlined call.
841 static bool addArgumentAttrsFromCallsites(Function &F) {
842   if (!EnableNonnullArgPropagation)
843     return false;
844 
845   bool Changed = false;
846 
847   // For an argument attribute to transfer from a callsite to the parent, the
848   // call must be guaranteed to execute every time the parent is called.
849   // Conservatively, just check for calls in the entry block that are guaranteed
850   // to execute.
851   // TODO: This could be enhanced by testing if the callsite post-dominates the
852   // entry block or by doing simple forward walks or backward walks to the
853   // callsite.
854   BasicBlock &Entry = F.getEntryBlock();
855   for (Instruction &I : Entry) {
856     if (auto *CB = dyn_cast<CallBase>(&I)) {
857       if (auto *CalledFunc = CB->getCalledFunction()) {
858         for (auto &CSArg : CalledFunc->args()) {
859           if (!CSArg.hasNonNullAttr(/* AllowUndefOrPoison */ false))
860             continue;
861 
862           // If the non-null callsite argument operand is an argument to 'F'
863           // (the caller) and the call is guaranteed to execute, then the value
864           // must be non-null throughout 'F'.
865           auto *FArg = dyn_cast<Argument>(CB->getArgOperand(CSArg.getArgNo()));
866           if (FArg && !FArg->hasNonNullAttr()) {
867             FArg->addAttr(Attribute::NonNull);
868             Changed = true;
869           }
870         }
871       }
872     }
873     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
874       break;
875   }
876 
877   return Changed;
878 }
879 
880 static bool addAccessAttr(Argument *A, Attribute::AttrKind R) {
881   assert((R == Attribute::ReadOnly || R == Attribute::ReadNone ||
882           R == Attribute::WriteOnly)
883          && "Must be an access attribute.");
884   assert(A && "Argument must not be null.");
885 
886   // If the argument already has the attribute, nothing needs to be done.
887   if (A->hasAttribute(R))
888       return false;
889 
890   // Otherwise, remove potentially conflicting attribute, add the new one,
891   // and update statistics.
892   A->removeAttr(Attribute::WriteOnly);
893   A->removeAttr(Attribute::ReadOnly);
894   A->removeAttr(Attribute::ReadNone);
895   A->addAttr(R);
896   if (R == Attribute::ReadOnly)
897     ++NumReadOnlyArg;
898   else if (R == Attribute::WriteOnly)
899     ++NumWriteOnlyArg;
900   else
901     ++NumReadNoneArg;
902   return true;
903 }
904 
905 /// Deduce nocapture attributes for the SCC.
906 static void addArgumentAttrs(const SCCNodeSet &SCCNodes,
907                              SmallSet<Function *, 8> &Changed) {
908   ArgumentGraph AG;
909 
910   // Check each function in turn, determining which pointer arguments are not
911   // captured.
912   for (Function *F : SCCNodes) {
913     // We can infer and propagate function attributes only when we know that the
914     // definition we'll get at link time is *exactly* the definition we see now.
915     // For more details, see GlobalValue::mayBeDerefined.
916     if (!F->hasExactDefinition())
917       continue;
918 
919     if (addArgumentAttrsFromCallsites(*F))
920       Changed.insert(F);
921 
922     // Functions that are readonly (or readnone) and nounwind and don't return
923     // a value can't capture arguments. Don't analyze them.
924     if (F->onlyReadsMemory() && F->doesNotThrow() &&
925         F->getReturnType()->isVoidTy()) {
926       for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
927            ++A) {
928         if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
929           A->addAttr(Attribute::NoCapture);
930           ++NumNoCapture;
931           Changed.insert(F);
932         }
933       }
934       continue;
935     }
936 
937     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
938          ++A) {
939       if (!A->getType()->isPointerTy())
940         continue;
941       bool HasNonLocalUses = false;
942       if (!A->hasNoCaptureAttr()) {
943         ArgumentUsesTracker Tracker(SCCNodes);
944         PointerMayBeCaptured(&*A, &Tracker);
945         if (!Tracker.Captured) {
946           if (Tracker.Uses.empty()) {
947             // If it's trivially not captured, mark it nocapture now.
948             A->addAttr(Attribute::NoCapture);
949             ++NumNoCapture;
950             Changed.insert(F);
951           } else {
952             // If it's not trivially captured and not trivially not captured,
953             // then it must be calling into another function in our SCC. Save
954             // its particulars for Argument-SCC analysis later.
955             ArgumentGraphNode *Node = AG[&*A];
956             for (Argument *Use : Tracker.Uses) {
957               Node->Uses.push_back(AG[Use]);
958               if (Use != &*A)
959                 HasNonLocalUses = true;
960             }
961           }
962         }
963         // Otherwise, it's captured. Don't bother doing SCC analysis on it.
964       }
965       if (!HasNonLocalUses && !A->onlyReadsMemory()) {
966         // Can we determine that it's readonly/readnone/writeonly without doing
967         // an SCC? Note that we don't allow any calls at all here, or else our
968         // result will be dependent on the iteration order through the
969         // functions in the SCC.
970         SmallPtrSet<Argument *, 8> Self;
971         Self.insert(&*A);
972         Attribute::AttrKind R = determinePointerAccessAttrs(&*A, Self);
973         if (R != Attribute::None)
974           if (addAccessAttr(A, R))
975             Changed.insert(F);
976       }
977     }
978   }
979 
980   // The graph we've collected is partial because we stopped scanning for
981   // argument uses once we solved the argument trivially. These partial nodes
982   // show up as ArgumentGraphNode objects with an empty Uses list, and for
983   // these nodes the final decision about whether they capture has already been
984   // made.  If the definition doesn't have a 'nocapture' attribute by now, it
985   // captures.
986 
987   for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
988     const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
989     if (ArgumentSCC.size() == 1) {
990       if (!ArgumentSCC[0]->Definition)
991         continue; // synthetic root node
992 
993       // eg. "void f(int* x) { if (...) f(x); }"
994       if (ArgumentSCC[0]->Uses.size() == 1 &&
995           ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
996         Argument *A = ArgumentSCC[0]->Definition;
997         A->addAttr(Attribute::NoCapture);
998         ++NumNoCapture;
999         Changed.insert(A->getParent());
1000       }
1001       continue;
1002     }
1003 
1004     bool SCCCaptured = false;
1005     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
1006          I != E && !SCCCaptured; ++I) {
1007       ArgumentGraphNode *Node = *I;
1008       if (Node->Uses.empty()) {
1009         if (!Node->Definition->hasNoCaptureAttr())
1010           SCCCaptured = true;
1011       }
1012     }
1013     if (SCCCaptured)
1014       continue;
1015 
1016     SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
1017     // Fill ArgumentSCCNodes with the elements of the ArgumentSCC.  Used for
1018     // quickly looking up whether a given Argument is in this ArgumentSCC.
1019     for (ArgumentGraphNode *I : ArgumentSCC) {
1020       ArgumentSCCNodes.insert(I->Definition);
1021     }
1022 
1023     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
1024          I != E && !SCCCaptured; ++I) {
1025       ArgumentGraphNode *N = *I;
1026       for (ArgumentGraphNode *Use : N->Uses) {
1027         Argument *A = Use->Definition;
1028         if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
1029           continue;
1030         SCCCaptured = true;
1031         break;
1032       }
1033     }
1034     if (SCCCaptured)
1035       continue;
1036 
1037     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
1038       Argument *A = ArgumentSCC[i]->Definition;
1039       A->addAttr(Attribute::NoCapture);
1040       ++NumNoCapture;
1041       Changed.insert(A->getParent());
1042     }
1043 
1044     // We also want to compute readonly/readnone/writeonly. With a small number
1045     // of false negatives, we can assume that any pointer which is captured
1046     // isn't going to be provably readonly or readnone, since by definition
1047     // we can't analyze all uses of a captured pointer.
1048     //
1049     // The false negatives happen when the pointer is captured by a function
1050     // that promises readonly/readnone behaviour on the pointer, then the
1051     // pointer's lifetime ends before anything that writes to arbitrary memory.
1052     // Also, a readonly/readnone pointer may be returned, but returning a
1053     // pointer is capturing it.
1054 
1055     auto meetAccessAttr = [](Attribute::AttrKind A, Attribute::AttrKind B) {
1056       if (A == B)
1057         return A;
1058       if (A == Attribute::ReadNone)
1059         return B;
1060       if (B == Attribute::ReadNone)
1061         return A;
1062       return Attribute::None;
1063     };
1064 
1065     Attribute::AttrKind AccessAttr = Attribute::ReadNone;
1066     for (unsigned i = 0, e = ArgumentSCC.size();
1067          i != e && AccessAttr != Attribute::None; ++i) {
1068       Argument *A = ArgumentSCC[i]->Definition;
1069       Attribute::AttrKind K = determinePointerAccessAttrs(A, ArgumentSCCNodes);
1070       AccessAttr = meetAccessAttr(AccessAttr, K);
1071     }
1072 
1073     if (AccessAttr != Attribute::None) {
1074       for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
1075         Argument *A = ArgumentSCC[i]->Definition;
1076         if (addAccessAttr(A, AccessAttr))
1077           Changed.insert(A->getParent());
1078       }
1079     }
1080   }
1081 }
1082 
1083 /// Tests whether a function is "malloc-like".
1084 ///
1085 /// A function is "malloc-like" if it returns either null or a pointer that
1086 /// doesn't alias any other pointer visible to the caller.
1087 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
1088   SmallSetVector<Value *, 8> FlowsToReturn;
1089   for (BasicBlock &BB : *F)
1090     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1091       FlowsToReturn.insert(Ret->getReturnValue());
1092 
1093   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1094     Value *RetVal = FlowsToReturn[i];
1095 
1096     if (Constant *C = dyn_cast<Constant>(RetVal)) {
1097       if (!C->isNullValue() && !isa<UndefValue>(C))
1098         return false;
1099 
1100       continue;
1101     }
1102 
1103     if (isa<Argument>(RetVal))
1104       return false;
1105 
1106     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
1107       switch (RVI->getOpcode()) {
1108       // Extend the analysis by looking upwards.
1109       case Instruction::BitCast:
1110       case Instruction::GetElementPtr:
1111       case Instruction::AddrSpaceCast:
1112         FlowsToReturn.insert(RVI->getOperand(0));
1113         continue;
1114       case Instruction::Select: {
1115         SelectInst *SI = cast<SelectInst>(RVI);
1116         FlowsToReturn.insert(SI->getTrueValue());
1117         FlowsToReturn.insert(SI->getFalseValue());
1118         continue;
1119       }
1120       case Instruction::PHI: {
1121         PHINode *PN = cast<PHINode>(RVI);
1122         for (Value *IncValue : PN->incoming_values())
1123           FlowsToReturn.insert(IncValue);
1124         continue;
1125       }
1126 
1127       // Check whether the pointer came from an allocation.
1128       case Instruction::Alloca:
1129         break;
1130       case Instruction::Call:
1131       case Instruction::Invoke: {
1132         CallBase &CB = cast<CallBase>(*RVI);
1133         if (CB.hasRetAttr(Attribute::NoAlias))
1134           break;
1135         if (CB.getCalledFunction() && SCCNodes.count(CB.getCalledFunction()))
1136           break;
1137         LLVM_FALLTHROUGH;
1138       }
1139       default:
1140         return false; // Did not come from an allocation.
1141       }
1142 
1143     if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
1144       return false;
1145   }
1146 
1147   return true;
1148 }
1149 
1150 /// Deduce noalias attributes for the SCC.
1151 static void addNoAliasAttrs(const SCCNodeSet &SCCNodes,
1152                             SmallSet<Function *, 8> &Changed) {
1153   // Check each function in turn, determining which functions return noalias
1154   // pointers.
1155   for (Function *F : SCCNodes) {
1156     // Already noalias.
1157     if (F->returnDoesNotAlias())
1158       continue;
1159 
1160     // We can infer and propagate function attributes only when we know that the
1161     // definition we'll get at link time is *exactly* the definition we see now.
1162     // For more details, see GlobalValue::mayBeDerefined.
1163     if (!F->hasExactDefinition())
1164       return;
1165 
1166     // We annotate noalias return values, which are only applicable to
1167     // pointer types.
1168     if (!F->getReturnType()->isPointerTy())
1169       continue;
1170 
1171     if (!isFunctionMallocLike(F, SCCNodes))
1172       return;
1173   }
1174 
1175   for (Function *F : SCCNodes) {
1176     if (F->returnDoesNotAlias() ||
1177         !F->getReturnType()->isPointerTy())
1178       continue;
1179 
1180     F->setReturnDoesNotAlias();
1181     ++NumNoAlias;
1182     Changed.insert(F);
1183   }
1184 }
1185 
1186 /// Tests whether this function is known to not return null.
1187 ///
1188 /// Requires that the function returns a pointer.
1189 ///
1190 /// Returns true if it believes the function will not return a null, and sets
1191 /// \p Speculative based on whether the returned conclusion is a speculative
1192 /// conclusion due to SCC calls.
1193 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
1194                             bool &Speculative) {
1195   assert(F->getReturnType()->isPointerTy() &&
1196          "nonnull only meaningful on pointer types");
1197   Speculative = false;
1198 
1199   SmallSetVector<Value *, 8> FlowsToReturn;
1200   for (BasicBlock &BB : *F)
1201     if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1202       FlowsToReturn.insert(Ret->getReturnValue());
1203 
1204   auto &DL = F->getParent()->getDataLayout();
1205 
1206   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1207     Value *RetVal = FlowsToReturn[i];
1208 
1209     // If this value is locally known to be non-null, we're good
1210     if (isKnownNonZero(RetVal, DL))
1211       continue;
1212 
1213     // Otherwise, we need to look upwards since we can't make any local
1214     // conclusions.
1215     Instruction *RVI = dyn_cast<Instruction>(RetVal);
1216     if (!RVI)
1217       return false;
1218     switch (RVI->getOpcode()) {
1219     // Extend the analysis by looking upwards.
1220     case Instruction::BitCast:
1221     case Instruction::GetElementPtr:
1222     case Instruction::AddrSpaceCast:
1223       FlowsToReturn.insert(RVI->getOperand(0));
1224       continue;
1225     case Instruction::Select: {
1226       SelectInst *SI = cast<SelectInst>(RVI);
1227       FlowsToReturn.insert(SI->getTrueValue());
1228       FlowsToReturn.insert(SI->getFalseValue());
1229       continue;
1230     }
1231     case Instruction::PHI: {
1232       PHINode *PN = cast<PHINode>(RVI);
1233       for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1234         FlowsToReturn.insert(PN->getIncomingValue(i));
1235       continue;
1236     }
1237     case Instruction::Call:
1238     case Instruction::Invoke: {
1239       CallBase &CB = cast<CallBase>(*RVI);
1240       Function *Callee = CB.getCalledFunction();
1241       // A call to a node within the SCC is assumed to return null until
1242       // proven otherwise
1243       if (Callee && SCCNodes.count(Callee)) {
1244         Speculative = true;
1245         continue;
1246       }
1247       return false;
1248     }
1249     default:
1250       return false; // Unknown source, may be null
1251     };
1252     llvm_unreachable("should have either continued or returned");
1253   }
1254 
1255   return true;
1256 }
1257 
1258 /// Deduce nonnull attributes for the SCC.
1259 static void addNonNullAttrs(const SCCNodeSet &SCCNodes,
1260                             SmallSet<Function *, 8> &Changed) {
1261   // Speculative that all functions in the SCC return only nonnull
1262   // pointers.  We may refute this as we analyze functions.
1263   bool SCCReturnsNonNull = true;
1264 
1265   // Check each function in turn, determining which functions return nonnull
1266   // pointers.
1267   for (Function *F : SCCNodes) {
1268     // Already nonnull.
1269     if (F->getAttributes().hasRetAttr(Attribute::NonNull))
1270       continue;
1271 
1272     // We can infer and propagate function attributes only when we know that the
1273     // definition we'll get at link time is *exactly* the definition we see now.
1274     // For more details, see GlobalValue::mayBeDerefined.
1275     if (!F->hasExactDefinition())
1276       return;
1277 
1278     // We annotate nonnull return values, which are only applicable to
1279     // pointer types.
1280     if (!F->getReturnType()->isPointerTy())
1281       continue;
1282 
1283     bool Speculative = false;
1284     if (isReturnNonNull(F, SCCNodes, Speculative)) {
1285       if (!Speculative) {
1286         // Mark the function eagerly since we may discover a function
1287         // which prevents us from speculating about the entire SCC
1288         LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1289                           << " as nonnull\n");
1290         F->addRetAttr(Attribute::NonNull);
1291         ++NumNonNullReturn;
1292         Changed.insert(F);
1293       }
1294       continue;
1295     }
1296     // At least one function returns something which could be null, can't
1297     // speculate any more.
1298     SCCReturnsNonNull = false;
1299   }
1300 
1301   if (SCCReturnsNonNull) {
1302     for (Function *F : SCCNodes) {
1303       if (F->getAttributes().hasRetAttr(Attribute::NonNull) ||
1304           !F->getReturnType()->isPointerTy())
1305         continue;
1306 
1307       LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1308       F->addRetAttr(Attribute::NonNull);
1309       ++NumNonNullReturn;
1310       Changed.insert(F);
1311     }
1312   }
1313 }
1314 
1315 namespace {
1316 
1317 /// Collects a set of attribute inference requests and performs them all in one
1318 /// go on a single SCC Node. Inference involves scanning function bodies
1319 /// looking for instructions that violate attribute assumptions.
1320 /// As soon as all the bodies are fine we are free to set the attribute.
1321 /// Customization of inference for individual attributes is performed by
1322 /// providing a handful of predicates for each attribute.
1323 class AttributeInferer {
1324 public:
1325   /// Describes a request for inference of a single attribute.
1326   struct InferenceDescriptor {
1327 
1328     /// Returns true if this function does not have to be handled.
1329     /// General intent for this predicate is to provide an optimization
1330     /// for functions that do not need this attribute inference at all
1331     /// (say, for functions that already have the attribute).
1332     std::function<bool(const Function &)> SkipFunction;
1333 
1334     /// Returns true if this instruction violates attribute assumptions.
1335     std::function<bool(Instruction &)> InstrBreaksAttribute;
1336 
1337     /// Sets the inferred attribute for this function.
1338     std::function<void(Function &)> SetAttribute;
1339 
1340     /// Attribute we derive.
1341     Attribute::AttrKind AKind;
1342 
1343     /// If true, only "exact" definitions can be used to infer this attribute.
1344     /// See GlobalValue::isDefinitionExact.
1345     bool RequiresExactDefinition;
1346 
1347     InferenceDescriptor(Attribute::AttrKind AK,
1348                         std::function<bool(const Function &)> SkipFunc,
1349                         std::function<bool(Instruction &)> InstrScan,
1350                         std::function<void(Function &)> SetAttr,
1351                         bool ReqExactDef)
1352         : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1353           SetAttribute(SetAttr), AKind(AK),
1354           RequiresExactDefinition(ReqExactDef) {}
1355   };
1356 
1357 private:
1358   SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1359 
1360 public:
1361   void registerAttrInference(InferenceDescriptor AttrInference) {
1362     InferenceDescriptors.push_back(AttrInference);
1363   }
1364 
1365   void run(const SCCNodeSet &SCCNodes, SmallSet<Function *, 8> &Changed);
1366 };
1367 
1368 /// Perform all the requested attribute inference actions according to the
1369 /// attribute predicates stored before.
1370 void AttributeInferer::run(const SCCNodeSet &SCCNodes,
1371                            SmallSet<Function *, 8> &Changed) {
1372   SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1373   // Go through all the functions in SCC and check corresponding attribute
1374   // assumptions for each of them. Attributes that are invalid for this SCC
1375   // will be removed from InferInSCC.
1376   for (Function *F : SCCNodes) {
1377 
1378     // No attributes whose assumptions are still valid - done.
1379     if (InferInSCC.empty())
1380       return;
1381 
1382     // Check if our attributes ever need scanning/can be scanned.
1383     llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1384       if (ID.SkipFunction(*F))
1385         return false;
1386 
1387       // Remove from further inference (invalidate) when visiting a function
1388       // that has no instructions to scan/has an unsuitable definition.
1389       return F->isDeclaration() ||
1390              (ID.RequiresExactDefinition && !F->hasExactDefinition());
1391     });
1392 
1393     // For each attribute still in InferInSCC that doesn't explicitly skip F,
1394     // set up the F instructions scan to verify assumptions of the attribute.
1395     SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1396     llvm::copy_if(
1397         InferInSCC, std::back_inserter(InferInThisFunc),
1398         [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1399 
1400     if (InferInThisFunc.empty())
1401       continue;
1402 
1403     // Start instruction scan.
1404     for (Instruction &I : instructions(*F)) {
1405       llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1406         if (!ID.InstrBreaksAttribute(I))
1407           return false;
1408         // Remove attribute from further inference on any other functions
1409         // because attribute assumptions have just been violated.
1410         llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1411           return D.AKind == ID.AKind;
1412         });
1413         // Remove attribute from the rest of current instruction scan.
1414         return true;
1415       });
1416 
1417       if (InferInThisFunc.empty())
1418         break;
1419     }
1420   }
1421 
1422   if (InferInSCC.empty())
1423     return;
1424 
1425   for (Function *F : SCCNodes)
1426     // At this point InferInSCC contains only functions that were either:
1427     //   - explicitly skipped from scan/inference, or
1428     //   - verified to have no instructions that break attribute assumptions.
1429     // Hence we just go and force the attribute for all non-skipped functions.
1430     for (auto &ID : InferInSCC) {
1431       if (ID.SkipFunction(*F))
1432         continue;
1433       Changed.insert(F);
1434       ID.SetAttribute(*F);
1435     }
1436 }
1437 
1438 struct SCCNodesResult {
1439   SCCNodeSet SCCNodes;
1440   bool HasUnknownCall;
1441 };
1442 
1443 } // end anonymous namespace
1444 
1445 /// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1446 static bool InstrBreaksNonConvergent(Instruction &I,
1447                                      const SCCNodeSet &SCCNodes) {
1448   const CallBase *CB = dyn_cast<CallBase>(&I);
1449   // Breaks non-convergent assumption if CS is a convergent call to a function
1450   // not in the SCC.
1451   return CB && CB->isConvergent() &&
1452          !SCCNodes.contains(CB->getCalledFunction());
1453 }
1454 
1455 /// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1456 static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1457   if (!I.mayThrow())
1458     return false;
1459   if (const auto *CI = dyn_cast<CallInst>(&I)) {
1460     if (Function *Callee = CI->getCalledFunction()) {
1461       // I is a may-throw call to a function inside our SCC. This doesn't
1462       // invalidate our current working assumption that the SCC is no-throw; we
1463       // just have to scan that other function.
1464       if (SCCNodes.contains(Callee))
1465         return false;
1466     }
1467   }
1468   return true;
1469 }
1470 
1471 /// Helper for NoFree inference predicate InstrBreaksAttribute.
1472 static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1473   CallBase *CB = dyn_cast<CallBase>(&I);
1474   if (!CB)
1475     return false;
1476 
1477   if (CB->hasFnAttr(Attribute::NoFree))
1478     return false;
1479 
1480   // Speculatively assume in SCC.
1481   if (Function *Callee = CB->getCalledFunction())
1482     if (SCCNodes.contains(Callee))
1483       return false;
1484 
1485   return true;
1486 }
1487 
1488 /// Attempt to remove convergent function attribute when possible.
1489 ///
1490 /// Returns true if any changes to function attributes were made.
1491 static void inferConvergent(const SCCNodeSet &SCCNodes,
1492                             SmallSet<Function *, 8> &Changed) {
1493   AttributeInferer AI;
1494 
1495   // Request to remove the convergent attribute from all functions in the SCC
1496   // if every callsite within the SCC is not convergent (except for calls
1497   // to functions within the SCC).
1498   // Note: Removal of the attr from the callsites will happen in
1499   // InstCombineCalls separately.
1500   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1501       Attribute::Convergent,
1502       // Skip non-convergent functions.
1503       [](const Function &F) { return !F.isConvergent(); },
1504       // Instructions that break non-convergent assumption.
1505       [SCCNodes](Instruction &I) {
1506         return InstrBreaksNonConvergent(I, SCCNodes);
1507       },
1508       [](Function &F) {
1509         LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1510                           << "\n");
1511         F.setNotConvergent();
1512       },
1513       /* RequiresExactDefinition= */ false});
1514   // Perform all the requested attribute inference actions.
1515   AI.run(SCCNodes, Changed);
1516 }
1517 
1518 /// Infer attributes from all functions in the SCC by scanning every
1519 /// instruction for compliance to the attribute assumptions. Currently it
1520 /// does:
1521 ///   - addition of NoUnwind attribute
1522 ///
1523 /// Returns true if any changes to function attributes were made.
1524 static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes,
1525                                          SmallSet<Function *, 8> &Changed) {
1526   AttributeInferer AI;
1527 
1528   if (!DisableNoUnwindInference)
1529     // Request to infer nounwind attribute for all the functions in the SCC if
1530     // every callsite within the SCC is not throwing (except for calls to
1531     // functions within the SCC). Note that nounwind attribute suffers from
1532     // derefinement - results may change depending on how functions are
1533     // optimized. Thus it can be inferred only from exact definitions.
1534     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1535         Attribute::NoUnwind,
1536         // Skip non-throwing functions.
1537         [](const Function &F) { return F.doesNotThrow(); },
1538         // Instructions that break non-throwing assumption.
1539         [&SCCNodes](Instruction &I) {
1540           return InstrBreaksNonThrowing(I, SCCNodes);
1541         },
1542         [](Function &F) {
1543           LLVM_DEBUG(dbgs()
1544                      << "Adding nounwind attr to fn " << F.getName() << "\n");
1545           F.setDoesNotThrow();
1546           ++NumNoUnwind;
1547         },
1548         /* RequiresExactDefinition= */ true});
1549 
1550   if (!DisableNoFreeInference)
1551     // Request to infer nofree attribute for all the functions in the SCC if
1552     // every callsite within the SCC does not directly or indirectly free
1553     // memory (except for calls to functions within the SCC). Note that nofree
1554     // attribute suffers from derefinement - results may change depending on
1555     // how functions are optimized. Thus it can be inferred only from exact
1556     // definitions.
1557     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1558         Attribute::NoFree,
1559         // Skip functions known not to free memory.
1560         [](const Function &F) { return F.doesNotFreeMemory(); },
1561         // Instructions that break non-deallocating assumption.
1562         [&SCCNodes](Instruction &I) {
1563           return InstrBreaksNoFree(I, SCCNodes);
1564         },
1565         [](Function &F) {
1566           LLVM_DEBUG(dbgs()
1567                      << "Adding nofree attr to fn " << F.getName() << "\n");
1568           F.setDoesNotFreeMemory();
1569           ++NumNoFree;
1570         },
1571         /* RequiresExactDefinition= */ true});
1572 
1573   // Perform all the requested attribute inference actions.
1574   AI.run(SCCNodes, Changed);
1575 }
1576 
1577 static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes,
1578                               SmallSet<Function *, 8> &Changed) {
1579   // Try and identify functions that do not recurse.
1580 
1581   // If the SCC contains multiple nodes we know for sure there is recursion.
1582   if (SCCNodes.size() != 1)
1583     return;
1584 
1585   Function *F = *SCCNodes.begin();
1586   if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
1587     return;
1588 
1589   // If all of the calls in F are identifiable and are to norecurse functions, F
1590   // is norecurse. This check also detects self-recursion as F is not currently
1591   // marked norecurse, so any called from F to F will not be marked norecurse.
1592   for (auto &BB : *F)
1593     for (auto &I : BB.instructionsWithoutDebug())
1594       if (auto *CB = dyn_cast<CallBase>(&I)) {
1595         Function *Callee = CB->getCalledFunction();
1596         if (!Callee || Callee == F || !Callee->doesNotRecurse())
1597           // Function calls a potentially recursive function.
1598           return;
1599       }
1600 
1601   // Every call was to a non-recursive function other than this function, and
1602   // we have no indirect recursion as the SCC size is one. This function cannot
1603   // recurse.
1604   F->setDoesNotRecurse();
1605   ++NumNoRecurse;
1606   Changed.insert(F);
1607 }
1608 
1609 static bool instructionDoesNotReturn(Instruction &I) {
1610   if (auto *CB = dyn_cast<CallBase>(&I))
1611     return CB->hasFnAttr(Attribute::NoReturn);
1612   return false;
1613 }
1614 
1615 // A basic block can only return if it terminates with a ReturnInst and does not
1616 // contain calls to noreturn functions.
1617 static bool basicBlockCanReturn(BasicBlock &BB) {
1618   if (!isa<ReturnInst>(BB.getTerminator()))
1619     return false;
1620   return none_of(BB, instructionDoesNotReturn);
1621 }
1622 
1623 // Set the noreturn function attribute if possible.
1624 static void addNoReturnAttrs(const SCCNodeSet &SCCNodes,
1625                              SmallSet<Function *, 8> &Changed) {
1626   for (Function *F : SCCNodes) {
1627     if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
1628         F->doesNotReturn())
1629       continue;
1630 
1631     // The function can return if any basic blocks can return.
1632     // FIXME: this doesn't handle recursion or unreachable blocks.
1633     if (none_of(*F, basicBlockCanReturn)) {
1634       F->setDoesNotReturn();
1635       Changed.insert(F);
1636     }
1637   }
1638 }
1639 
1640 static bool functionWillReturn(const Function &F) {
1641   // We can infer and propagate function attributes only when we know that the
1642   // definition we'll get at link time is *exactly* the definition we see now.
1643   // For more details, see GlobalValue::mayBeDerefined.
1644   if (!F.hasExactDefinition())
1645     return false;
1646 
1647   // Must-progress function without side-effects must return.
1648   if (F.mustProgress() && F.onlyReadsMemory())
1649     return true;
1650 
1651   // Can only analyze functions with a definition.
1652   if (F.isDeclaration())
1653     return false;
1654 
1655   // Functions with loops require more sophisticated analysis, as the loop
1656   // may be infinite. For now, don't try to handle them.
1657   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>> Backedges;
1658   FindFunctionBackedges(F, Backedges);
1659   if (!Backedges.empty())
1660     return false;
1661 
1662   // If there are no loops, then the function is willreturn if all calls in
1663   // it are willreturn.
1664   return all_of(instructions(F), [](const Instruction &I) {
1665     return I.willReturn();
1666   });
1667 }
1668 
1669 // Set the willreturn function attribute if possible.
1670 static void addWillReturn(const SCCNodeSet &SCCNodes,
1671                           SmallSet<Function *, 8> &Changed) {
1672   for (Function *F : SCCNodes) {
1673     if (!F || F->willReturn() || !functionWillReturn(*F))
1674       continue;
1675 
1676     F->setWillReturn();
1677     NumWillReturn++;
1678     Changed.insert(F);
1679   }
1680 }
1681 
1682 // Return true if this is an atomic which has an ordering stronger than
1683 // unordered.  Note that this is different than the predicate we use in
1684 // Attributor.  Here we chose to be conservative and consider monotonic
1685 // operations potentially synchronizing.  We generally don't do much with
1686 // monotonic operations, so this is simply risk reduction.
1687 static bool isOrderedAtomic(Instruction *I) {
1688   if (!I->isAtomic())
1689     return false;
1690 
1691   if (auto *FI = dyn_cast<FenceInst>(I))
1692     // All legal orderings for fence are stronger than monotonic.
1693     return FI->getSyncScopeID() != SyncScope::SingleThread;
1694   else if (isa<AtomicCmpXchgInst>(I) || isa<AtomicRMWInst>(I))
1695     return true;
1696   else if (auto *SI = dyn_cast<StoreInst>(I))
1697     return !SI->isUnordered();
1698   else if (auto *LI = dyn_cast<LoadInst>(I))
1699     return !LI->isUnordered();
1700   else {
1701     llvm_unreachable("unknown atomic instruction?");
1702   }
1703 }
1704 
1705 static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes) {
1706   // Volatile may synchronize
1707   if (I.isVolatile())
1708     return true;
1709 
1710   // An ordered atomic may synchronize.  (See comment about on monotonic.)
1711   if (isOrderedAtomic(&I))
1712     return true;
1713 
1714   auto *CB = dyn_cast<CallBase>(&I);
1715   if (!CB)
1716     // Non call site cases covered by the two checks above
1717     return false;
1718 
1719   if (CB->hasFnAttr(Attribute::NoSync))
1720     return false;
1721 
1722   // Non volatile memset/memcpy/memmoves are nosync
1723   // NOTE: Only intrinsics with volatile flags should be handled here.  All
1724   // others should be marked in Intrinsics.td.
1725   if (auto *MI = dyn_cast<MemIntrinsic>(&I))
1726     if (!MI->isVolatile())
1727       return false;
1728 
1729   // Speculatively assume in SCC.
1730   if (Function *Callee = CB->getCalledFunction())
1731     if (SCCNodes.contains(Callee))
1732       return false;
1733 
1734   return true;
1735 }
1736 
1737 // Infer the nosync attribute.
1738 static void addNoSyncAttr(const SCCNodeSet &SCCNodes,
1739                           SmallSet<Function *, 8> &Changed) {
1740   AttributeInferer AI;
1741   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1742       Attribute::NoSync,
1743       // Skip already marked functions.
1744       [](const Function &F) { return F.hasNoSync(); },
1745       // Instructions that break nosync assumption.
1746       [&SCCNodes](Instruction &I) {
1747         return InstrBreaksNoSync(I, SCCNodes);
1748       },
1749       [](Function &F) {
1750         LLVM_DEBUG(dbgs()
1751                    << "Adding nosync attr to fn " << F.getName() << "\n");
1752         F.setNoSync();
1753         ++NumNoSync;
1754       },
1755       /* RequiresExactDefinition= */ true});
1756   AI.run(SCCNodes, Changed);
1757 }
1758 
1759 static SCCNodesResult createSCCNodeSet(ArrayRef<Function *> Functions) {
1760   SCCNodesResult Res;
1761   Res.HasUnknownCall = false;
1762   for (Function *F : Functions) {
1763     if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked) ||
1764         F->isPresplitCoroutine()) {
1765       // Treat any function we're trying not to optimize as if it were an
1766       // indirect call and omit it from the node set used below.
1767       Res.HasUnknownCall = true;
1768       continue;
1769     }
1770     // Track whether any functions in this SCC have an unknown call edge.
1771     // Note: if this is ever a performance hit, we can common it with
1772     // subsequent routines which also do scans over the instructions of the
1773     // function.
1774     if (!Res.HasUnknownCall) {
1775       for (Instruction &I : instructions(*F)) {
1776         if (auto *CB = dyn_cast<CallBase>(&I)) {
1777           if (!CB->getCalledFunction()) {
1778             Res.HasUnknownCall = true;
1779             break;
1780           }
1781         }
1782       }
1783     }
1784     Res.SCCNodes.insert(F);
1785   }
1786   return Res;
1787 }
1788 
1789 template <typename AARGetterT>
1790 static SmallSet<Function *, 8>
1791 deriveAttrsInPostOrder(ArrayRef<Function *> Functions, AARGetterT &&AARGetter) {
1792   SCCNodesResult Nodes = createSCCNodeSet(Functions);
1793 
1794   // Bail if the SCC only contains optnone functions.
1795   if (Nodes.SCCNodes.empty())
1796     return {};
1797 
1798   SmallSet<Function *, 8> Changed;
1799 
1800   addArgumentReturnedAttrs(Nodes.SCCNodes, Changed);
1801   addReadAttrs(Nodes.SCCNodes, AARGetter, Changed);
1802   addArgumentAttrs(Nodes.SCCNodes, Changed);
1803   inferConvergent(Nodes.SCCNodes, Changed);
1804   addNoReturnAttrs(Nodes.SCCNodes, Changed);
1805   addWillReturn(Nodes.SCCNodes, Changed);
1806 
1807   // If we have no external nodes participating in the SCC, we can deduce some
1808   // more precise attributes as well.
1809   if (!Nodes.HasUnknownCall) {
1810     addNoAliasAttrs(Nodes.SCCNodes, Changed);
1811     addNonNullAttrs(Nodes.SCCNodes, Changed);
1812     inferAttrsFromFunctionBodies(Nodes.SCCNodes, Changed);
1813     addNoRecurseAttrs(Nodes.SCCNodes, Changed);
1814   }
1815 
1816   addNoSyncAttr(Nodes.SCCNodes, Changed);
1817 
1818   // Finally, infer the maximal set of attributes from the ones we've inferred
1819   // above.  This is handling the cases where one attribute on a signature
1820   // implies another, but for implementation reasons the inference rule for
1821   // the later is missing (or simply less sophisticated).
1822   for (Function *F : Nodes.SCCNodes)
1823     if (F)
1824       if (inferAttributesFromOthers(*F))
1825         Changed.insert(F);
1826 
1827   return Changed;
1828 }
1829 
1830 PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
1831                                                   CGSCCAnalysisManager &AM,
1832                                                   LazyCallGraph &CG,
1833                                                   CGSCCUpdateResult &) {
1834   FunctionAnalysisManager &FAM =
1835       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1836 
1837   // We pass a lambda into functions to wire them up to the analysis manager
1838   // for getting function analyses.
1839   auto AARGetter = [&](Function &F) -> AAResults & {
1840     return FAM.getResult<AAManager>(F);
1841   };
1842 
1843   SmallVector<Function *, 8> Functions;
1844   for (LazyCallGraph::Node &N : C) {
1845     Functions.push_back(&N.getFunction());
1846   }
1847 
1848   auto ChangedFunctions = deriveAttrsInPostOrder(Functions, AARGetter);
1849   if (ChangedFunctions.empty())
1850     return PreservedAnalyses::all();
1851 
1852   // Invalidate analyses for modified functions so that we don't have to
1853   // invalidate all analyses for all functions in this SCC.
1854   PreservedAnalyses FuncPA;
1855   // We haven't changed the CFG for modified functions.
1856   FuncPA.preserveSet<CFGAnalyses>();
1857   for (Function *Changed : ChangedFunctions) {
1858     FAM.invalidate(*Changed, FuncPA);
1859     // Also invalidate any direct callers of changed functions since analyses
1860     // may care about attributes of direct callees. For example, MemorySSA cares
1861     // about whether or not a call's callee modifies memory and queries that
1862     // through function attributes.
1863     for (auto *U : Changed->users()) {
1864       if (auto *Call = dyn_cast<CallBase>(U)) {
1865         if (Call->getCalledFunction() == Changed)
1866           FAM.invalidate(*Call->getFunction(), FuncPA);
1867       }
1868     }
1869   }
1870 
1871   PreservedAnalyses PA;
1872   // We have not added or removed functions.
1873   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1874   // We already invalidated all relevant function analyses above.
1875   PA.preserveSet<AllAnalysesOn<Function>>();
1876   return PA;
1877 }
1878 
1879 namespace {
1880 
1881 struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1882   // Pass identification, replacement for typeid
1883   static char ID;
1884 
1885   PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
1886     initializePostOrderFunctionAttrsLegacyPassPass(
1887         *PassRegistry::getPassRegistry());
1888   }
1889 
1890   bool runOnSCC(CallGraphSCC &SCC) override;
1891 
1892   void getAnalysisUsage(AnalysisUsage &AU) const override {
1893     AU.setPreservesCFG();
1894     AU.addRequired<AssumptionCacheTracker>();
1895     getAAResultsAnalysisUsage(AU);
1896     CallGraphSCCPass::getAnalysisUsage(AU);
1897   }
1898 };
1899 
1900 } // end anonymous namespace
1901 
1902 char PostOrderFunctionAttrsLegacyPass::ID = 0;
1903 INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1904                       "Deduce function attributes", false, false)
1905 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1906 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1907 INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1908                     "Deduce function attributes", false, false)
1909 
1910 Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1911   return new PostOrderFunctionAttrsLegacyPass();
1912 }
1913 
1914 template <typename AARGetterT>
1915 static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
1916   SmallVector<Function *, 8> Functions;
1917   for (CallGraphNode *I : SCC) {
1918     Functions.push_back(I->getFunction());
1919   }
1920 
1921   return !deriveAttrsInPostOrder(Functions, AARGetter).empty();
1922 }
1923 
1924 bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1925   if (skipSCC(SCC))
1926     return false;
1927   return runImpl(SCC, LegacyAARGetter(*this));
1928 }
1929 
1930 namespace {
1931 
1932 struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
1933   // Pass identification, replacement for typeid
1934   static char ID;
1935 
1936   ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
1937     initializeReversePostOrderFunctionAttrsLegacyPassPass(
1938         *PassRegistry::getPassRegistry());
1939   }
1940 
1941   bool runOnModule(Module &M) override;
1942 
1943   void getAnalysisUsage(AnalysisUsage &AU) const override {
1944     AU.setPreservesCFG();
1945     AU.addRequired<CallGraphWrapperPass>();
1946     AU.addPreserved<CallGraphWrapperPass>();
1947   }
1948 };
1949 
1950 } // end anonymous namespace
1951 
1952 char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1953 
1954 INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass,
1955                       "rpo-function-attrs", "Deduce function attributes in RPO",
1956                       false, false)
1957 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1958 INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass,
1959                     "rpo-function-attrs", "Deduce function attributes in RPO",
1960                     false, false)
1961 
1962 Pass *llvm::createReversePostOrderFunctionAttrsPass() {
1963   return new ReversePostOrderFunctionAttrsLegacyPass();
1964 }
1965 
1966 static bool addNoRecurseAttrsTopDown(Function &F) {
1967   // We check the preconditions for the function prior to calling this to avoid
1968   // the cost of building up a reversible post-order list. We assert them here
1969   // to make sure none of the invariants this relies on were violated.
1970   assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1971   assert(!F.doesNotRecurse() &&
1972          "This function has already been deduced as norecurs!");
1973   assert(F.hasInternalLinkage() &&
1974          "Can only do top-down deduction for internal linkage functions!");
1975 
1976   // If F is internal and all of its uses are calls from a non-recursive
1977   // functions, then none of its calls could in fact recurse without going
1978   // through a function marked norecurse, and so we can mark this function too
1979   // as norecurse. Note that the uses must actually be calls -- otherwise
1980   // a pointer to this function could be returned from a norecurse function but
1981   // this function could be recursively (indirectly) called. Note that this
1982   // also detects if F is directly recursive as F is not yet marked as
1983   // a norecurse function.
1984   for (auto *U : F.users()) {
1985     auto *I = dyn_cast<Instruction>(U);
1986     if (!I)
1987       return false;
1988     CallBase *CB = dyn_cast<CallBase>(I);
1989     if (!CB || !CB->getParent()->getParent()->doesNotRecurse())
1990       return false;
1991   }
1992   F.setDoesNotRecurse();
1993   ++NumNoRecurse;
1994   return true;
1995 }
1996 
1997 static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
1998   // We only have a post-order SCC traversal (because SCCs are inherently
1999   // discovered in post-order), so we accumulate them in a vector and then walk
2000   // it in reverse. This is simpler than using the RPO iterator infrastructure
2001   // because we need to combine SCC detection and the PO walk of the call
2002   // graph. We can also cheat egregiously because we're primarily interested in
2003   // synthesizing norecurse and so we can only save the singular SCCs as SCCs
2004   // with multiple functions in them will clearly be recursive.
2005   SmallVector<Function *, 16> Worklist;
2006   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
2007     if (I->size() != 1)
2008       continue;
2009 
2010     Function *F = I->front()->getFunction();
2011     if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
2012         F->hasInternalLinkage())
2013       Worklist.push_back(F);
2014   }
2015 
2016   bool Changed = false;
2017   for (auto *F : llvm::reverse(Worklist))
2018     Changed |= addNoRecurseAttrsTopDown(*F);
2019 
2020   return Changed;
2021 }
2022 
2023 bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
2024   if (skipModule(M))
2025     return false;
2026 
2027   auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
2028 
2029   return deduceFunctionAttributeInRPO(M, CG);
2030 }
2031 
2032 PreservedAnalyses
2033 ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
2034   auto &CG = AM.getResult<CallGraphAnalysis>(M);
2035 
2036   if (!deduceFunctionAttributeInRPO(M, CG))
2037     return PreservedAnalyses::all();
2038 
2039   PreservedAnalyses PA;
2040   PA.preserve<CallGraphAnalysis>();
2041   return PA;
2042 }
2043