xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/FunctionAttrs.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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       CallBase &CB = cast<CallBase>(*I);
685       if (CB.isCallee(U)) {
686         IsRead = true;
687         // Note that indirect calls do not capture, see comment in
688         // CaptureTracking for context
689         continue;
690       }
691 
692       // Given we've explictily handled the callee operand above, what's left
693       // must be a data operand (e.g. argument or operand bundle)
694       const unsigned UseIndex = CB.getDataOperandNo(U);
695 
696       if (!CB.doesNotCapture(UseIndex)) {
697         if (!CB.onlyReadsMemory())
698           // If the callee can save a copy into other memory, then simply
699           // scanning uses of the call is insufficient.  We have no way
700           // of tracking copies of the pointer through memory to see
701           // if a reloaded copy is written to, thus we must give up.
702           return Attribute::None;
703         // Push users for processing once we finish this one
704         if (!I->getType()->isVoidTy())
705           for (Use &UU : I->uses())
706             if (Visited.insert(&UU).second)
707               Worklist.push_back(&UU);
708       }
709 
710       if (CB.doesNotAccessMemory())
711         continue;
712 
713       if (Function *F = CB.getCalledFunction())
714         if (CB.isArgOperand(U) && UseIndex < F->arg_size() &&
715             SCCNodes.count(F->getArg(UseIndex)))
716           // This is an argument which is part of the speculative SCC.  Note
717           // that only operands corresponding to formal arguments of the callee
718           // can participate in the speculation.
719           break;
720 
721       // The accessors used on call site here do the right thing for calls and
722       // invokes with operand bundles.
723       if (!CB.onlyReadsMemory() && !CB.onlyReadsMemory(UseIndex))
724         return Attribute::None;
725       if (!CB.doesNotAccessMemory(UseIndex))
726         IsRead = true;
727       break;
728     }
729 
730     case Instruction::Load:
731       // A volatile load has side effects beyond what readonly can be relied
732       // upon.
733       if (cast<LoadInst>(I)->isVolatile())
734         return Attribute::None;
735 
736       IsRead = true;
737       break;
738 
739     case Instruction::Store:
740       if (cast<StoreInst>(I)->getValueOperand() == *U)
741         // untrackable capture
742         return Attribute::None;
743 
744       // A volatile store has side effects beyond what writeonly can be relied
745       // upon.
746       if (cast<StoreInst>(I)->isVolatile())
747         return Attribute::None;
748 
749       IsWrite = true;
750       break;
751 
752     case Instruction::ICmp:
753     case Instruction::Ret:
754       break;
755 
756     default:
757       return Attribute::None;
758     }
759   }
760 
761   if (IsWrite && IsRead)
762     return Attribute::None;
763   else if (IsRead)
764     return Attribute::ReadOnly;
765   else if (IsWrite)
766     return Attribute::WriteOnly;
767   else
768     return Attribute::ReadNone;
769 }
770 
771 /// Deduce returned attributes for the SCC.
772 static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes,
773                                      SmallSet<Function *, 8> &Changed) {
774   // Check each function in turn, determining if an argument is always returned.
775   for (Function *F : SCCNodes) {
776     // We can infer and propagate function attributes only when we know that the
777     // definition we'll get at link time is *exactly* the definition we see now.
778     // For more details, see GlobalValue::mayBeDerefined.
779     if (!F->hasExactDefinition())
780       continue;
781 
782     if (F->getReturnType()->isVoidTy())
783       continue;
784 
785     // There is nothing to do if an argument is already marked as 'returned'.
786     if (llvm::any_of(F->args(),
787                      [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
788       continue;
789 
790     auto FindRetArg = [&]() -> Value * {
791       Value *RetArg = nullptr;
792       for (BasicBlock &BB : *F)
793         if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
794           // Note that stripPointerCasts should look through functions with
795           // returned arguments.
796           Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
797           if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
798             return nullptr;
799 
800           if (!RetArg)
801             RetArg = RetVal;
802           else if (RetArg != RetVal)
803             return nullptr;
804         }
805 
806       return RetArg;
807     };
808 
809     if (Value *RetArg = FindRetArg()) {
810       auto *A = cast<Argument>(RetArg);
811       A->addAttr(Attribute::Returned);
812       ++NumReturned;
813       Changed.insert(F);
814     }
815   }
816 }
817 
818 /// If a callsite has arguments that are also arguments to the parent function,
819 /// try to propagate attributes from the callsite's arguments to the parent's
820 /// arguments. This may be important because inlining can cause information loss
821 /// when attribute knowledge disappears with the inlined call.
822 static bool addArgumentAttrsFromCallsites(Function &F) {
823   if (!EnableNonnullArgPropagation)
824     return false;
825 
826   bool Changed = false;
827 
828   // For an argument attribute to transfer from a callsite to the parent, the
829   // call must be guaranteed to execute every time the parent is called.
830   // Conservatively, just check for calls in the entry block that are guaranteed
831   // to execute.
832   // TODO: This could be enhanced by testing if the callsite post-dominates the
833   // entry block or by doing simple forward walks or backward walks to the
834   // callsite.
835   BasicBlock &Entry = F.getEntryBlock();
836   for (Instruction &I : Entry) {
837     if (auto *CB = dyn_cast<CallBase>(&I)) {
838       if (auto *CalledFunc = CB->getCalledFunction()) {
839         for (auto &CSArg : CalledFunc->args()) {
840           if (!CSArg.hasNonNullAttr(/* AllowUndefOrPoison */ false))
841             continue;
842 
843           // If the non-null callsite argument operand is an argument to 'F'
844           // (the caller) and the call is guaranteed to execute, then the value
845           // must be non-null throughout 'F'.
846           auto *FArg = dyn_cast<Argument>(CB->getArgOperand(CSArg.getArgNo()));
847           if (FArg && !FArg->hasNonNullAttr()) {
848             FArg->addAttr(Attribute::NonNull);
849             Changed = true;
850           }
851         }
852       }
853     }
854     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
855       break;
856   }
857 
858   return Changed;
859 }
860 
861 static bool addAccessAttr(Argument *A, Attribute::AttrKind R) {
862   assert((R == Attribute::ReadOnly || R == Attribute::ReadNone ||
863           R == Attribute::WriteOnly)
864          && "Must be an access attribute.");
865   assert(A && "Argument must not be null.");
866 
867   // If the argument already has the attribute, nothing needs to be done.
868   if (A->hasAttribute(R))
869       return false;
870 
871   // Otherwise, remove potentially conflicting attribute, add the new one,
872   // and update statistics.
873   A->removeAttr(Attribute::WriteOnly);
874   A->removeAttr(Attribute::ReadOnly);
875   A->removeAttr(Attribute::ReadNone);
876   A->addAttr(R);
877   if (R == Attribute::ReadOnly)
878     ++NumReadOnlyArg;
879   else if (R == Attribute::WriteOnly)
880     ++NumWriteOnlyArg;
881   else
882     ++NumReadNoneArg;
883   return true;
884 }
885 
886 /// Deduce nocapture attributes for the SCC.
887 static void addArgumentAttrs(const SCCNodeSet &SCCNodes,
888                              SmallSet<Function *, 8> &Changed) {
889   ArgumentGraph AG;
890 
891   // Check each function in turn, determining which pointer arguments are not
892   // captured.
893   for (Function *F : SCCNodes) {
894     // We can infer and propagate function attributes only when we know that the
895     // definition we'll get at link time is *exactly* the definition we see now.
896     // For more details, see GlobalValue::mayBeDerefined.
897     if (!F->hasExactDefinition())
898       continue;
899 
900     if (addArgumentAttrsFromCallsites(*F))
901       Changed.insert(F);
902 
903     // Functions that are readonly (or readnone) and nounwind and don't return
904     // a value can't capture arguments. Don't analyze them.
905     if (F->onlyReadsMemory() && F->doesNotThrow() &&
906         F->getReturnType()->isVoidTy()) {
907       for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
908            ++A) {
909         if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
910           A->addAttr(Attribute::NoCapture);
911           ++NumNoCapture;
912           Changed.insert(F);
913         }
914       }
915       continue;
916     }
917 
918     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
919          ++A) {
920       if (!A->getType()->isPointerTy())
921         continue;
922       bool HasNonLocalUses = false;
923       if (!A->hasNoCaptureAttr()) {
924         ArgumentUsesTracker Tracker(SCCNodes);
925         PointerMayBeCaptured(&*A, &Tracker);
926         if (!Tracker.Captured) {
927           if (Tracker.Uses.empty()) {
928             // If it's trivially not captured, mark it nocapture now.
929             A->addAttr(Attribute::NoCapture);
930             ++NumNoCapture;
931             Changed.insert(F);
932           } else {
933             // If it's not trivially captured and not trivially not captured,
934             // then it must be calling into another function in our SCC. Save
935             // its particulars for Argument-SCC analysis later.
936             ArgumentGraphNode *Node = AG[&*A];
937             for (Argument *Use : Tracker.Uses) {
938               Node->Uses.push_back(AG[Use]);
939               if (Use != &*A)
940                 HasNonLocalUses = true;
941             }
942           }
943         }
944         // Otherwise, it's captured. Don't bother doing SCC analysis on it.
945       }
946       if (!HasNonLocalUses && !A->onlyReadsMemory()) {
947         // Can we determine that it's readonly/readnone/writeonly without doing
948         // an SCC? Note that we don't allow any calls at all here, or else our
949         // result will be dependent on the iteration order through the
950         // functions in the SCC.
951         SmallPtrSet<Argument *, 8> Self;
952         Self.insert(&*A);
953         Attribute::AttrKind R = determinePointerAccessAttrs(&*A, Self);
954         if (R != Attribute::None)
955           if (addAccessAttr(A, R))
956             Changed.insert(F);
957       }
958     }
959   }
960 
961   // The graph we've collected is partial because we stopped scanning for
962   // argument uses once we solved the argument trivially. These partial nodes
963   // show up as ArgumentGraphNode objects with an empty Uses list, and for
964   // these nodes the final decision about whether they capture has already been
965   // made.  If the definition doesn't have a 'nocapture' attribute by now, it
966   // captures.
967 
968   for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
969     const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
970     if (ArgumentSCC.size() == 1) {
971       if (!ArgumentSCC[0]->Definition)
972         continue; // synthetic root node
973 
974       // eg. "void f(int* x) { if (...) f(x); }"
975       if (ArgumentSCC[0]->Uses.size() == 1 &&
976           ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
977         Argument *A = ArgumentSCC[0]->Definition;
978         A->addAttr(Attribute::NoCapture);
979         ++NumNoCapture;
980         Changed.insert(A->getParent());
981 
982         // Infer the access attributes given the new nocapture one
983         SmallPtrSet<Argument *, 8> Self;
984         Self.insert(&*A);
985         Attribute::AttrKind R = determinePointerAccessAttrs(&*A, Self);
986         if (R != Attribute::None)
987           addAccessAttr(A, R);
988       }
989       continue;
990     }
991 
992     bool SCCCaptured = false;
993     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
994          I != E && !SCCCaptured; ++I) {
995       ArgumentGraphNode *Node = *I;
996       if (Node->Uses.empty()) {
997         if (!Node->Definition->hasNoCaptureAttr())
998           SCCCaptured = true;
999       }
1000     }
1001     if (SCCCaptured)
1002       continue;
1003 
1004     SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
1005     // Fill ArgumentSCCNodes with the elements of the ArgumentSCC.  Used for
1006     // quickly looking up whether a given Argument is in this ArgumentSCC.
1007     for (ArgumentGraphNode *I : ArgumentSCC) {
1008       ArgumentSCCNodes.insert(I->Definition);
1009     }
1010 
1011     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
1012          I != E && !SCCCaptured; ++I) {
1013       ArgumentGraphNode *N = *I;
1014       for (ArgumentGraphNode *Use : N->Uses) {
1015         Argument *A = Use->Definition;
1016         if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
1017           continue;
1018         SCCCaptured = true;
1019         break;
1020       }
1021     }
1022     if (SCCCaptured)
1023       continue;
1024 
1025     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
1026       Argument *A = ArgumentSCC[i]->Definition;
1027       A->addAttr(Attribute::NoCapture);
1028       ++NumNoCapture;
1029       Changed.insert(A->getParent());
1030     }
1031 
1032     // We also want to compute readonly/readnone/writeonly. With a small number
1033     // of false negatives, we can assume that any pointer which is captured
1034     // isn't going to be provably readonly or readnone, since by definition
1035     // we can't analyze all uses of a captured pointer.
1036     //
1037     // The false negatives happen when the pointer is captured by a function
1038     // that promises readonly/readnone behaviour on the pointer, then the
1039     // pointer's lifetime ends before anything that writes to arbitrary memory.
1040     // Also, a readonly/readnone pointer may be returned, but returning a
1041     // pointer is capturing it.
1042 
1043     auto meetAccessAttr = [](Attribute::AttrKind A, Attribute::AttrKind B) {
1044       if (A == B)
1045         return A;
1046       if (A == Attribute::ReadNone)
1047         return B;
1048       if (B == Attribute::ReadNone)
1049         return A;
1050       return Attribute::None;
1051     };
1052 
1053     Attribute::AttrKind AccessAttr = Attribute::ReadNone;
1054     for (unsigned i = 0, e = ArgumentSCC.size();
1055          i != e && AccessAttr != Attribute::None; ++i) {
1056       Argument *A = ArgumentSCC[i]->Definition;
1057       Attribute::AttrKind K = determinePointerAccessAttrs(A, ArgumentSCCNodes);
1058       AccessAttr = meetAccessAttr(AccessAttr, K);
1059     }
1060 
1061     if (AccessAttr != Attribute::None) {
1062       for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
1063         Argument *A = ArgumentSCC[i]->Definition;
1064         if (addAccessAttr(A, AccessAttr))
1065           Changed.insert(A->getParent());
1066       }
1067     }
1068   }
1069 }
1070 
1071 /// Tests whether a function is "malloc-like".
1072 ///
1073 /// A function is "malloc-like" if it returns either null or a pointer that
1074 /// doesn't alias any other pointer visible to the caller.
1075 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
1076   SmallSetVector<Value *, 8> FlowsToReturn;
1077   for (BasicBlock &BB : *F)
1078     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1079       FlowsToReturn.insert(Ret->getReturnValue());
1080 
1081   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1082     Value *RetVal = FlowsToReturn[i];
1083 
1084     if (Constant *C = dyn_cast<Constant>(RetVal)) {
1085       if (!C->isNullValue() && !isa<UndefValue>(C))
1086         return false;
1087 
1088       continue;
1089     }
1090 
1091     if (isa<Argument>(RetVal))
1092       return false;
1093 
1094     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
1095       switch (RVI->getOpcode()) {
1096       // Extend the analysis by looking upwards.
1097       case Instruction::BitCast:
1098       case Instruction::GetElementPtr:
1099       case Instruction::AddrSpaceCast:
1100         FlowsToReturn.insert(RVI->getOperand(0));
1101         continue;
1102       case Instruction::Select: {
1103         SelectInst *SI = cast<SelectInst>(RVI);
1104         FlowsToReturn.insert(SI->getTrueValue());
1105         FlowsToReturn.insert(SI->getFalseValue());
1106         continue;
1107       }
1108       case Instruction::PHI: {
1109         PHINode *PN = cast<PHINode>(RVI);
1110         for (Value *IncValue : PN->incoming_values())
1111           FlowsToReturn.insert(IncValue);
1112         continue;
1113       }
1114 
1115       // Check whether the pointer came from an allocation.
1116       case Instruction::Alloca:
1117         break;
1118       case Instruction::Call:
1119       case Instruction::Invoke: {
1120         CallBase &CB = cast<CallBase>(*RVI);
1121         if (CB.hasRetAttr(Attribute::NoAlias))
1122           break;
1123         if (CB.getCalledFunction() && SCCNodes.count(CB.getCalledFunction()))
1124           break;
1125         LLVM_FALLTHROUGH;
1126       }
1127       default:
1128         return false; // Did not come from an allocation.
1129       }
1130 
1131     if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
1132       return false;
1133   }
1134 
1135   return true;
1136 }
1137 
1138 /// Deduce noalias attributes for the SCC.
1139 static void addNoAliasAttrs(const SCCNodeSet &SCCNodes,
1140                             SmallSet<Function *, 8> &Changed) {
1141   // Check each function in turn, determining which functions return noalias
1142   // pointers.
1143   for (Function *F : SCCNodes) {
1144     // Already noalias.
1145     if (F->returnDoesNotAlias())
1146       continue;
1147 
1148     // We can infer and propagate function attributes only when we know that the
1149     // definition we'll get at link time is *exactly* the definition we see now.
1150     // For more details, see GlobalValue::mayBeDerefined.
1151     if (!F->hasExactDefinition())
1152       return;
1153 
1154     // We annotate noalias return values, which are only applicable to
1155     // pointer types.
1156     if (!F->getReturnType()->isPointerTy())
1157       continue;
1158 
1159     if (!isFunctionMallocLike(F, SCCNodes))
1160       return;
1161   }
1162 
1163   for (Function *F : SCCNodes) {
1164     if (F->returnDoesNotAlias() ||
1165         !F->getReturnType()->isPointerTy())
1166       continue;
1167 
1168     F->setReturnDoesNotAlias();
1169     ++NumNoAlias;
1170     Changed.insert(F);
1171   }
1172 }
1173 
1174 /// Tests whether this function is known to not return null.
1175 ///
1176 /// Requires that the function returns a pointer.
1177 ///
1178 /// Returns true if it believes the function will not return a null, and sets
1179 /// \p Speculative based on whether the returned conclusion is a speculative
1180 /// conclusion due to SCC calls.
1181 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
1182                             bool &Speculative) {
1183   assert(F->getReturnType()->isPointerTy() &&
1184          "nonnull only meaningful on pointer types");
1185   Speculative = false;
1186 
1187   SmallSetVector<Value *, 8> FlowsToReturn;
1188   for (BasicBlock &BB : *F)
1189     if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1190       FlowsToReturn.insert(Ret->getReturnValue());
1191 
1192   auto &DL = F->getParent()->getDataLayout();
1193 
1194   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1195     Value *RetVal = FlowsToReturn[i];
1196 
1197     // If this value is locally known to be non-null, we're good
1198     if (isKnownNonZero(RetVal, DL))
1199       continue;
1200 
1201     // Otherwise, we need to look upwards since we can't make any local
1202     // conclusions.
1203     Instruction *RVI = dyn_cast<Instruction>(RetVal);
1204     if (!RVI)
1205       return false;
1206     switch (RVI->getOpcode()) {
1207     // Extend the analysis by looking upwards.
1208     case Instruction::BitCast:
1209     case Instruction::GetElementPtr:
1210     case Instruction::AddrSpaceCast:
1211       FlowsToReturn.insert(RVI->getOperand(0));
1212       continue;
1213     case Instruction::Select: {
1214       SelectInst *SI = cast<SelectInst>(RVI);
1215       FlowsToReturn.insert(SI->getTrueValue());
1216       FlowsToReturn.insert(SI->getFalseValue());
1217       continue;
1218     }
1219     case Instruction::PHI: {
1220       PHINode *PN = cast<PHINode>(RVI);
1221       for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1222         FlowsToReturn.insert(PN->getIncomingValue(i));
1223       continue;
1224     }
1225     case Instruction::Call:
1226     case Instruction::Invoke: {
1227       CallBase &CB = cast<CallBase>(*RVI);
1228       Function *Callee = CB.getCalledFunction();
1229       // A call to a node within the SCC is assumed to return null until
1230       // proven otherwise
1231       if (Callee && SCCNodes.count(Callee)) {
1232         Speculative = true;
1233         continue;
1234       }
1235       return false;
1236     }
1237     default:
1238       return false; // Unknown source, may be null
1239     };
1240     llvm_unreachable("should have either continued or returned");
1241   }
1242 
1243   return true;
1244 }
1245 
1246 /// Deduce nonnull attributes for the SCC.
1247 static void addNonNullAttrs(const SCCNodeSet &SCCNodes,
1248                             SmallSet<Function *, 8> &Changed) {
1249   // Speculative that all functions in the SCC return only nonnull
1250   // pointers.  We may refute this as we analyze functions.
1251   bool SCCReturnsNonNull = true;
1252 
1253   // Check each function in turn, determining which functions return nonnull
1254   // pointers.
1255   for (Function *F : SCCNodes) {
1256     // Already nonnull.
1257     if (F->getAttributes().hasRetAttr(Attribute::NonNull))
1258       continue;
1259 
1260     // We can infer and propagate function attributes only when we know that the
1261     // definition we'll get at link time is *exactly* the definition we see now.
1262     // For more details, see GlobalValue::mayBeDerefined.
1263     if (!F->hasExactDefinition())
1264       return;
1265 
1266     // We annotate nonnull return values, which are only applicable to
1267     // pointer types.
1268     if (!F->getReturnType()->isPointerTy())
1269       continue;
1270 
1271     bool Speculative = false;
1272     if (isReturnNonNull(F, SCCNodes, Speculative)) {
1273       if (!Speculative) {
1274         // Mark the function eagerly since we may discover a function
1275         // which prevents us from speculating about the entire SCC
1276         LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1277                           << " as nonnull\n");
1278         F->addRetAttr(Attribute::NonNull);
1279         ++NumNonNullReturn;
1280         Changed.insert(F);
1281       }
1282       continue;
1283     }
1284     // At least one function returns something which could be null, can't
1285     // speculate any more.
1286     SCCReturnsNonNull = false;
1287   }
1288 
1289   if (SCCReturnsNonNull) {
1290     for (Function *F : SCCNodes) {
1291       if (F->getAttributes().hasRetAttr(Attribute::NonNull) ||
1292           !F->getReturnType()->isPointerTy())
1293         continue;
1294 
1295       LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1296       F->addRetAttr(Attribute::NonNull);
1297       ++NumNonNullReturn;
1298       Changed.insert(F);
1299     }
1300   }
1301 }
1302 
1303 namespace {
1304 
1305 /// Collects a set of attribute inference requests and performs them all in one
1306 /// go on a single SCC Node. Inference involves scanning function bodies
1307 /// looking for instructions that violate attribute assumptions.
1308 /// As soon as all the bodies are fine we are free to set the attribute.
1309 /// Customization of inference for individual attributes is performed by
1310 /// providing a handful of predicates for each attribute.
1311 class AttributeInferer {
1312 public:
1313   /// Describes a request for inference of a single attribute.
1314   struct InferenceDescriptor {
1315 
1316     /// Returns true if this function does not have to be handled.
1317     /// General intent for this predicate is to provide an optimization
1318     /// for functions that do not need this attribute inference at all
1319     /// (say, for functions that already have the attribute).
1320     std::function<bool(const Function &)> SkipFunction;
1321 
1322     /// Returns true if this instruction violates attribute assumptions.
1323     std::function<bool(Instruction &)> InstrBreaksAttribute;
1324 
1325     /// Sets the inferred attribute for this function.
1326     std::function<void(Function &)> SetAttribute;
1327 
1328     /// Attribute we derive.
1329     Attribute::AttrKind AKind;
1330 
1331     /// If true, only "exact" definitions can be used to infer this attribute.
1332     /// See GlobalValue::isDefinitionExact.
1333     bool RequiresExactDefinition;
1334 
1335     InferenceDescriptor(Attribute::AttrKind AK,
1336                         std::function<bool(const Function &)> SkipFunc,
1337                         std::function<bool(Instruction &)> InstrScan,
1338                         std::function<void(Function &)> SetAttr,
1339                         bool ReqExactDef)
1340         : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1341           SetAttribute(SetAttr), AKind(AK),
1342           RequiresExactDefinition(ReqExactDef) {}
1343   };
1344 
1345 private:
1346   SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1347 
1348 public:
1349   void registerAttrInference(InferenceDescriptor AttrInference) {
1350     InferenceDescriptors.push_back(AttrInference);
1351   }
1352 
1353   void run(const SCCNodeSet &SCCNodes, SmallSet<Function *, 8> &Changed);
1354 };
1355 
1356 /// Perform all the requested attribute inference actions according to the
1357 /// attribute predicates stored before.
1358 void AttributeInferer::run(const SCCNodeSet &SCCNodes,
1359                            SmallSet<Function *, 8> &Changed) {
1360   SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1361   // Go through all the functions in SCC and check corresponding attribute
1362   // assumptions for each of them. Attributes that are invalid for this SCC
1363   // will be removed from InferInSCC.
1364   for (Function *F : SCCNodes) {
1365 
1366     // No attributes whose assumptions are still valid - done.
1367     if (InferInSCC.empty())
1368       return;
1369 
1370     // Check if our attributes ever need scanning/can be scanned.
1371     llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1372       if (ID.SkipFunction(*F))
1373         return false;
1374 
1375       // Remove from further inference (invalidate) when visiting a function
1376       // that has no instructions to scan/has an unsuitable definition.
1377       return F->isDeclaration() ||
1378              (ID.RequiresExactDefinition && !F->hasExactDefinition());
1379     });
1380 
1381     // For each attribute still in InferInSCC that doesn't explicitly skip F,
1382     // set up the F instructions scan to verify assumptions of the attribute.
1383     SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1384     llvm::copy_if(
1385         InferInSCC, std::back_inserter(InferInThisFunc),
1386         [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1387 
1388     if (InferInThisFunc.empty())
1389       continue;
1390 
1391     // Start instruction scan.
1392     for (Instruction &I : instructions(*F)) {
1393       llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1394         if (!ID.InstrBreaksAttribute(I))
1395           return false;
1396         // Remove attribute from further inference on any other functions
1397         // because attribute assumptions have just been violated.
1398         llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1399           return D.AKind == ID.AKind;
1400         });
1401         // Remove attribute from the rest of current instruction scan.
1402         return true;
1403       });
1404 
1405       if (InferInThisFunc.empty())
1406         break;
1407     }
1408   }
1409 
1410   if (InferInSCC.empty())
1411     return;
1412 
1413   for (Function *F : SCCNodes)
1414     // At this point InferInSCC contains only functions that were either:
1415     //   - explicitly skipped from scan/inference, or
1416     //   - verified to have no instructions that break attribute assumptions.
1417     // Hence we just go and force the attribute for all non-skipped functions.
1418     for (auto &ID : InferInSCC) {
1419       if (ID.SkipFunction(*F))
1420         continue;
1421       Changed.insert(F);
1422       ID.SetAttribute(*F);
1423     }
1424 }
1425 
1426 struct SCCNodesResult {
1427   SCCNodeSet SCCNodes;
1428   bool HasUnknownCall;
1429 };
1430 
1431 } // end anonymous namespace
1432 
1433 /// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1434 static bool InstrBreaksNonConvergent(Instruction &I,
1435                                      const SCCNodeSet &SCCNodes) {
1436   const CallBase *CB = dyn_cast<CallBase>(&I);
1437   // Breaks non-convergent assumption if CS is a convergent call to a function
1438   // not in the SCC.
1439   return CB && CB->isConvergent() &&
1440          !SCCNodes.contains(CB->getCalledFunction());
1441 }
1442 
1443 /// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1444 static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1445   if (!I.mayThrow())
1446     return false;
1447   if (const auto *CI = dyn_cast<CallInst>(&I)) {
1448     if (Function *Callee = CI->getCalledFunction()) {
1449       // I is a may-throw call to a function inside our SCC. This doesn't
1450       // invalidate our current working assumption that the SCC is no-throw; we
1451       // just have to scan that other function.
1452       if (SCCNodes.contains(Callee))
1453         return false;
1454     }
1455   }
1456   return true;
1457 }
1458 
1459 /// Helper for NoFree inference predicate InstrBreaksAttribute.
1460 static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1461   CallBase *CB = dyn_cast<CallBase>(&I);
1462   if (!CB)
1463     return false;
1464 
1465   if (CB->hasFnAttr(Attribute::NoFree))
1466     return false;
1467 
1468   // Speculatively assume in SCC.
1469   if (Function *Callee = CB->getCalledFunction())
1470     if (SCCNodes.contains(Callee))
1471       return false;
1472 
1473   return true;
1474 }
1475 
1476 /// Attempt to remove convergent function attribute when possible.
1477 ///
1478 /// Returns true if any changes to function attributes were made.
1479 static void inferConvergent(const SCCNodeSet &SCCNodes,
1480                             SmallSet<Function *, 8> &Changed) {
1481   AttributeInferer AI;
1482 
1483   // Request to remove the convergent attribute from all functions in the SCC
1484   // if every callsite within the SCC is not convergent (except for calls
1485   // to functions within the SCC).
1486   // Note: Removal of the attr from the callsites will happen in
1487   // InstCombineCalls separately.
1488   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1489       Attribute::Convergent,
1490       // Skip non-convergent functions.
1491       [](const Function &F) { return !F.isConvergent(); },
1492       // Instructions that break non-convergent assumption.
1493       [SCCNodes](Instruction &I) {
1494         return InstrBreaksNonConvergent(I, SCCNodes);
1495       },
1496       [](Function &F) {
1497         LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1498                           << "\n");
1499         F.setNotConvergent();
1500       },
1501       /* RequiresExactDefinition= */ false});
1502   // Perform all the requested attribute inference actions.
1503   AI.run(SCCNodes, Changed);
1504 }
1505 
1506 /// Infer attributes from all functions in the SCC by scanning every
1507 /// instruction for compliance to the attribute assumptions. Currently it
1508 /// does:
1509 ///   - addition of NoUnwind attribute
1510 ///
1511 /// Returns true if any changes to function attributes were made.
1512 static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes,
1513                                          SmallSet<Function *, 8> &Changed) {
1514   AttributeInferer AI;
1515 
1516   if (!DisableNoUnwindInference)
1517     // Request to infer nounwind attribute for all the functions in the SCC if
1518     // every callsite within the SCC is not throwing (except for calls to
1519     // functions within the SCC). Note that nounwind attribute suffers from
1520     // derefinement - results may change depending on how functions are
1521     // optimized. Thus it can be inferred only from exact definitions.
1522     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1523         Attribute::NoUnwind,
1524         // Skip non-throwing functions.
1525         [](const Function &F) { return F.doesNotThrow(); },
1526         // Instructions that break non-throwing assumption.
1527         [&SCCNodes](Instruction &I) {
1528           return InstrBreaksNonThrowing(I, SCCNodes);
1529         },
1530         [](Function &F) {
1531           LLVM_DEBUG(dbgs()
1532                      << "Adding nounwind attr to fn " << F.getName() << "\n");
1533           F.setDoesNotThrow();
1534           ++NumNoUnwind;
1535         },
1536         /* RequiresExactDefinition= */ true});
1537 
1538   if (!DisableNoFreeInference)
1539     // Request to infer nofree attribute for all the functions in the SCC if
1540     // every callsite within the SCC does not directly or indirectly free
1541     // memory (except for calls to functions within the SCC). Note that nofree
1542     // attribute suffers from derefinement - results may change depending on
1543     // how functions are optimized. Thus it can be inferred only from exact
1544     // definitions.
1545     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1546         Attribute::NoFree,
1547         // Skip functions known not to free memory.
1548         [](const Function &F) { return F.doesNotFreeMemory(); },
1549         // Instructions that break non-deallocating assumption.
1550         [&SCCNodes](Instruction &I) {
1551           return InstrBreaksNoFree(I, SCCNodes);
1552         },
1553         [](Function &F) {
1554           LLVM_DEBUG(dbgs()
1555                      << "Adding nofree attr to fn " << F.getName() << "\n");
1556           F.setDoesNotFreeMemory();
1557           ++NumNoFree;
1558         },
1559         /* RequiresExactDefinition= */ true});
1560 
1561   // Perform all the requested attribute inference actions.
1562   AI.run(SCCNodes, Changed);
1563 }
1564 
1565 static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes,
1566                               SmallSet<Function *, 8> &Changed) {
1567   // Try and identify functions that do not recurse.
1568 
1569   // If the SCC contains multiple nodes we know for sure there is recursion.
1570   if (SCCNodes.size() != 1)
1571     return;
1572 
1573   Function *F = *SCCNodes.begin();
1574   if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
1575     return;
1576 
1577   // If all of the calls in F are identifiable and are to norecurse functions, F
1578   // is norecurse. This check also detects self-recursion as F is not currently
1579   // marked norecurse, so any called from F to F will not be marked norecurse.
1580   for (auto &BB : *F)
1581     for (auto &I : BB.instructionsWithoutDebug())
1582       if (auto *CB = dyn_cast<CallBase>(&I)) {
1583         Function *Callee = CB->getCalledFunction();
1584         if (!Callee || Callee == F || !Callee->doesNotRecurse())
1585           // Function calls a potentially recursive function.
1586           return;
1587       }
1588 
1589   // Every call was to a non-recursive function other than this function, and
1590   // we have no indirect recursion as the SCC size is one. This function cannot
1591   // recurse.
1592   F->setDoesNotRecurse();
1593   ++NumNoRecurse;
1594   Changed.insert(F);
1595 }
1596 
1597 static bool instructionDoesNotReturn(Instruction &I) {
1598   if (auto *CB = dyn_cast<CallBase>(&I))
1599     return CB->hasFnAttr(Attribute::NoReturn);
1600   return false;
1601 }
1602 
1603 // A basic block can only return if it terminates with a ReturnInst and does not
1604 // contain calls to noreturn functions.
1605 static bool basicBlockCanReturn(BasicBlock &BB) {
1606   if (!isa<ReturnInst>(BB.getTerminator()))
1607     return false;
1608   return none_of(BB, instructionDoesNotReturn);
1609 }
1610 
1611 // Set the noreturn function attribute if possible.
1612 static void addNoReturnAttrs(const SCCNodeSet &SCCNodes,
1613                              SmallSet<Function *, 8> &Changed) {
1614   for (Function *F : SCCNodes) {
1615     if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
1616         F->doesNotReturn())
1617       continue;
1618 
1619     // The function can return if any basic blocks can return.
1620     // FIXME: this doesn't handle recursion or unreachable blocks.
1621     if (none_of(*F, basicBlockCanReturn)) {
1622       F->setDoesNotReturn();
1623       Changed.insert(F);
1624     }
1625   }
1626 }
1627 
1628 static bool functionWillReturn(const Function &F) {
1629   // We can infer and propagate function attributes only when we know that the
1630   // definition we'll get at link time is *exactly* the definition we see now.
1631   // For more details, see GlobalValue::mayBeDerefined.
1632   if (!F.hasExactDefinition())
1633     return false;
1634 
1635   // Must-progress function without side-effects must return.
1636   if (F.mustProgress() && F.onlyReadsMemory())
1637     return true;
1638 
1639   // Can only analyze functions with a definition.
1640   if (F.isDeclaration())
1641     return false;
1642 
1643   // Functions with loops require more sophisticated analysis, as the loop
1644   // may be infinite. For now, don't try to handle them.
1645   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>> Backedges;
1646   FindFunctionBackedges(F, Backedges);
1647   if (!Backedges.empty())
1648     return false;
1649 
1650   // If there are no loops, then the function is willreturn if all calls in
1651   // it are willreturn.
1652   return all_of(instructions(F), [](const Instruction &I) {
1653     return I.willReturn();
1654   });
1655 }
1656 
1657 // Set the willreturn function attribute if possible.
1658 static void addWillReturn(const SCCNodeSet &SCCNodes,
1659                           SmallSet<Function *, 8> &Changed) {
1660   for (Function *F : SCCNodes) {
1661     if (!F || F->willReturn() || !functionWillReturn(*F))
1662       continue;
1663 
1664     F->setWillReturn();
1665     NumWillReturn++;
1666     Changed.insert(F);
1667   }
1668 }
1669 
1670 // Return true if this is an atomic which has an ordering stronger than
1671 // unordered.  Note that this is different than the predicate we use in
1672 // Attributor.  Here we chose to be conservative and consider monotonic
1673 // operations potentially synchronizing.  We generally don't do much with
1674 // monotonic operations, so this is simply risk reduction.
1675 static bool isOrderedAtomic(Instruction *I) {
1676   if (!I->isAtomic())
1677     return false;
1678 
1679   if (auto *FI = dyn_cast<FenceInst>(I))
1680     // All legal orderings for fence are stronger than monotonic.
1681     return FI->getSyncScopeID() != SyncScope::SingleThread;
1682   else if (isa<AtomicCmpXchgInst>(I) || isa<AtomicRMWInst>(I))
1683     return true;
1684   else if (auto *SI = dyn_cast<StoreInst>(I))
1685     return !SI->isUnordered();
1686   else if (auto *LI = dyn_cast<LoadInst>(I))
1687     return !LI->isUnordered();
1688   else {
1689     llvm_unreachable("unknown atomic instruction?");
1690   }
1691 }
1692 
1693 static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes) {
1694   // Volatile may synchronize
1695   if (I.isVolatile())
1696     return true;
1697 
1698   // An ordered atomic may synchronize.  (See comment about on monotonic.)
1699   if (isOrderedAtomic(&I))
1700     return true;
1701 
1702   auto *CB = dyn_cast<CallBase>(&I);
1703   if (!CB)
1704     // Non call site cases covered by the two checks above
1705     return false;
1706 
1707   if (CB->hasFnAttr(Attribute::NoSync))
1708     return false;
1709 
1710   // Non volatile memset/memcpy/memmoves are nosync
1711   // NOTE: Only intrinsics with volatile flags should be handled here.  All
1712   // others should be marked in Intrinsics.td.
1713   if (auto *MI = dyn_cast<MemIntrinsic>(&I))
1714     if (!MI->isVolatile())
1715       return false;
1716 
1717   // Speculatively assume in SCC.
1718   if (Function *Callee = CB->getCalledFunction())
1719     if (SCCNodes.contains(Callee))
1720       return false;
1721 
1722   return true;
1723 }
1724 
1725 // Infer the nosync attribute.
1726 static void addNoSyncAttr(const SCCNodeSet &SCCNodes,
1727                           SmallSet<Function *, 8> &Changed) {
1728   AttributeInferer AI;
1729   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1730       Attribute::NoSync,
1731       // Skip already marked functions.
1732       [](const Function &F) { return F.hasNoSync(); },
1733       // Instructions that break nosync assumption.
1734       [&SCCNodes](Instruction &I) {
1735         return InstrBreaksNoSync(I, SCCNodes);
1736       },
1737       [](Function &F) {
1738         LLVM_DEBUG(dbgs()
1739                    << "Adding nosync attr to fn " << F.getName() << "\n");
1740         F.setNoSync();
1741         ++NumNoSync;
1742       },
1743       /* RequiresExactDefinition= */ true});
1744   AI.run(SCCNodes, Changed);
1745 }
1746 
1747 static SCCNodesResult createSCCNodeSet(ArrayRef<Function *> Functions) {
1748   SCCNodesResult Res;
1749   Res.HasUnknownCall = false;
1750   for (Function *F : Functions) {
1751     if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked) ||
1752         F->isPresplitCoroutine()) {
1753       // Treat any function we're trying not to optimize as if it were an
1754       // indirect call and omit it from the node set used below.
1755       Res.HasUnknownCall = true;
1756       continue;
1757     }
1758     // Track whether any functions in this SCC have an unknown call edge.
1759     // Note: if this is ever a performance hit, we can common it with
1760     // subsequent routines which also do scans over the instructions of the
1761     // function.
1762     if (!Res.HasUnknownCall) {
1763       for (Instruction &I : instructions(*F)) {
1764         if (auto *CB = dyn_cast<CallBase>(&I)) {
1765           if (!CB->getCalledFunction()) {
1766             Res.HasUnknownCall = true;
1767             break;
1768           }
1769         }
1770       }
1771     }
1772     Res.SCCNodes.insert(F);
1773   }
1774   return Res;
1775 }
1776 
1777 template <typename AARGetterT>
1778 static SmallSet<Function *, 8>
1779 deriveAttrsInPostOrder(ArrayRef<Function *> Functions, AARGetterT &&AARGetter) {
1780   SCCNodesResult Nodes = createSCCNodeSet(Functions);
1781 
1782   // Bail if the SCC only contains optnone functions.
1783   if (Nodes.SCCNodes.empty())
1784     return {};
1785 
1786   SmallSet<Function *, 8> Changed;
1787 
1788   addArgumentReturnedAttrs(Nodes.SCCNodes, Changed);
1789   addReadAttrs(Nodes.SCCNodes, AARGetter, Changed);
1790   addArgumentAttrs(Nodes.SCCNodes, Changed);
1791   inferConvergent(Nodes.SCCNodes, Changed);
1792   addNoReturnAttrs(Nodes.SCCNodes, Changed);
1793   addWillReturn(Nodes.SCCNodes, Changed);
1794 
1795   // If we have no external nodes participating in the SCC, we can deduce some
1796   // more precise attributes as well.
1797   if (!Nodes.HasUnknownCall) {
1798     addNoAliasAttrs(Nodes.SCCNodes, Changed);
1799     addNonNullAttrs(Nodes.SCCNodes, Changed);
1800     inferAttrsFromFunctionBodies(Nodes.SCCNodes, Changed);
1801     addNoRecurseAttrs(Nodes.SCCNodes, Changed);
1802   }
1803 
1804   addNoSyncAttr(Nodes.SCCNodes, Changed);
1805 
1806   // Finally, infer the maximal set of attributes from the ones we've inferred
1807   // above.  This is handling the cases where one attribute on a signature
1808   // implies another, but for implementation reasons the inference rule for
1809   // the later is missing (or simply less sophisticated).
1810   for (Function *F : Nodes.SCCNodes)
1811     if (F)
1812       if (inferAttributesFromOthers(*F))
1813         Changed.insert(F);
1814 
1815   return Changed;
1816 }
1817 
1818 PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
1819                                                   CGSCCAnalysisManager &AM,
1820                                                   LazyCallGraph &CG,
1821                                                   CGSCCUpdateResult &) {
1822   FunctionAnalysisManager &FAM =
1823       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1824 
1825   // We pass a lambda into functions to wire them up to the analysis manager
1826   // for getting function analyses.
1827   auto AARGetter = [&](Function &F) -> AAResults & {
1828     return FAM.getResult<AAManager>(F);
1829   };
1830 
1831   SmallVector<Function *, 8> Functions;
1832   for (LazyCallGraph::Node &N : C) {
1833     Functions.push_back(&N.getFunction());
1834   }
1835 
1836   auto ChangedFunctions = deriveAttrsInPostOrder(Functions, AARGetter);
1837   if (ChangedFunctions.empty())
1838     return PreservedAnalyses::all();
1839 
1840   // Invalidate analyses for modified functions so that we don't have to
1841   // invalidate all analyses for all functions in this SCC.
1842   PreservedAnalyses FuncPA;
1843   // We haven't changed the CFG for modified functions.
1844   FuncPA.preserveSet<CFGAnalyses>();
1845   for (Function *Changed : ChangedFunctions) {
1846     FAM.invalidate(*Changed, FuncPA);
1847     // Also invalidate any direct callers of changed functions since analyses
1848     // may care about attributes of direct callees. For example, MemorySSA cares
1849     // about whether or not a call's callee modifies memory and queries that
1850     // through function attributes.
1851     for (auto *U : Changed->users()) {
1852       if (auto *Call = dyn_cast<CallBase>(U)) {
1853         if (Call->getCalledFunction() == Changed)
1854           FAM.invalidate(*Call->getFunction(), FuncPA);
1855       }
1856     }
1857   }
1858 
1859   PreservedAnalyses PA;
1860   // We have not added or removed functions.
1861   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1862   // We already invalidated all relevant function analyses above.
1863   PA.preserveSet<AllAnalysesOn<Function>>();
1864   return PA;
1865 }
1866 
1867 namespace {
1868 
1869 struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1870   // Pass identification, replacement for typeid
1871   static char ID;
1872 
1873   PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
1874     initializePostOrderFunctionAttrsLegacyPassPass(
1875         *PassRegistry::getPassRegistry());
1876   }
1877 
1878   bool runOnSCC(CallGraphSCC &SCC) override;
1879 
1880   void getAnalysisUsage(AnalysisUsage &AU) const override {
1881     AU.setPreservesCFG();
1882     AU.addRequired<AssumptionCacheTracker>();
1883     getAAResultsAnalysisUsage(AU);
1884     CallGraphSCCPass::getAnalysisUsage(AU);
1885   }
1886 };
1887 
1888 } // end anonymous namespace
1889 
1890 char PostOrderFunctionAttrsLegacyPass::ID = 0;
1891 INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1892                       "Deduce function attributes", false, false)
1893 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1894 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1895 INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1896                     "Deduce function attributes", false, false)
1897 
1898 Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1899   return new PostOrderFunctionAttrsLegacyPass();
1900 }
1901 
1902 template <typename AARGetterT>
1903 static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
1904   SmallVector<Function *, 8> Functions;
1905   for (CallGraphNode *I : SCC) {
1906     Functions.push_back(I->getFunction());
1907   }
1908 
1909   return !deriveAttrsInPostOrder(Functions, AARGetter).empty();
1910 }
1911 
1912 bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1913   if (skipSCC(SCC))
1914     return false;
1915   return runImpl(SCC, LegacyAARGetter(*this));
1916 }
1917 
1918 namespace {
1919 
1920 struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
1921   // Pass identification, replacement for typeid
1922   static char ID;
1923 
1924   ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
1925     initializeReversePostOrderFunctionAttrsLegacyPassPass(
1926         *PassRegistry::getPassRegistry());
1927   }
1928 
1929   bool runOnModule(Module &M) override;
1930 
1931   void getAnalysisUsage(AnalysisUsage &AU) const override {
1932     AU.setPreservesCFG();
1933     AU.addRequired<CallGraphWrapperPass>();
1934     AU.addPreserved<CallGraphWrapperPass>();
1935   }
1936 };
1937 
1938 } // end anonymous namespace
1939 
1940 char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1941 
1942 INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass,
1943                       "rpo-function-attrs", "Deduce function attributes in RPO",
1944                       false, false)
1945 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1946 INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass,
1947                     "rpo-function-attrs", "Deduce function attributes in RPO",
1948                     false, false)
1949 
1950 Pass *llvm::createReversePostOrderFunctionAttrsPass() {
1951   return new ReversePostOrderFunctionAttrsLegacyPass();
1952 }
1953 
1954 static bool addNoRecurseAttrsTopDown(Function &F) {
1955   // We check the preconditions for the function prior to calling this to avoid
1956   // the cost of building up a reversible post-order list. We assert them here
1957   // to make sure none of the invariants this relies on were violated.
1958   assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1959   assert(!F.doesNotRecurse() &&
1960          "This function has already been deduced as norecurs!");
1961   assert(F.hasInternalLinkage() &&
1962          "Can only do top-down deduction for internal linkage functions!");
1963 
1964   // If F is internal and all of its uses are calls from a non-recursive
1965   // functions, then none of its calls could in fact recurse without going
1966   // through a function marked norecurse, and so we can mark this function too
1967   // as norecurse. Note that the uses must actually be calls -- otherwise
1968   // a pointer to this function could be returned from a norecurse function but
1969   // this function could be recursively (indirectly) called. Note that this
1970   // also detects if F is directly recursive as F is not yet marked as
1971   // a norecurse function.
1972   for (auto *U : F.users()) {
1973     auto *I = dyn_cast<Instruction>(U);
1974     if (!I)
1975       return false;
1976     CallBase *CB = dyn_cast<CallBase>(I);
1977     if (!CB || !CB->getParent()->getParent()->doesNotRecurse())
1978       return false;
1979   }
1980   F.setDoesNotRecurse();
1981   ++NumNoRecurse;
1982   return true;
1983 }
1984 
1985 static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
1986   // We only have a post-order SCC traversal (because SCCs are inherently
1987   // discovered in post-order), so we accumulate them in a vector and then walk
1988   // it in reverse. This is simpler than using the RPO iterator infrastructure
1989   // because we need to combine SCC detection and the PO walk of the call
1990   // graph. We can also cheat egregiously because we're primarily interested in
1991   // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1992   // with multiple functions in them will clearly be recursive.
1993   SmallVector<Function *, 16> Worklist;
1994   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1995     if (I->size() != 1)
1996       continue;
1997 
1998     Function *F = I->front()->getFunction();
1999     if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
2000         F->hasInternalLinkage())
2001       Worklist.push_back(F);
2002   }
2003 
2004   bool Changed = false;
2005   for (auto *F : llvm::reverse(Worklist))
2006     Changed |= addNoRecurseAttrsTopDown(*F);
2007 
2008   return Changed;
2009 }
2010 
2011 bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
2012   if (skipModule(M))
2013     return false;
2014 
2015   auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
2016 
2017   return deduceFunctionAttributeInRPO(M, CG);
2018 }
2019 
2020 PreservedAnalyses
2021 ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
2022   auto &CG = AM.getResult<CallGraphAnalysis>(M);
2023 
2024   if (!deduceFunctionAttributeInRPO(M, CG))
2025     return PreservedAnalyses::all();
2026 
2027   PreservedAnalyses PA;
2028   PA.preserve<CallGraphAnalysis>();
2029   return PA;
2030 }
2031