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