xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/Attributor.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===- Attributor.cpp - Module-wide attribute deduction -------------------===//
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 // This file implements an interprocedural pass that deduces and/or propagates
10 // attributes. This is done in an abstract interpretation style fixpoint
11 // iteration. See the Attributor.h file comment and the class descriptions in
12 // that file for more information.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/IPO/Attributor.h"
17 
18 #include "llvm/ADT/GraphTraits.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/TinyPtrVector.h"
23 #include "llvm/Analysis/InlineCost.h"
24 #include "llvm/Analysis/LazyValueInfo.h"
25 #include "llvm/Analysis/MemorySSAUpdater.h"
26 #include "llvm/Analysis/MustExecute.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/NoFolder.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/IR/Verifier.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/DebugCounter.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/GraphWriter.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 
52 #include <cassert>
53 #include <string>
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "attributor"
58 
59 DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest",
60               "Determine what attributes are manifested in the IR");
61 
62 STATISTIC(NumFnDeleted, "Number of function deleted");
63 STATISTIC(NumFnWithExactDefinition,
64           "Number of functions with exact definitions");
65 STATISTIC(NumFnWithoutExactDefinition,
66           "Number of functions without exact definitions");
67 STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created");
68 STATISTIC(NumAttributesTimedOut,
69           "Number of abstract attributes timed out before fixpoint");
70 STATISTIC(NumAttributesValidFixpoint,
71           "Number of abstract attributes in a valid fixpoint state");
72 STATISTIC(NumAttributesManifested,
73           "Number of abstract attributes manifested in IR");
74 
75 // TODO: Determine a good default value.
76 //
77 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
78 // (when run with the first 5 abstract attributes). The results also indicate
79 // that we never reach 32 iterations but always find a fixpoint sooner.
80 //
81 // This will become more evolved once we perform two interleaved fixpoint
82 // iterations: bottom-up and top-down.
83 static cl::opt<unsigned>
84     SetFixpointIterations("attributor-max-iterations", cl::Hidden,
85                           cl::desc("Maximal number of fixpoint iterations."),
86                           cl::init(32));
87 
88 static cl::opt<unsigned, true> MaxInitializationChainLengthX(
89     "attributor-max-initialization-chain-length", cl::Hidden,
90     cl::desc(
91         "Maximal number of chained initializations (to avoid stack overflows)"),
92     cl::location(MaxInitializationChainLength), cl::init(1024));
93 unsigned llvm::MaxInitializationChainLength;
94 
95 static cl::opt<bool> VerifyMaxFixpointIterations(
96     "attributor-max-iterations-verify", cl::Hidden,
97     cl::desc("Verify that max-iterations is a tight bound for a fixpoint"),
98     cl::init(false));
99 
100 static cl::opt<bool> AnnotateDeclarationCallSites(
101     "attributor-annotate-decl-cs", cl::Hidden,
102     cl::desc("Annotate call sites of function declarations."), cl::init(false));
103 
104 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
105                                        cl::init(true), cl::Hidden);
106 
107 static cl::opt<bool>
108     AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
109                          cl::desc("Allow the Attributor to create shallow "
110                                   "wrappers for non-exact definitions."),
111                          cl::init(false));
112 
113 static cl::opt<bool>
114     AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden,
115                      cl::desc("Allow the Attributor to use IP information "
116                               "derived from non-exact functions via cloning"),
117                      cl::init(false));
118 
119 // These options can only used for debug builds.
120 #ifndef NDEBUG
121 static cl::list<std::string>
122     SeedAllowList("attributor-seed-allow-list", cl::Hidden,
123                   cl::desc("Comma seperated list of attribute names that are "
124                            "allowed to be seeded."),
125                   cl::ZeroOrMore, cl::CommaSeparated);
126 
127 static cl::list<std::string> FunctionSeedAllowList(
128     "attributor-function-seed-allow-list", cl::Hidden,
129     cl::desc("Comma seperated list of function names that are "
130              "allowed to be seeded."),
131     cl::ZeroOrMore, cl::CommaSeparated);
132 #endif
133 
134 static cl::opt<bool>
135     DumpDepGraph("attributor-dump-dep-graph", cl::Hidden,
136                  cl::desc("Dump the dependency graph to dot files."),
137                  cl::init(false));
138 
139 static cl::opt<std::string> DepGraphDotFileNamePrefix(
140     "attributor-depgraph-dot-filename-prefix", cl::Hidden,
141     cl::desc("The prefix used for the CallGraph dot file names."));
142 
143 static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden,
144                                   cl::desc("View the dependency graph."),
145                                   cl::init(false));
146 
147 static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden,
148                                        cl::desc("Print attribute dependencies"),
149                                        cl::init(false));
150 
151 static cl::opt<bool> EnableCallSiteSpecific(
152     "attributor-enable-call-site-specific-deduction", cl::Hidden,
153     cl::desc("Allow the Attributor to do call site specific analysis"),
154     cl::init(false));
155 
156 static cl::opt<bool>
157     PrintCallGraph("attributor-print-call-graph", cl::Hidden,
158                    cl::desc("Print Attributor's internal call graph"),
159                    cl::init(false));
160 
161 static cl::opt<bool> SimplifyAllLoads("attributor-simplify-all-loads",
162                                       cl::Hidden,
163                                       cl::desc("Try to simplify all loads."),
164                                       cl::init(true));
165 
166 /// Logic operators for the change status enum class.
167 ///
168 ///{
169 ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) {
170   return L == ChangeStatus::CHANGED ? L : R;
171 }
172 ChangeStatus &llvm::operator|=(ChangeStatus &L, ChangeStatus R) {
173   L = L | R;
174   return L;
175 }
176 ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) {
177   return L == ChangeStatus::UNCHANGED ? L : R;
178 }
179 ChangeStatus &llvm::operator&=(ChangeStatus &L, ChangeStatus R) {
180   L = L & R;
181   return L;
182 }
183 ///}
184 
185 bool AA::isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA,
186                              const Value &V) {
187   if (auto *C = dyn_cast<Constant>(&V))
188     return !C->isThreadDependent();
189   // TODO: Inspect and cache more complex instructions.
190   if (auto *CB = dyn_cast<CallBase>(&V))
191     return CB->getNumOperands() == 0 && !CB->mayHaveSideEffects() &&
192            !CB->mayReadFromMemory();
193   const Function *Scope = nullptr;
194   if (auto *I = dyn_cast<Instruction>(&V))
195     Scope = I->getFunction();
196   if (auto *A = dyn_cast<Argument>(&V))
197     Scope = A->getParent();
198   if (!Scope)
199     return false;
200   auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
201       QueryingAA, IRPosition::function(*Scope), DepClassTy::OPTIONAL);
202   return NoRecurseAA.isAssumedNoRecurse();
203 }
204 
205 Constant *AA::getInitialValueForObj(Value &Obj, Type &Ty) {
206   if (isa<AllocaInst>(Obj))
207     return UndefValue::get(&Ty);
208   auto *GV = dyn_cast<GlobalVariable>(&Obj);
209   if (!GV || !GV->hasLocalLinkage())
210     return nullptr;
211   if (!GV->hasInitializer())
212     return UndefValue::get(&Ty);
213   return dyn_cast_or_null<Constant>(getWithType(*GV->getInitializer(), Ty));
214 }
215 
216 bool AA::isValidInScope(const Value &V, const Function *Scope) {
217   if (isa<Constant>(V))
218     return true;
219   if (auto *I = dyn_cast<Instruction>(&V))
220     return I->getFunction() == Scope;
221   if (auto *A = dyn_cast<Argument>(&V))
222     return A->getParent() == Scope;
223   return false;
224 }
225 
226 bool AA::isValidAtPosition(const Value &V, const Instruction &CtxI,
227                            InformationCache &InfoCache) {
228   if (isa<Constant>(V))
229     return true;
230   const Function *Scope = CtxI.getFunction();
231   if (auto *A = dyn_cast<Argument>(&V))
232     return A->getParent() == Scope;
233   if (auto *I = dyn_cast<Instruction>(&V))
234     if (I->getFunction() == Scope) {
235       const DominatorTree *DT =
236           InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Scope);
237       return DT && DT->dominates(I, &CtxI);
238     }
239   return false;
240 }
241 
242 Value *AA::getWithType(Value &V, Type &Ty) {
243   if (V.getType() == &Ty)
244     return &V;
245   if (isa<PoisonValue>(V))
246     return PoisonValue::get(&Ty);
247   if (isa<UndefValue>(V))
248     return UndefValue::get(&Ty);
249   if (auto *C = dyn_cast<Constant>(&V)) {
250     if (C->isNullValue())
251       return Constant::getNullValue(&Ty);
252     if (C->getType()->isPointerTy() && Ty.isPointerTy())
253       return ConstantExpr::getPointerCast(C, &Ty);
254     if (C->getType()->getPrimitiveSizeInBits() >= Ty.getPrimitiveSizeInBits()) {
255       if (C->getType()->isIntegerTy() && Ty.isIntegerTy())
256         return ConstantExpr::getTrunc(C, &Ty, /* OnlyIfReduced */ true);
257       if (C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy())
258         return ConstantExpr::getFPTrunc(C, &Ty, /* OnlyIfReduced */ true);
259     }
260   }
261   return nullptr;
262 }
263 
264 Optional<Value *>
265 AA::combineOptionalValuesInAAValueLatice(const Optional<Value *> &A,
266                                          const Optional<Value *> &B, Type *Ty) {
267   if (A == B)
268     return A;
269   if (!B.hasValue())
270     return A;
271   if (*B == nullptr)
272     return nullptr;
273   if (!A.hasValue())
274     return Ty ? getWithType(**B, *Ty) : nullptr;
275   if (*A == nullptr)
276     return nullptr;
277   if (!Ty)
278     Ty = (*A)->getType();
279   if (isa_and_nonnull<UndefValue>(*A))
280     return getWithType(**B, *Ty);
281   if (isa<UndefValue>(*B))
282     return A;
283   if (*A && *B && *A == getWithType(**B, *Ty))
284     return A;
285   return nullptr;
286 }
287 
288 bool AA::getPotentialCopiesOfStoredValue(
289     Attributor &A, StoreInst &SI, SmallSetVector<Value *, 4> &PotentialCopies,
290     const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation) {
291 
292   Value &Ptr = *SI.getPointerOperand();
293   SmallVector<Value *, 8> Objects;
294   if (!AA::getAssumedUnderlyingObjects(A, Ptr, Objects, QueryingAA, &SI)) {
295     LLVM_DEBUG(
296         dbgs() << "Underlying objects stored into could not be determined\n";);
297     return false;
298   }
299 
300   SmallVector<const AAPointerInfo *> PIs;
301   SmallVector<Value *> NewCopies;
302 
303   for (Value *Obj : Objects) {
304     LLVM_DEBUG(dbgs() << "Visit underlying object " << *Obj << "\n");
305     if (isa<UndefValue>(Obj))
306       continue;
307     if (isa<ConstantPointerNull>(Obj)) {
308       // A null pointer access can be undefined but any offset from null may
309       // be OK. We do not try to optimize the latter.
310       if (!NullPointerIsDefined(SI.getFunction(),
311                                 Ptr.getType()->getPointerAddressSpace()) &&
312           A.getAssumedSimplified(Ptr, QueryingAA, UsedAssumedInformation) ==
313               Obj)
314         continue;
315       LLVM_DEBUG(
316           dbgs() << "Underlying object is a valid nullptr, giving up.\n";);
317       return false;
318     }
319     if (!isa<AllocaInst>(Obj) && !isa<GlobalVariable>(Obj)) {
320       LLVM_DEBUG(dbgs() << "Underlying object is not supported yet: " << *Obj
321                         << "\n";);
322       return false;
323     }
324     if (auto *GV = dyn_cast<GlobalVariable>(Obj))
325       if (!GV->hasLocalLinkage()) {
326         LLVM_DEBUG(dbgs() << "Underlying object is global with external "
327                              "linkage, not supported yet: "
328                           << *Obj << "\n";);
329         return false;
330       }
331 
332     auto CheckAccess = [&](const AAPointerInfo::Access &Acc, bool IsExact) {
333       if (!Acc.isRead())
334         return true;
335       auto *LI = dyn_cast<LoadInst>(Acc.getRemoteInst());
336       if (!LI) {
337         LLVM_DEBUG(dbgs() << "Underlying object read through a non-load "
338                              "instruction not supported yet: "
339                           << *Acc.getRemoteInst() << "\n";);
340         return false;
341       }
342       NewCopies.push_back(LI);
343       return true;
344     };
345 
346     auto &PI = A.getAAFor<AAPointerInfo>(QueryingAA, IRPosition::value(*Obj),
347                                          DepClassTy::NONE);
348     if (!PI.forallInterferingAccesses(SI, CheckAccess)) {
349       LLVM_DEBUG(
350           dbgs()
351           << "Failed to verify all interfering accesses for underlying object: "
352           << *Obj << "\n");
353       return false;
354     }
355     PIs.push_back(&PI);
356   }
357 
358   for (auto *PI : PIs) {
359     if (!PI->getState().isAtFixpoint())
360       UsedAssumedInformation = true;
361     A.recordDependence(*PI, QueryingAA, DepClassTy::OPTIONAL);
362   }
363   PotentialCopies.insert(NewCopies.begin(), NewCopies.end());
364 
365   return true;
366 }
367 
368 /// Return true if \p New is equal or worse than \p Old.
369 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
370   if (!Old.isIntAttribute())
371     return true;
372 
373   return Old.getValueAsInt() >= New.getValueAsInt();
374 }
375 
376 /// Return true if the information provided by \p Attr was added to the
377 /// attribute list \p Attrs. This is only the case if it was not already present
378 /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
379 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
380                              AttributeList &Attrs, int AttrIdx,
381                              bool ForceReplace = false) {
382 
383   if (Attr.isEnumAttribute()) {
384     Attribute::AttrKind Kind = Attr.getKindAsEnum();
385     if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
386       if (!ForceReplace &&
387           isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
388         return false;
389     Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
390     return true;
391   }
392   if (Attr.isStringAttribute()) {
393     StringRef Kind = Attr.getKindAsString();
394     if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
395       if (!ForceReplace &&
396           isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
397         return false;
398     Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
399     return true;
400   }
401   if (Attr.isIntAttribute()) {
402     Attribute::AttrKind Kind = Attr.getKindAsEnum();
403     if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
404       if (!ForceReplace &&
405           isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
406         return false;
407     Attrs = Attrs.removeAttributeAtIndex(Ctx, AttrIdx, Kind);
408     Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
409     return true;
410   }
411 
412   llvm_unreachable("Expected enum or string attribute!");
413 }
414 
415 Argument *IRPosition::getAssociatedArgument() const {
416   if (getPositionKind() == IRP_ARGUMENT)
417     return cast<Argument>(&getAnchorValue());
418 
419   // Not an Argument and no argument number means this is not a call site
420   // argument, thus we cannot find a callback argument to return.
421   int ArgNo = getCallSiteArgNo();
422   if (ArgNo < 0)
423     return nullptr;
424 
425   // Use abstract call sites to make the connection between the call site
426   // values and the ones in callbacks. If a callback was found that makes use
427   // of the underlying call site operand, we want the corresponding callback
428   // callee argument and not the direct callee argument.
429   Optional<Argument *> CBCandidateArg;
430   SmallVector<const Use *, 4> CallbackUses;
431   const auto &CB = cast<CallBase>(getAnchorValue());
432   AbstractCallSite::getCallbackUses(CB, CallbackUses);
433   for (const Use *U : CallbackUses) {
434     AbstractCallSite ACS(U);
435     assert(ACS && ACS.isCallbackCall());
436     if (!ACS.getCalledFunction())
437       continue;
438 
439     for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
440 
441       // Test if the underlying call site operand is argument number u of the
442       // callback callee.
443       if (ACS.getCallArgOperandNo(u) != ArgNo)
444         continue;
445 
446       assert(ACS.getCalledFunction()->arg_size() > u &&
447              "ACS mapped into var-args arguments!");
448       if (CBCandidateArg.hasValue()) {
449         CBCandidateArg = nullptr;
450         break;
451       }
452       CBCandidateArg = ACS.getCalledFunction()->getArg(u);
453     }
454   }
455 
456   // If we found a unique callback candidate argument, return it.
457   if (CBCandidateArg.hasValue() && CBCandidateArg.getValue())
458     return CBCandidateArg.getValue();
459 
460   // If no callbacks were found, or none used the underlying call site operand
461   // exclusively, use the direct callee argument if available.
462   const Function *Callee = CB.getCalledFunction();
463   if (Callee && Callee->arg_size() > unsigned(ArgNo))
464     return Callee->getArg(ArgNo);
465 
466   return nullptr;
467 }
468 
469 ChangeStatus AbstractAttribute::update(Attributor &A) {
470   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
471   if (getState().isAtFixpoint())
472     return HasChanged;
473 
474   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
475 
476   HasChanged = updateImpl(A);
477 
478   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
479                     << "\n");
480 
481   return HasChanged;
482 }
483 
484 ChangeStatus
485 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP,
486                                    const ArrayRef<Attribute> &DeducedAttrs,
487                                    bool ForceReplace) {
488   Function *ScopeFn = IRP.getAnchorScope();
489   IRPosition::Kind PK = IRP.getPositionKind();
490 
491   // In the following some generic code that will manifest attributes in
492   // DeducedAttrs if they improve the current IR. Due to the different
493   // annotation positions we use the underlying AttributeList interface.
494 
495   AttributeList Attrs;
496   switch (PK) {
497   case IRPosition::IRP_INVALID:
498   case IRPosition::IRP_FLOAT:
499     return ChangeStatus::UNCHANGED;
500   case IRPosition::IRP_ARGUMENT:
501   case IRPosition::IRP_FUNCTION:
502   case IRPosition::IRP_RETURNED:
503     Attrs = ScopeFn->getAttributes();
504     break;
505   case IRPosition::IRP_CALL_SITE:
506   case IRPosition::IRP_CALL_SITE_RETURNED:
507   case IRPosition::IRP_CALL_SITE_ARGUMENT:
508     Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes();
509     break;
510   }
511 
512   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
513   LLVMContext &Ctx = IRP.getAnchorValue().getContext();
514   for (const Attribute &Attr : DeducedAttrs) {
515     if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx(), ForceReplace))
516       continue;
517 
518     HasChanged = ChangeStatus::CHANGED;
519   }
520 
521   if (HasChanged == ChangeStatus::UNCHANGED)
522     return HasChanged;
523 
524   switch (PK) {
525   case IRPosition::IRP_ARGUMENT:
526   case IRPosition::IRP_FUNCTION:
527   case IRPosition::IRP_RETURNED:
528     ScopeFn->setAttributes(Attrs);
529     break;
530   case IRPosition::IRP_CALL_SITE:
531   case IRPosition::IRP_CALL_SITE_RETURNED:
532   case IRPosition::IRP_CALL_SITE_ARGUMENT:
533     cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs);
534     break;
535   case IRPosition::IRP_INVALID:
536   case IRPosition::IRP_FLOAT:
537     break;
538   }
539 
540   return HasChanged;
541 }
542 
543 const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey());
544 const IRPosition
545     IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey());
546 
547 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
548   IRPositions.emplace_back(IRP);
549 
550   // Helper to determine if operand bundles on a call site are benin or
551   // potentially problematic. We handle only llvm.assume for now.
552   auto CanIgnoreOperandBundles = [](const CallBase &CB) {
553     return (isa<IntrinsicInst>(CB) &&
554             cast<IntrinsicInst>(CB).getIntrinsicID() == Intrinsic ::assume);
555   };
556 
557   const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue());
558   switch (IRP.getPositionKind()) {
559   case IRPosition::IRP_INVALID:
560   case IRPosition::IRP_FLOAT:
561   case IRPosition::IRP_FUNCTION:
562     return;
563   case IRPosition::IRP_ARGUMENT:
564   case IRPosition::IRP_RETURNED:
565     IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope()));
566     return;
567   case IRPosition::IRP_CALL_SITE:
568     assert(CB && "Expected call site!");
569     // TODO: We need to look at the operand bundles similar to the redirection
570     //       in CallBase.
571     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
572       if (const Function *Callee = CB->getCalledFunction())
573         IRPositions.emplace_back(IRPosition::function(*Callee));
574     return;
575   case IRPosition::IRP_CALL_SITE_RETURNED:
576     assert(CB && "Expected call site!");
577     // TODO: We need to look at the operand bundles similar to the redirection
578     //       in CallBase.
579     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
580       if (const Function *Callee = CB->getCalledFunction()) {
581         IRPositions.emplace_back(IRPosition::returned(*Callee));
582         IRPositions.emplace_back(IRPosition::function(*Callee));
583         for (const Argument &Arg : Callee->args())
584           if (Arg.hasReturnedAttr()) {
585             IRPositions.emplace_back(
586                 IRPosition::callsite_argument(*CB, Arg.getArgNo()));
587             IRPositions.emplace_back(
588                 IRPosition::value(*CB->getArgOperand(Arg.getArgNo())));
589             IRPositions.emplace_back(IRPosition::argument(Arg));
590           }
591       }
592     }
593     IRPositions.emplace_back(IRPosition::callsite_function(*CB));
594     return;
595   case IRPosition::IRP_CALL_SITE_ARGUMENT: {
596     assert(CB && "Expected call site!");
597     // TODO: We need to look at the operand bundles similar to the redirection
598     //       in CallBase.
599     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
600       const Function *Callee = CB->getCalledFunction();
601       if (Callee) {
602         if (Argument *Arg = IRP.getAssociatedArgument())
603           IRPositions.emplace_back(IRPosition::argument(*Arg));
604         IRPositions.emplace_back(IRPosition::function(*Callee));
605       }
606     }
607     IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
608     return;
609   }
610   }
611 }
612 
613 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs,
614                          bool IgnoreSubsumingPositions, Attributor *A) const {
615   SmallVector<Attribute, 4> Attrs;
616   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
617     for (Attribute::AttrKind AK : AKs)
618       if (EquivIRP.getAttrsFromIRAttr(AK, Attrs))
619         return true;
620     // The first position returned by the SubsumingPositionIterator is
621     // always the position itself. If we ignore subsuming positions we
622     // are done after the first iteration.
623     if (IgnoreSubsumingPositions)
624       break;
625   }
626   if (A)
627     for (Attribute::AttrKind AK : AKs)
628       if (getAttrsFromAssumes(AK, Attrs, *A))
629         return true;
630   return false;
631 }
632 
633 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
634                           SmallVectorImpl<Attribute> &Attrs,
635                           bool IgnoreSubsumingPositions, Attributor *A) const {
636   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
637     for (Attribute::AttrKind AK : AKs)
638       EquivIRP.getAttrsFromIRAttr(AK, Attrs);
639     // The first position returned by the SubsumingPositionIterator is
640     // always the position itself. If we ignore subsuming positions we
641     // are done after the first iteration.
642     if (IgnoreSubsumingPositions)
643       break;
644   }
645   if (A)
646     for (Attribute::AttrKind AK : AKs)
647       getAttrsFromAssumes(AK, Attrs, *A);
648 }
649 
650 bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK,
651                                     SmallVectorImpl<Attribute> &Attrs) const {
652   if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT)
653     return false;
654 
655   AttributeList AttrList;
656   if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
657     AttrList = CB->getAttributes();
658   else
659     AttrList = getAssociatedFunction()->getAttributes();
660 
661   bool HasAttr = AttrList.hasAttributeAtIndex(getAttrIdx(), AK);
662   if (HasAttr)
663     Attrs.push_back(AttrList.getAttributeAtIndex(getAttrIdx(), AK));
664   return HasAttr;
665 }
666 
667 bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK,
668                                      SmallVectorImpl<Attribute> &Attrs,
669                                      Attributor &A) const {
670   assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!");
671   Value &AssociatedValue = getAssociatedValue();
672 
673   const Assume2KnowledgeMap &A2K =
674       A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK});
675 
676   // Check if we found any potential assume use, if not we don't need to create
677   // explorer iterators.
678   if (A2K.empty())
679     return false;
680 
681   LLVMContext &Ctx = AssociatedValue.getContext();
682   unsigned AttrsSize = Attrs.size();
683   MustBeExecutedContextExplorer &Explorer =
684       A.getInfoCache().getMustBeExecutedContextExplorer();
685   auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI());
686   for (auto &It : A2K)
687     if (Explorer.findInContextOf(It.first, EIt, EEnd))
688       Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max));
689   return AttrsSize != Attrs.size();
690 }
691 
692 void IRPosition::verify() {
693 #ifdef EXPENSIVE_CHECKS
694   switch (getPositionKind()) {
695   case IRP_INVALID:
696     assert((CBContext == nullptr) &&
697            "Invalid position must not have CallBaseContext!");
698     assert(!Enc.getOpaqueValue() &&
699            "Expected a nullptr for an invalid position!");
700     return;
701   case IRP_FLOAT:
702     assert((!isa<CallBase>(&getAssociatedValue()) &&
703             !isa<Argument>(&getAssociatedValue())) &&
704            "Expected specialized kind for call base and argument values!");
705     return;
706   case IRP_RETURNED:
707     assert(isa<Function>(getAsValuePtr()) &&
708            "Expected function for a 'returned' position!");
709     assert(getAsValuePtr() == &getAssociatedValue() &&
710            "Associated value mismatch!");
711     return;
712   case IRP_CALL_SITE_RETURNED:
713     assert((CBContext == nullptr) &&
714            "'call site returned' position must not have CallBaseContext!");
715     assert((isa<CallBase>(getAsValuePtr())) &&
716            "Expected call base for 'call site returned' position!");
717     assert(getAsValuePtr() == &getAssociatedValue() &&
718            "Associated value mismatch!");
719     return;
720   case IRP_CALL_SITE:
721     assert((CBContext == nullptr) &&
722            "'call site function' position must not have CallBaseContext!");
723     assert((isa<CallBase>(getAsValuePtr())) &&
724            "Expected call base for 'call site function' position!");
725     assert(getAsValuePtr() == &getAssociatedValue() &&
726            "Associated value mismatch!");
727     return;
728   case IRP_FUNCTION:
729     assert(isa<Function>(getAsValuePtr()) &&
730            "Expected function for a 'function' position!");
731     assert(getAsValuePtr() == &getAssociatedValue() &&
732            "Associated value mismatch!");
733     return;
734   case IRP_ARGUMENT:
735     assert(isa<Argument>(getAsValuePtr()) &&
736            "Expected argument for a 'argument' position!");
737     assert(getAsValuePtr() == &getAssociatedValue() &&
738            "Associated value mismatch!");
739     return;
740   case IRP_CALL_SITE_ARGUMENT: {
741     assert((CBContext == nullptr) &&
742            "'call site argument' position must not have CallBaseContext!");
743     Use *U = getAsUsePtr();
744     assert(U && "Expected use for a 'call site argument' position!");
745     assert(isa<CallBase>(U->getUser()) &&
746            "Expected call base user for a 'call site argument' position!");
747     assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
748            "Expected call base argument operand for a 'call site argument' "
749            "position");
750     assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
751                unsigned(getCallSiteArgNo()) &&
752            "Argument number mismatch!");
753     assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
754     return;
755   }
756   }
757 #endif
758 }
759 
760 Optional<Constant *>
761 Attributor::getAssumedConstant(const IRPosition &IRP,
762                                const AbstractAttribute &AA,
763                                bool &UsedAssumedInformation) {
764   // First check all callbacks provided by outside AAs. If any of them returns
765   // a non-null value that is different from the associated value, or None, we
766   // assume it's simpliied.
767   for (auto &CB : SimplificationCallbacks.lookup(IRP)) {
768     Optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
769     if (!SimplifiedV.hasValue())
770       return llvm::None;
771     if (isa_and_nonnull<Constant>(*SimplifiedV))
772       return cast<Constant>(*SimplifiedV);
773     return nullptr;
774   }
775   const auto &ValueSimplifyAA =
776       getAAFor<AAValueSimplify>(AA, IRP, DepClassTy::NONE);
777   Optional<Value *> SimplifiedV =
778       ValueSimplifyAA.getAssumedSimplifiedValue(*this);
779   bool IsKnown = ValueSimplifyAA.isAtFixpoint();
780   UsedAssumedInformation |= !IsKnown;
781   if (!SimplifiedV.hasValue()) {
782     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
783     return llvm::None;
784   }
785   if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) {
786     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
787     return UndefValue::get(IRP.getAssociatedType());
788   }
789   Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue());
790   if (CI)
791     CI = dyn_cast_or_null<Constant>(
792         AA::getWithType(*CI, *IRP.getAssociatedType()));
793   if (CI)
794     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
795   return CI;
796 }
797 
798 Optional<Value *>
799 Attributor::getAssumedSimplified(const IRPosition &IRP,
800                                  const AbstractAttribute *AA,
801                                  bool &UsedAssumedInformation) {
802   // First check all callbacks provided by outside AAs. If any of them returns
803   // a non-null value that is different from the associated value, or None, we
804   // assume it's simpliied.
805   for (auto &CB : SimplificationCallbacks.lookup(IRP))
806     return CB(IRP, AA, UsedAssumedInformation);
807 
808   // If no high-level/outside simplification occured, use AAValueSimplify.
809   const auto &ValueSimplifyAA =
810       getOrCreateAAFor<AAValueSimplify>(IRP, AA, DepClassTy::NONE);
811   Optional<Value *> SimplifiedV =
812       ValueSimplifyAA.getAssumedSimplifiedValue(*this);
813   bool IsKnown = ValueSimplifyAA.isAtFixpoint();
814   UsedAssumedInformation |= !IsKnown;
815   if (!SimplifiedV.hasValue()) {
816     if (AA)
817       recordDependence(ValueSimplifyAA, *AA, DepClassTy::OPTIONAL);
818     return llvm::None;
819   }
820   if (*SimplifiedV == nullptr)
821     return const_cast<Value *>(&IRP.getAssociatedValue());
822   if (Value *SimpleV =
823           AA::getWithType(**SimplifiedV, *IRP.getAssociatedType())) {
824     if (AA)
825       recordDependence(ValueSimplifyAA, *AA, DepClassTy::OPTIONAL);
826     return SimpleV;
827   }
828   return const_cast<Value *>(&IRP.getAssociatedValue());
829 }
830 
831 Optional<Value *> Attributor::translateArgumentToCallSiteContent(
832     Optional<Value *> V, CallBase &CB, const AbstractAttribute &AA,
833     bool &UsedAssumedInformation) {
834   if (!V.hasValue())
835     return V;
836   if (*V == nullptr || isa<Constant>(*V))
837     return V;
838   if (auto *Arg = dyn_cast<Argument>(*V))
839     if (CB.getCalledFunction() == Arg->getParent())
840       if (!Arg->hasPointeeInMemoryValueAttr())
841         return getAssumedSimplified(
842             IRPosition::callsite_argument(CB, Arg->getArgNo()), AA,
843             UsedAssumedInformation);
844   return nullptr;
845 }
846 
847 Attributor::~Attributor() {
848   // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
849   // thus we cannot delete them. We can, and want to, destruct them though.
850   for (auto &DepAA : DG.SyntheticRoot.Deps) {
851     AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
852     AA->~AbstractAttribute();
853   }
854 }
855 
856 bool Attributor::isAssumedDead(const AbstractAttribute &AA,
857                                const AAIsDead *FnLivenessAA,
858                                bool &UsedAssumedInformation,
859                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
860   const IRPosition &IRP = AA.getIRPosition();
861   if (!Functions.count(IRP.getAnchorScope()))
862     return false;
863   return isAssumedDead(IRP, &AA, FnLivenessAA, UsedAssumedInformation,
864                        CheckBBLivenessOnly, DepClass);
865 }
866 
867 bool Attributor::isAssumedDead(const Use &U,
868                                const AbstractAttribute *QueryingAA,
869                                const AAIsDead *FnLivenessAA,
870                                bool &UsedAssumedInformation,
871                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
872   Instruction *UserI = dyn_cast<Instruction>(U.getUser());
873   if (!UserI)
874     return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA,
875                          UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
876 
877   if (auto *CB = dyn_cast<CallBase>(UserI)) {
878     // For call site argument uses we can check if the argument is
879     // unused/dead.
880     if (CB->isArgOperand(&U)) {
881       const IRPosition &CSArgPos =
882           IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
883       return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA,
884                            UsedAssumedInformation, CheckBBLivenessOnly,
885                            DepClass);
886     }
887   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
888     const IRPosition &RetPos = IRPosition::returned(*RI->getFunction());
889     return isAssumedDead(RetPos, QueryingAA, FnLivenessAA,
890                          UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
891   } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) {
892     BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
893     return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA,
894                          UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
895   }
896 
897   return isAssumedDead(IRPosition::value(*UserI), QueryingAA, FnLivenessAA,
898                        UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
899 }
900 
901 bool Attributor::isAssumedDead(const Instruction &I,
902                                const AbstractAttribute *QueryingAA,
903                                const AAIsDead *FnLivenessAA,
904                                bool &UsedAssumedInformation,
905                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
906   const IRPosition::CallBaseContext *CBCtx =
907       QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
908 
909   if (ManifestAddedBlocks.contains(I.getParent()))
910     return false;
911 
912   if (!FnLivenessAA)
913     FnLivenessAA =
914         lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction(), CBCtx),
915                               QueryingAA, DepClassTy::NONE);
916 
917   // If we have a context instruction and a liveness AA we use it.
918   if (FnLivenessAA &&
919       FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() &&
920       FnLivenessAA->isAssumedDead(&I)) {
921     if (QueryingAA)
922       recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
923     if (!FnLivenessAA->isKnownDead(&I))
924       UsedAssumedInformation = true;
925     return true;
926   }
927 
928   if (CheckBBLivenessOnly)
929     return false;
930 
931   const AAIsDead &IsDeadAA = getOrCreateAAFor<AAIsDead>(
932       IRPosition::value(I, CBCtx), QueryingAA, DepClassTy::NONE);
933   // Don't check liveness for AAIsDead.
934   if (QueryingAA == &IsDeadAA)
935     return false;
936 
937   if (IsDeadAA.isAssumedDead()) {
938     if (QueryingAA)
939       recordDependence(IsDeadAA, *QueryingAA, DepClass);
940     if (!IsDeadAA.isKnownDead())
941       UsedAssumedInformation = true;
942     return true;
943   }
944 
945   return false;
946 }
947 
948 bool Attributor::isAssumedDead(const IRPosition &IRP,
949                                const AbstractAttribute *QueryingAA,
950                                const AAIsDead *FnLivenessAA,
951                                bool &UsedAssumedInformation,
952                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
953   Instruction *CtxI = IRP.getCtxI();
954   if (CtxI &&
955       isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
956                     /* CheckBBLivenessOnly */ true,
957                     CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
958     return true;
959 
960   if (CheckBBLivenessOnly)
961     return false;
962 
963   // If we haven't succeeded we query the specific liveness info for the IRP.
964   const AAIsDead *IsDeadAA;
965   if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
966     IsDeadAA = &getOrCreateAAFor<AAIsDead>(
967         IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())),
968         QueryingAA, DepClassTy::NONE);
969   else
970     IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
971   // Don't check liveness for AAIsDead.
972   if (QueryingAA == IsDeadAA)
973     return false;
974 
975   if (IsDeadAA->isAssumedDead()) {
976     if (QueryingAA)
977       recordDependence(*IsDeadAA, *QueryingAA, DepClass);
978     if (!IsDeadAA->isKnownDead())
979       UsedAssumedInformation = true;
980     return true;
981   }
982 
983   return false;
984 }
985 
986 bool Attributor::isAssumedDead(const BasicBlock &BB,
987                                const AbstractAttribute *QueryingAA,
988                                const AAIsDead *FnLivenessAA,
989                                DepClassTy DepClass) {
990   if (!FnLivenessAA)
991     FnLivenessAA = lookupAAFor<AAIsDead>(IRPosition::function(*BB.getParent()),
992                                          QueryingAA, DepClassTy::NONE);
993   if (FnLivenessAA->isAssumedDead(&BB)) {
994     if (QueryingAA)
995       recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
996     return true;
997   }
998 
999   return false;
1000 }
1001 
1002 bool Attributor::checkForAllUses(function_ref<bool(const Use &, bool &)> Pred,
1003                                  const AbstractAttribute &QueryingAA,
1004                                  const Value &V, bool CheckBBLivenessOnly,
1005                                  DepClassTy LivenessDepClass) {
1006 
1007   // Check the trivial case first as it catches void values.
1008   if (V.use_empty())
1009     return true;
1010 
1011   const IRPosition &IRP = QueryingAA.getIRPosition();
1012   SmallVector<const Use *, 16> Worklist;
1013   SmallPtrSet<const Use *, 16> Visited;
1014 
1015   for (const Use &U : V.uses())
1016     Worklist.push_back(&U);
1017 
1018   LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
1019                     << " initial uses to check\n");
1020 
1021   const Function *ScopeFn = IRP.getAnchorScope();
1022   const auto *LivenessAA =
1023       ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn),
1024                                     DepClassTy::NONE)
1025               : nullptr;
1026 
1027   while (!Worklist.empty()) {
1028     const Use *U = Worklist.pop_back_val();
1029     if (isa<PHINode>(U->getUser()) && !Visited.insert(U).second)
1030       continue;
1031     LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << " in "
1032                       << *U->getUser() << "\n");
1033     bool UsedAssumedInformation = false;
1034     if (isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation,
1035                       CheckBBLivenessOnly, LivenessDepClass)) {
1036       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
1037       continue;
1038     }
1039     if (U->getUser()->isDroppable()) {
1040       LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n");
1041       continue;
1042     }
1043 
1044     if (auto *SI = dyn_cast<StoreInst>(U->getUser())) {
1045       if (&SI->getOperandUse(0) == U) {
1046         if (!Visited.insert(U).second)
1047           continue;
1048         SmallSetVector<Value *, 4> PotentialCopies;
1049         if (AA::getPotentialCopiesOfStoredValue(*this, *SI, PotentialCopies,
1050                                                 QueryingAA,
1051                                                 UsedAssumedInformation)) {
1052           LLVM_DEBUG(dbgs() << "[Attributor] Value is stored, continue with "
1053                             << PotentialCopies.size()
1054                             << " potential copies instead!\n");
1055           for (Value *PotentialCopy : PotentialCopies)
1056             for (const Use &U : PotentialCopy->uses())
1057               Worklist.push_back(&U);
1058           continue;
1059         }
1060       }
1061     }
1062 
1063     bool Follow = false;
1064     if (!Pred(*U, Follow))
1065       return false;
1066     if (!Follow)
1067       continue;
1068     for (const Use &UU : U->getUser()->uses())
1069       Worklist.push_back(&UU);
1070   }
1071 
1072   return true;
1073 }
1074 
1075 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1076                                       const AbstractAttribute &QueryingAA,
1077                                       bool RequireAllCallSites,
1078                                       bool &AllCallSitesKnown) {
1079   // We can try to determine information from
1080   // the call sites. However, this is only possible all call sites are known,
1081   // hence the function has internal linkage.
1082   const IRPosition &IRP = QueryingAA.getIRPosition();
1083   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1084   if (!AssociatedFunction) {
1085     LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
1086                       << "\n");
1087     AllCallSitesKnown = false;
1088     return false;
1089   }
1090 
1091   return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
1092                               &QueryingAA, AllCallSitesKnown);
1093 }
1094 
1095 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1096                                       const Function &Fn,
1097                                       bool RequireAllCallSites,
1098                                       const AbstractAttribute *QueryingAA,
1099                                       bool &AllCallSitesKnown) {
1100   if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
1101     LLVM_DEBUG(
1102         dbgs()
1103         << "[Attributor] Function " << Fn.getName()
1104         << " has no internal linkage, hence not all call sites are known\n");
1105     AllCallSitesKnown = false;
1106     return false;
1107   }
1108 
1109   // If we do not require all call sites we might not see all.
1110   AllCallSitesKnown = RequireAllCallSites;
1111 
1112   SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses()));
1113   for (unsigned u = 0; u < Uses.size(); ++u) {
1114     const Use &U = *Uses[u];
1115     LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << *U << " in "
1116                       << *U.getUser() << "\n");
1117     bool UsedAssumedInformation = false;
1118     if (isAssumedDead(U, QueryingAA, nullptr, UsedAssumedInformation,
1119                       /* CheckBBLivenessOnly */ true)) {
1120       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
1121       continue;
1122     }
1123     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
1124       if (CE->isCast() && CE->getType()->isPointerTy() &&
1125           CE->getType()->getPointerElementType()->isFunctionTy()) {
1126         LLVM_DEBUG(
1127             dbgs() << "[Attributor] Use, is constant cast expression, add "
1128                    << CE->getNumUses()
1129                    << " uses of that expression instead!\n");
1130         for (const Use &CEU : CE->uses())
1131           Uses.push_back(&CEU);
1132         continue;
1133       }
1134     }
1135 
1136     AbstractCallSite ACS(&U);
1137     if (!ACS) {
1138       LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
1139                         << " has non call site use " << *U.get() << " in "
1140                         << *U.getUser() << "\n");
1141       // BlockAddress users are allowed.
1142       if (isa<BlockAddress>(U.getUser()))
1143         continue;
1144       return false;
1145     }
1146 
1147     const Use *EffectiveUse =
1148         ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
1149     if (!ACS.isCallee(EffectiveUse)) {
1150       if (!RequireAllCallSites) {
1151         LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
1152                           << " is not a call of " << Fn.getName()
1153                           << ", skip use\n");
1154         continue;
1155       }
1156       LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
1157                         << " is an invalid use of " << Fn.getName() << "\n");
1158       return false;
1159     }
1160 
1161     // Make sure the arguments that can be matched between the call site and the
1162     // callee argee on their type. It is unlikely they do not and it doesn't
1163     // make sense for all attributes to know/care about this.
1164     assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
1165     unsigned MinArgsParams =
1166         std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size());
1167     for (unsigned u = 0; u < MinArgsParams; ++u) {
1168       Value *CSArgOp = ACS.getCallArgOperand(u);
1169       if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) {
1170         LLVM_DEBUG(
1171             dbgs() << "[Attributor] Call site / callee argument type mismatch ["
1172                    << u << "@" << Fn.getName() << ": "
1173                    << *Fn.getArg(u)->getType() << " vs. "
1174                    << *ACS.getCallArgOperand(u)->getType() << "\n");
1175         return false;
1176       }
1177     }
1178 
1179     if (Pred(ACS))
1180       continue;
1181 
1182     LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
1183                       << *ACS.getInstruction() << "\n");
1184     return false;
1185   }
1186 
1187   return true;
1188 }
1189 
1190 bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
1191   // TODO: Maintain a cache of Values that are
1192   // on the pathway from a Argument to a Instruction that would effect the
1193   // liveness/return state etc.
1194   return EnableCallSiteSpecific;
1195 }
1196 
1197 bool Attributor::checkForAllReturnedValuesAndReturnInsts(
1198     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred,
1199     const AbstractAttribute &QueryingAA) {
1200 
1201   const IRPosition &IRP = QueryingAA.getIRPosition();
1202   // Since we need to provide return instructions we have to have an exact
1203   // definition.
1204   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1205   if (!AssociatedFunction)
1206     return false;
1207 
1208   // If this is a call site query we use the call site specific return values
1209   // and liveness information.
1210   // TODO: use the function scope once we have call site AAReturnedValues.
1211   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
1212   const auto &AARetVal =
1213       getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
1214   if (!AARetVal.getState().isValidState())
1215     return false;
1216 
1217   return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
1218 }
1219 
1220 bool Attributor::checkForAllReturnedValues(
1221     function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) {
1222 
1223   const IRPosition &IRP = QueryingAA.getIRPosition();
1224   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1225   if (!AssociatedFunction)
1226     return false;
1227 
1228   // TODO: use the function scope once we have call site AAReturnedValues.
1229   const IRPosition &QueryIRP = IRPosition::function(
1230       *AssociatedFunction, QueryingAA.getCallBaseContext());
1231   const auto &AARetVal =
1232       getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
1233   if (!AARetVal.getState().isValidState())
1234     return false;
1235 
1236   return AARetVal.checkForAllReturnedValuesAndReturnInsts(
1237       [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) {
1238         return Pred(RV);
1239       });
1240 }
1241 
1242 static bool checkForAllInstructionsImpl(
1243     Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
1244     function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
1245     const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes,
1246     bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false,
1247     bool CheckPotentiallyDead = false) {
1248   for (unsigned Opcode : Opcodes) {
1249     // Check if we have instructions with this opcode at all first.
1250     auto *Insts = OpcodeInstMap.lookup(Opcode);
1251     if (!Insts)
1252       continue;
1253 
1254     for (Instruction *I : *Insts) {
1255       // Skip dead instructions.
1256       if (A && !CheckPotentiallyDead &&
1257           A->isAssumedDead(IRPosition::value(*I), QueryingAA, LivenessAA,
1258                            UsedAssumedInformation, CheckBBLivenessOnly))
1259         continue;
1260 
1261       if (!Pred(*I))
1262         return false;
1263     }
1264   }
1265   return true;
1266 }
1267 
1268 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
1269                                          const AbstractAttribute &QueryingAA,
1270                                          const ArrayRef<unsigned> &Opcodes,
1271                                          bool &UsedAssumedInformation,
1272                                          bool CheckBBLivenessOnly,
1273                                          bool CheckPotentiallyDead) {
1274 
1275   const IRPosition &IRP = QueryingAA.getIRPosition();
1276   // Since we need to provide instructions we have to have an exact definition.
1277   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1278   if (!AssociatedFunction)
1279     return false;
1280 
1281   if (AssociatedFunction->isDeclaration())
1282     return false;
1283 
1284   // TODO: use the function scope once we have call site AAReturnedValues.
1285   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
1286   const auto *LivenessAA =
1287       (CheckBBLivenessOnly || CheckPotentiallyDead)
1288           ? nullptr
1289           : &(getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE));
1290 
1291   auto &OpcodeInstMap =
1292       InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction);
1293   if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA,
1294                                    LivenessAA, Opcodes, UsedAssumedInformation,
1295                                    CheckBBLivenessOnly, CheckPotentiallyDead))
1296     return false;
1297 
1298   return true;
1299 }
1300 
1301 bool Attributor::checkForAllReadWriteInstructions(
1302     function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA,
1303     bool &UsedAssumedInformation) {
1304 
1305   const Function *AssociatedFunction =
1306       QueryingAA.getIRPosition().getAssociatedFunction();
1307   if (!AssociatedFunction)
1308     return false;
1309 
1310   // TODO: use the function scope once we have call site AAReturnedValues.
1311   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
1312   const auto &LivenessAA =
1313       getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE);
1314 
1315   for (Instruction *I :
1316        InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
1317     // Skip dead instructions.
1318     if (isAssumedDead(IRPosition::value(*I), &QueryingAA, &LivenessAA,
1319                       UsedAssumedInformation))
1320       continue;
1321 
1322     if (!Pred(*I))
1323       return false;
1324   }
1325 
1326   return true;
1327 }
1328 
1329 void Attributor::runTillFixpoint() {
1330   TimeTraceScope TimeScope("Attributor::runTillFixpoint");
1331   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
1332                     << DG.SyntheticRoot.Deps.size()
1333                     << " abstract attributes.\n");
1334 
1335   // Now that all abstract attributes are collected and initialized we start
1336   // the abstract analysis.
1337 
1338   unsigned IterationCounter = 1;
1339   unsigned MaxFixedPointIterations;
1340   if (MaxFixpointIterations)
1341     MaxFixedPointIterations = MaxFixpointIterations.getValue();
1342   else
1343     MaxFixedPointIterations = SetFixpointIterations;
1344 
1345   SmallVector<AbstractAttribute *, 32> ChangedAAs;
1346   SetVector<AbstractAttribute *> Worklist, InvalidAAs;
1347   Worklist.insert(DG.SyntheticRoot.begin(), DG.SyntheticRoot.end());
1348 
1349   do {
1350     // Remember the size to determine new attributes.
1351     size_t NumAAs = DG.SyntheticRoot.Deps.size();
1352     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
1353                       << ", Worklist size: " << Worklist.size() << "\n");
1354 
1355     // For invalid AAs we can fix dependent AAs that have a required dependence,
1356     // thereby folding long dependence chains in a single step without the need
1357     // to run updates.
1358     for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
1359       AbstractAttribute *InvalidAA = InvalidAAs[u];
1360 
1361       // Check the dependences to fast track invalidation.
1362       LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has "
1363                         << InvalidAA->Deps.size()
1364                         << " required & optional dependences\n");
1365       while (!InvalidAA->Deps.empty()) {
1366         const auto &Dep = InvalidAA->Deps.back();
1367         InvalidAA->Deps.pop_back();
1368         AbstractAttribute *DepAA = cast<AbstractAttribute>(Dep.getPointer());
1369         if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) {
1370           Worklist.insert(DepAA);
1371           continue;
1372         }
1373         DepAA->getState().indicatePessimisticFixpoint();
1374         assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
1375         if (!DepAA->getState().isValidState())
1376           InvalidAAs.insert(DepAA);
1377         else
1378           ChangedAAs.push_back(DepAA);
1379       }
1380     }
1381 
1382     // Add all abstract attributes that are potentially dependent on one that
1383     // changed to the work list.
1384     for (AbstractAttribute *ChangedAA : ChangedAAs)
1385       while (!ChangedAA->Deps.empty()) {
1386         Worklist.insert(
1387             cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
1388         ChangedAA->Deps.pop_back();
1389       }
1390 
1391     LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
1392                       << ", Worklist+Dependent size: " << Worklist.size()
1393                       << "\n");
1394 
1395     // Reset the changed and invalid set.
1396     ChangedAAs.clear();
1397     InvalidAAs.clear();
1398 
1399     // Update all abstract attribute in the work list and record the ones that
1400     // changed.
1401     for (AbstractAttribute *AA : Worklist) {
1402       const auto &AAState = AA->getState();
1403       if (!AAState.isAtFixpoint())
1404         if (updateAA(*AA) == ChangeStatus::CHANGED)
1405           ChangedAAs.push_back(AA);
1406 
1407       // Use the InvalidAAs vector to propagate invalid states fast transitively
1408       // without requiring updates.
1409       if (!AAState.isValidState())
1410         InvalidAAs.insert(AA);
1411     }
1412 
1413     // Add attributes to the changed set if they have been created in the last
1414     // iteration.
1415     ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs,
1416                       DG.SyntheticRoot.end());
1417 
1418     // Reset the work list and repopulate with the changed abstract attributes.
1419     // Note that dependent ones are added above.
1420     Worklist.clear();
1421     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
1422 
1423   } while (!Worklist.empty() && (IterationCounter++ < MaxFixedPointIterations ||
1424                                  VerifyMaxFixpointIterations));
1425 
1426   if (IterationCounter > MaxFixedPointIterations && !Worklist.empty()) {
1427     auto Remark = [&](OptimizationRemarkMissed ORM) {
1428       return ORM << "Attributor did not reach a fixpoint after "
1429                  << ore::NV("Iterations", MaxFixedPointIterations)
1430                  << " iterations.";
1431     };
1432     Function *F = Worklist.front()->getIRPosition().getAssociatedFunction();
1433     emitRemark<OptimizationRemarkMissed>(F, "FixedPoint", Remark);
1434   }
1435 
1436   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
1437                     << IterationCounter << "/" << MaxFixpointIterations
1438                     << " iterations\n");
1439 
1440   // Reset abstract arguments not settled in a sound fixpoint by now. This
1441   // happens when we stopped the fixpoint iteration early. Note that only the
1442   // ones marked as "changed" *and* the ones transitively depending on them
1443   // need to be reverted to a pessimistic state. Others might not be in a
1444   // fixpoint state but we can use the optimistic results for them anyway.
1445   SmallPtrSet<AbstractAttribute *, 32> Visited;
1446   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
1447     AbstractAttribute *ChangedAA = ChangedAAs[u];
1448     if (!Visited.insert(ChangedAA).second)
1449       continue;
1450 
1451     AbstractState &State = ChangedAA->getState();
1452     if (!State.isAtFixpoint()) {
1453       State.indicatePessimisticFixpoint();
1454 
1455       NumAttributesTimedOut++;
1456     }
1457 
1458     while (!ChangedAA->Deps.empty()) {
1459       ChangedAAs.push_back(
1460           cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
1461       ChangedAA->Deps.pop_back();
1462     }
1463   }
1464 
1465   LLVM_DEBUG({
1466     if (!Visited.empty())
1467       dbgs() << "\n[Attributor] Finalized " << Visited.size()
1468              << " abstract attributes.\n";
1469   });
1470 
1471   if (VerifyMaxFixpointIterations &&
1472       IterationCounter != MaxFixedPointIterations) {
1473     errs() << "\n[Attributor] Fixpoint iteration done after: "
1474            << IterationCounter << "/" << MaxFixedPointIterations
1475            << " iterations\n";
1476     llvm_unreachable("The fixpoint was not reached with exactly the number of "
1477                      "specified iterations!");
1478   }
1479 }
1480 
1481 ChangeStatus Attributor::manifestAttributes() {
1482   TimeTraceScope TimeScope("Attributor::manifestAttributes");
1483   size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
1484 
1485   unsigned NumManifested = 0;
1486   unsigned NumAtFixpoint = 0;
1487   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
1488   for (auto &DepAA : DG.SyntheticRoot.Deps) {
1489     AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
1490     AbstractState &State = AA->getState();
1491 
1492     // If there is not already a fixpoint reached, we can now take the
1493     // optimistic state. This is correct because we enforced a pessimistic one
1494     // on abstract attributes that were transitively dependent on a changed one
1495     // already above.
1496     if (!State.isAtFixpoint())
1497       State.indicateOptimisticFixpoint();
1498 
1499     // We must not manifest Attributes that use Callbase info.
1500     if (AA->hasCallBaseContext())
1501       continue;
1502     // If the state is invalid, we do not try to manifest it.
1503     if (!State.isValidState())
1504       continue;
1505 
1506     // Skip dead code.
1507     bool UsedAssumedInformation = false;
1508     if (isAssumedDead(*AA, nullptr, UsedAssumedInformation,
1509                       /* CheckBBLivenessOnly */ true))
1510       continue;
1511     // Check if the manifest debug counter that allows skipping manifestation of
1512     // AAs
1513     if (!DebugCounter::shouldExecute(ManifestDBGCounter))
1514       continue;
1515     // Manifest the state and record if we changed the IR.
1516     ChangeStatus LocalChange = AA->manifest(*this);
1517     if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
1518       AA->trackStatistics();
1519     LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
1520                       << "\n");
1521 
1522     ManifestChange = ManifestChange | LocalChange;
1523 
1524     NumAtFixpoint++;
1525     NumManifested += (LocalChange == ChangeStatus::CHANGED);
1526   }
1527 
1528   (void)NumManifested;
1529   (void)NumAtFixpoint;
1530   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
1531                     << " arguments while " << NumAtFixpoint
1532                     << " were in a valid fixpoint state\n");
1533 
1534   NumAttributesManifested += NumManifested;
1535   NumAttributesValidFixpoint += NumAtFixpoint;
1536 
1537   (void)NumFinalAAs;
1538   if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
1539     for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size(); ++u)
1540       errs() << "Unexpected abstract attribute: "
1541              << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
1542              << " :: "
1543              << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
1544                     ->getIRPosition()
1545                     .getAssociatedValue()
1546              << "\n";
1547     llvm_unreachable("Expected the final number of abstract attributes to "
1548                      "remain unchanged!");
1549   }
1550   return ManifestChange;
1551 }
1552 
1553 void Attributor::identifyDeadInternalFunctions() {
1554   // Early exit if we don't intend to delete functions.
1555   if (!DeleteFns)
1556     return;
1557 
1558   // Identify dead internal functions and delete them. This happens outside
1559   // the other fixpoint analysis as we might treat potentially dead functions
1560   // as live to lower the number of iterations. If they happen to be dead, the
1561   // below fixpoint loop will identify and eliminate them.
1562   SmallVector<Function *, 8> InternalFns;
1563   for (Function *F : Functions)
1564     if (F->hasLocalLinkage())
1565       InternalFns.push_back(F);
1566 
1567   SmallPtrSet<Function *, 8> LiveInternalFns;
1568   bool FoundLiveInternal = true;
1569   while (FoundLiveInternal) {
1570     FoundLiveInternal = false;
1571     for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) {
1572       Function *F = InternalFns[u];
1573       if (!F)
1574         continue;
1575 
1576       bool AllCallSitesKnown;
1577       if (checkForAllCallSites(
1578               [&](AbstractCallSite ACS) {
1579                 Function *Callee = ACS.getInstruction()->getFunction();
1580                 return ToBeDeletedFunctions.count(Callee) ||
1581                        (Functions.count(Callee) && Callee->hasLocalLinkage() &&
1582                         !LiveInternalFns.count(Callee));
1583               },
1584               *F, true, nullptr, AllCallSitesKnown)) {
1585         continue;
1586       }
1587 
1588       LiveInternalFns.insert(F);
1589       InternalFns[u] = nullptr;
1590       FoundLiveInternal = true;
1591     }
1592   }
1593 
1594   for (unsigned u = 0, e = InternalFns.size(); u < e; ++u)
1595     if (Function *F = InternalFns[u])
1596       ToBeDeletedFunctions.insert(F);
1597 }
1598 
1599 ChangeStatus Attributor::cleanupIR() {
1600   TimeTraceScope TimeScope("Attributor::cleanupIR");
1601   // Delete stuff at the end to avoid invalid references and a nice order.
1602   LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least "
1603                     << ToBeDeletedFunctions.size() << " functions and "
1604                     << ToBeDeletedBlocks.size() << " blocks and "
1605                     << ToBeDeletedInsts.size() << " instructions and "
1606                     << ToBeChangedValues.size() << " values and "
1607                     << ToBeChangedUses.size() << " uses. "
1608                     << "Preserve manifest added " << ManifestAddedBlocks.size()
1609                     << " blocks\n");
1610 
1611   SmallVector<WeakTrackingVH, 32> DeadInsts;
1612   SmallVector<Instruction *, 32> TerminatorsToFold;
1613 
1614   auto ReplaceUse = [&](Use *U, Value *NewV) {
1615     Value *OldV = U->get();
1616 
1617     // If we plan to replace NewV we need to update it at this point.
1618     do {
1619       const auto &Entry = ToBeChangedValues.lookup(NewV);
1620       if (!Entry.first)
1621         break;
1622       NewV = Entry.first;
1623     } while (true);
1624 
1625     // Do not replace uses in returns if the value is a must-tail call we will
1626     // not delete.
1627     if (auto *RI = dyn_cast<ReturnInst>(U->getUser())) {
1628       if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
1629         if (CI->isMustTailCall() &&
1630             (!ToBeDeletedInsts.count(CI) || !isRunOn(*CI->getCaller())))
1631           return;
1632       // If we rewrite a return and the new value is not an argument, strip the
1633       // `returned` attribute as it is wrong now.
1634       if (!isa<Argument>(NewV))
1635         for (auto &Arg : RI->getFunction()->args())
1636           Arg.removeAttr(Attribute::Returned);
1637     }
1638 
1639     // Do not perform call graph altering changes outside the SCC.
1640     if (auto *CB = dyn_cast<CallBase>(U->getUser()))
1641       if (CB->isCallee(U) && !isRunOn(*CB->getCaller()))
1642         return;
1643 
1644     LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
1645                       << " instead of " << *OldV << "\n");
1646     U->set(NewV);
1647 
1648     if (Instruction *I = dyn_cast<Instruction>(OldV)) {
1649       CGModifiedFunctions.insert(I->getFunction());
1650       if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) &&
1651           isInstructionTriviallyDead(I))
1652         DeadInsts.push_back(I);
1653     }
1654     if (isa<UndefValue>(NewV) && isa<CallBase>(U->getUser())) {
1655       auto *CB = cast<CallBase>(U->getUser());
1656       if (CB->isArgOperand(U)) {
1657         unsigned Idx = CB->getArgOperandNo(U);
1658         CB->removeParamAttr(Idx, Attribute::NoUndef);
1659         Function *Fn = CB->getCalledFunction();
1660         if (Fn && Fn->arg_size() > Idx)
1661           Fn->removeParamAttr(Idx, Attribute::NoUndef);
1662       }
1663     }
1664     if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) {
1665       Instruction *UserI = cast<Instruction>(U->getUser());
1666       if (isa<UndefValue>(NewV)) {
1667         ToBeChangedToUnreachableInsts.insert(UserI);
1668       } else {
1669         TerminatorsToFold.push_back(UserI);
1670       }
1671     }
1672   };
1673 
1674   for (auto &It : ToBeChangedUses) {
1675     Use *U = It.first;
1676     Value *NewV = It.second;
1677     ReplaceUse(U, NewV);
1678   }
1679 
1680   SmallVector<Use *, 4> Uses;
1681   for (auto &It : ToBeChangedValues) {
1682     Value *OldV = It.first;
1683     auto &Entry = It.second;
1684     Value *NewV = Entry.first;
1685     Uses.clear();
1686     for (auto &U : OldV->uses())
1687       if (Entry.second || !U.getUser()->isDroppable())
1688         Uses.push_back(&U);
1689     for (Use *U : Uses)
1690       ReplaceUse(U, NewV);
1691   }
1692 
1693   for (auto &V : InvokeWithDeadSuccessor)
1694     if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
1695       assert(isRunOn(*II->getFunction()) &&
1696              "Cannot replace an invoke outside the current SCC!");
1697       bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
1698       bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
1699       bool Invoke2CallAllowed =
1700           !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction());
1701       assert((UnwindBBIsDead || NormalBBIsDead) &&
1702              "Invoke does not have dead successors!");
1703       BasicBlock *BB = II->getParent();
1704       BasicBlock *NormalDestBB = II->getNormalDest();
1705       if (UnwindBBIsDead) {
1706         Instruction *NormalNextIP = &NormalDestBB->front();
1707         if (Invoke2CallAllowed) {
1708           changeToCall(II);
1709           NormalNextIP = BB->getTerminator();
1710         }
1711         if (NormalBBIsDead)
1712           ToBeChangedToUnreachableInsts.insert(NormalNextIP);
1713       } else {
1714         assert(NormalBBIsDead && "Broken invariant!");
1715         if (!NormalDestBB->getUniquePredecessor())
1716           NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead");
1717         ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front());
1718       }
1719     }
1720   for (Instruction *I : TerminatorsToFold) {
1721     if (!isRunOn(*I->getFunction()))
1722       continue;
1723     CGModifiedFunctions.insert(I->getFunction());
1724     ConstantFoldTerminator(I->getParent());
1725   }
1726   for (auto &V : ToBeChangedToUnreachableInsts)
1727     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
1728       if (!isRunOn(*I->getFunction()))
1729         continue;
1730       CGModifiedFunctions.insert(I->getFunction());
1731       changeToUnreachable(I);
1732     }
1733 
1734   for (auto &V : ToBeDeletedInsts) {
1735     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
1736       if (auto *CB = dyn_cast<CallBase>(I)) {
1737         if (!isRunOn(*I->getFunction()))
1738           continue;
1739         if (!isa<IntrinsicInst>(CB))
1740           CGUpdater.removeCallSite(*CB);
1741       }
1742       I->dropDroppableUses();
1743       CGModifiedFunctions.insert(I->getFunction());
1744       if (!I->getType()->isVoidTy())
1745         I->replaceAllUsesWith(UndefValue::get(I->getType()));
1746       if (!isa<PHINode>(I) && isInstructionTriviallyDead(I))
1747         DeadInsts.push_back(I);
1748       else
1749         I->eraseFromParent();
1750     }
1751   }
1752 
1753   llvm::erase_if(DeadInsts, [&](WeakTrackingVH I) {
1754     return !I || !isRunOn(*cast<Instruction>(I)->getFunction());
1755   });
1756 
1757   LLVM_DEBUG({
1758     dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n";
1759     for (auto &I : DeadInsts)
1760       if (I)
1761         dbgs() << "  - " << *I << "\n";
1762   });
1763 
1764   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
1765 
1766   if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
1767     SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
1768     ToBeDeletedBBs.reserve(NumDeadBlocks);
1769     for (BasicBlock *BB : ToBeDeletedBlocks) {
1770       assert(isRunOn(*BB->getParent()) &&
1771              "Cannot delete a block outside the current SCC!");
1772       CGModifiedFunctions.insert(BB->getParent());
1773       // Do not delete BBs added during manifests of AAs.
1774       if (ManifestAddedBlocks.contains(BB))
1775         continue;
1776       ToBeDeletedBBs.push_back(BB);
1777     }
1778     // Actually we do not delete the blocks but squash them into a single
1779     // unreachable but untangling branches that jump here is something we need
1780     // to do in a more generic way.
1781     DetatchDeadBlocks(ToBeDeletedBBs, nullptr);
1782   }
1783 
1784   identifyDeadInternalFunctions();
1785 
1786   // Rewrite the functions as requested during manifest.
1787   ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
1788 
1789   for (Function *Fn : CGModifiedFunctions)
1790     if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn))
1791       CGUpdater.reanalyzeFunction(*Fn);
1792 
1793   for (Function *Fn : ToBeDeletedFunctions) {
1794     if (!Functions.count(Fn))
1795       continue;
1796     CGUpdater.removeFunction(*Fn);
1797   }
1798 
1799   if (!ToBeChangedUses.empty())
1800     ManifestChange = ChangeStatus::CHANGED;
1801 
1802   if (!ToBeChangedToUnreachableInsts.empty())
1803     ManifestChange = ChangeStatus::CHANGED;
1804 
1805   if (!ToBeDeletedFunctions.empty())
1806     ManifestChange = ChangeStatus::CHANGED;
1807 
1808   if (!ToBeDeletedBlocks.empty())
1809     ManifestChange = ChangeStatus::CHANGED;
1810 
1811   if (!ToBeDeletedInsts.empty())
1812     ManifestChange = ChangeStatus::CHANGED;
1813 
1814   if (!InvokeWithDeadSuccessor.empty())
1815     ManifestChange = ChangeStatus::CHANGED;
1816 
1817   if (!DeadInsts.empty())
1818     ManifestChange = ChangeStatus::CHANGED;
1819 
1820   NumFnDeleted += ToBeDeletedFunctions.size();
1821 
1822   LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
1823                     << " functions after manifest.\n");
1824 
1825 #ifdef EXPENSIVE_CHECKS
1826   for (Function *F : Functions) {
1827     if (ToBeDeletedFunctions.count(F))
1828       continue;
1829     assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
1830   }
1831 #endif
1832 
1833   return ManifestChange;
1834 }
1835 
1836 ChangeStatus Attributor::run() {
1837   TimeTraceScope TimeScope("Attributor::run");
1838   AttributorCallGraph ACallGraph(*this);
1839 
1840   if (PrintCallGraph)
1841     ACallGraph.populateAll();
1842 
1843   Phase = AttributorPhase::UPDATE;
1844   runTillFixpoint();
1845 
1846   // dump graphs on demand
1847   if (DumpDepGraph)
1848     DG.dumpGraph();
1849 
1850   if (ViewDepGraph)
1851     DG.viewGraph();
1852 
1853   if (PrintDependencies)
1854     DG.print();
1855 
1856   Phase = AttributorPhase::MANIFEST;
1857   ChangeStatus ManifestChange = manifestAttributes();
1858 
1859   Phase = AttributorPhase::CLEANUP;
1860   ChangeStatus CleanupChange = cleanupIR();
1861 
1862   if (PrintCallGraph)
1863     ACallGraph.print();
1864 
1865   return ManifestChange | CleanupChange;
1866 }
1867 
1868 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
1869   TimeTraceScope TimeScope(
1870       AA.getName() + std::to_string(AA.getIRPosition().getPositionKind()) +
1871       "::updateAA");
1872   assert(Phase == AttributorPhase::UPDATE &&
1873          "We can update AA only in the update stage!");
1874 
1875   // Use a new dependence vector for this update.
1876   DependenceVector DV;
1877   DependenceStack.push_back(&DV);
1878 
1879   auto &AAState = AA.getState();
1880   ChangeStatus CS = ChangeStatus::UNCHANGED;
1881   bool UsedAssumedInformation = false;
1882   if (!isAssumedDead(AA, nullptr, UsedAssumedInformation,
1883                      /* CheckBBLivenessOnly */ true))
1884     CS = AA.update(*this);
1885 
1886   if (DV.empty()) {
1887     // If the attribute did not query any non-fix information, the state
1888     // will not change and we can indicate that right away.
1889     AAState.indicateOptimisticFixpoint();
1890   }
1891 
1892   if (!AAState.isAtFixpoint())
1893     rememberDependences();
1894 
1895   // Verify the stack was used properly, that is we pop the dependence vector we
1896   // put there earlier.
1897   DependenceVector *PoppedDV = DependenceStack.pop_back_val();
1898   (void)PoppedDV;
1899   assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
1900 
1901   return CS;
1902 }
1903 
1904 void Attributor::createShallowWrapper(Function &F) {
1905   assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
1906 
1907   Module &M = *F.getParent();
1908   LLVMContext &Ctx = M.getContext();
1909   FunctionType *FnTy = F.getFunctionType();
1910 
1911   Function *Wrapper =
1912       Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName());
1913   F.setName(""); // set the inside function anonymous
1914   M.getFunctionList().insert(F.getIterator(), Wrapper);
1915 
1916   F.setLinkage(GlobalValue::InternalLinkage);
1917 
1918   F.replaceAllUsesWith(Wrapper);
1919   assert(F.use_empty() && "Uses remained after wrapper was created!");
1920 
1921   // Move the COMDAT section to the wrapper.
1922   // TODO: Check if we need to keep it for F as well.
1923   Wrapper->setComdat(F.getComdat());
1924   F.setComdat(nullptr);
1925 
1926   // Copy all metadata and attributes but keep them on F as well.
1927   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1928   F.getAllMetadata(MDs);
1929   for (auto MDIt : MDs)
1930     Wrapper->addMetadata(MDIt.first, *MDIt.second);
1931   Wrapper->setAttributes(F.getAttributes());
1932 
1933   // Create the call in the wrapper.
1934   BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper);
1935 
1936   SmallVector<Value *, 8> Args;
1937   Argument *FArgIt = F.arg_begin();
1938   for (Argument &Arg : Wrapper->args()) {
1939     Args.push_back(&Arg);
1940     Arg.setName((FArgIt++)->getName());
1941   }
1942 
1943   CallInst *CI = CallInst::Create(&F, Args, "", EntryBB);
1944   CI->setTailCall(true);
1945   CI->addFnAttr(Attribute::NoInline);
1946   ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB);
1947 
1948   NumFnShallowWrappersCreated++;
1949 }
1950 
1951 bool Attributor::isInternalizable(Function &F) {
1952   if (F.isDeclaration() || F.hasLocalLinkage() ||
1953       GlobalValue::isInterposableLinkage(F.getLinkage()))
1954     return false;
1955   return true;
1956 }
1957 
1958 Function *Attributor::internalizeFunction(Function &F, bool Force) {
1959   if (!AllowDeepWrapper && !Force)
1960     return nullptr;
1961   if (!isInternalizable(F))
1962     return nullptr;
1963 
1964   SmallPtrSet<Function *, 2> FnSet = {&F};
1965   DenseMap<Function *, Function *> InternalizedFns;
1966   internalizeFunctions(FnSet, InternalizedFns);
1967 
1968   return InternalizedFns[&F];
1969 }
1970 
1971 bool Attributor::internalizeFunctions(SmallPtrSetImpl<Function *> &FnSet,
1972                                       DenseMap<Function *, Function *> &FnMap) {
1973   for (Function *F : FnSet)
1974     if (!Attributor::isInternalizable(*F))
1975       return false;
1976 
1977   FnMap.clear();
1978   // Generate the internalized version of each function.
1979   for (Function *F : FnSet) {
1980     Module &M = *F->getParent();
1981     FunctionType *FnTy = F->getFunctionType();
1982 
1983     // Create a copy of the current function
1984     Function *Copied =
1985         Function::Create(FnTy, F->getLinkage(), F->getAddressSpace(),
1986                          F->getName() + ".internalized");
1987     ValueToValueMapTy VMap;
1988     auto *NewFArgIt = Copied->arg_begin();
1989     for (auto &Arg : F->args()) {
1990       auto ArgName = Arg.getName();
1991       NewFArgIt->setName(ArgName);
1992       VMap[&Arg] = &(*NewFArgIt++);
1993     }
1994     SmallVector<ReturnInst *, 8> Returns;
1995 
1996     // Copy the body of the original function to the new one
1997     CloneFunctionInto(Copied, F, VMap,
1998                       CloneFunctionChangeType::LocalChangesOnly, Returns);
1999 
2000     // Set the linakage and visibility late as CloneFunctionInto has some
2001     // implicit requirements.
2002     Copied->setVisibility(GlobalValue::DefaultVisibility);
2003     Copied->setLinkage(GlobalValue::PrivateLinkage);
2004 
2005     // Copy metadata
2006     SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2007     F->getAllMetadata(MDs);
2008     for (auto MDIt : MDs)
2009       if (!Copied->hasMetadata())
2010         Copied->addMetadata(MDIt.first, *MDIt.second);
2011 
2012     M.getFunctionList().insert(F->getIterator(), Copied);
2013     Copied->setDSOLocal(true);
2014     FnMap[F] = Copied;
2015   }
2016 
2017   // Replace all uses of the old function with the new internalized function
2018   // unless the caller is a function that was just internalized.
2019   for (Function *F : FnSet) {
2020     auto &InternalizedFn = FnMap[F];
2021     auto IsNotInternalized = [&](Use &U) -> bool {
2022       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
2023         return !FnMap.lookup(CB->getCaller());
2024       return false;
2025     };
2026     F->replaceUsesWithIf(InternalizedFn, IsNotInternalized);
2027   }
2028 
2029   return true;
2030 }
2031 
2032 bool Attributor::isValidFunctionSignatureRewrite(
2033     Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
2034 
2035   if (!RewriteSignatures)
2036     return false;
2037 
2038   Function *Fn = Arg.getParent();
2039   auto CallSiteCanBeChanged = [Fn](AbstractCallSite ACS) {
2040     // Forbid the call site to cast the function return type. If we need to
2041     // rewrite these functions we need to re-create a cast for the new call site
2042     // (if the old had uses).
2043     if (!ACS.getCalledFunction() ||
2044         ACS.getInstruction()->getType() !=
2045             ACS.getCalledFunction()->getReturnType())
2046       return false;
2047     if (ACS.getCalledOperand()->getType() != Fn->getType())
2048       return false;
2049     // Forbid must-tail calls for now.
2050     return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
2051   };
2052 
2053   // Avoid var-arg functions for now.
2054   if (Fn->isVarArg()) {
2055     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
2056     return false;
2057   }
2058 
2059   // Avoid functions with complicated argument passing semantics.
2060   AttributeList FnAttributeList = Fn->getAttributes();
2061   if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
2062       FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
2063       FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
2064       FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
2065     LLVM_DEBUG(
2066         dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
2067     return false;
2068   }
2069 
2070   // Avoid callbacks for now.
2071   bool AllCallSitesKnown;
2072   if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr,
2073                             AllCallSitesKnown)) {
2074     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
2075     return false;
2076   }
2077 
2078   auto InstPred = [](Instruction &I) {
2079     if (auto *CI = dyn_cast<CallInst>(&I))
2080       return !CI->isMustTailCall();
2081     return true;
2082   };
2083 
2084   // Forbid must-tail calls for now.
2085   // TODO:
2086   bool UsedAssumedInformation = false;
2087   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
2088   if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr,
2089                                    nullptr, {Instruction::Call},
2090                                    UsedAssumedInformation)) {
2091     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
2092     return false;
2093   }
2094 
2095   return true;
2096 }
2097 
2098 bool Attributor::registerFunctionSignatureRewrite(
2099     Argument &Arg, ArrayRef<Type *> ReplacementTypes,
2100     ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
2101     ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
2102   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2103                     << Arg.getParent()->getName() << " with "
2104                     << ReplacementTypes.size() << " replacements\n");
2105   assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
2106          "Cannot register an invalid rewrite");
2107 
2108   Function *Fn = Arg.getParent();
2109   SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
2110       ArgumentReplacementMap[Fn];
2111   if (ARIs.empty())
2112     ARIs.resize(Fn->arg_size());
2113 
2114   // If we have a replacement already with less than or equal new arguments,
2115   // ignore this request.
2116   std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
2117   if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
2118     LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
2119     return false;
2120   }
2121 
2122   // If we have a replacement already but we like the new one better, delete
2123   // the old.
2124   ARI.reset();
2125 
2126   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2127                     << Arg.getParent()->getName() << " with "
2128                     << ReplacementTypes.size() << " replacements\n");
2129 
2130   // Remember the replacement.
2131   ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
2132                                         std::move(CalleeRepairCB),
2133                                         std::move(ACSRepairCB)));
2134 
2135   return true;
2136 }
2137 
2138 bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
2139   bool Result = true;
2140 #ifndef NDEBUG
2141   if (SeedAllowList.size() != 0)
2142     Result = llvm::is_contained(SeedAllowList, AA.getName());
2143   Function *Fn = AA.getAnchorScope();
2144   if (FunctionSeedAllowList.size() != 0 && Fn)
2145     Result &= llvm::is_contained(FunctionSeedAllowList, Fn->getName());
2146 #endif
2147   return Result;
2148 }
2149 
2150 ChangeStatus Attributor::rewriteFunctionSignatures(
2151     SmallPtrSetImpl<Function *> &ModifiedFns) {
2152   ChangeStatus Changed = ChangeStatus::UNCHANGED;
2153 
2154   for (auto &It : ArgumentReplacementMap) {
2155     Function *OldFn = It.getFirst();
2156 
2157     // Deleted functions do not require rewrites.
2158     if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
2159       continue;
2160 
2161     const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
2162         It.getSecond();
2163     assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
2164 
2165     SmallVector<Type *, 16> NewArgumentTypes;
2166     SmallVector<AttributeSet, 16> NewArgumentAttributes;
2167 
2168     // Collect replacement argument types and copy over existing attributes.
2169     AttributeList OldFnAttributeList = OldFn->getAttributes();
2170     for (Argument &Arg : OldFn->args()) {
2171       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2172               ARIs[Arg.getArgNo()]) {
2173         NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
2174                                 ARI->ReplacementTypes.end());
2175         NewArgumentAttributes.append(ARI->getNumReplacementArgs(),
2176                                      AttributeSet());
2177       } else {
2178         NewArgumentTypes.push_back(Arg.getType());
2179         NewArgumentAttributes.push_back(
2180             OldFnAttributeList.getParamAttrs(Arg.getArgNo()));
2181       }
2182     }
2183 
2184     FunctionType *OldFnTy = OldFn->getFunctionType();
2185     Type *RetTy = OldFnTy->getReturnType();
2186 
2187     // Construct the new function type using the new arguments types.
2188     FunctionType *NewFnTy =
2189         FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg());
2190 
2191     LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
2192                       << "' from " << *OldFn->getFunctionType() << " to "
2193                       << *NewFnTy << "\n");
2194 
2195     // Create the new function body and insert it into the module.
2196     Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(),
2197                                        OldFn->getAddressSpace(), "");
2198     Functions.insert(NewFn);
2199     OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn);
2200     NewFn->takeName(OldFn);
2201     NewFn->copyAttributesFrom(OldFn);
2202 
2203     // Patch the pointer to LLVM function in debug info descriptor.
2204     NewFn->setSubprogram(OldFn->getSubprogram());
2205     OldFn->setSubprogram(nullptr);
2206 
2207     // Recompute the parameter attributes list based on the new arguments for
2208     // the function.
2209     LLVMContext &Ctx = OldFn->getContext();
2210     NewFn->setAttributes(AttributeList::get(
2211         Ctx, OldFnAttributeList.getFnAttrs(), OldFnAttributeList.getRetAttrs(),
2212         NewArgumentAttributes));
2213 
2214     // Since we have now created the new function, splice the body of the old
2215     // function right into the new function, leaving the old rotting hulk of the
2216     // function empty.
2217     NewFn->getBasicBlockList().splice(NewFn->begin(),
2218                                       OldFn->getBasicBlockList());
2219 
2220     // Fixup block addresses to reference new function.
2221     SmallVector<BlockAddress *, 8u> BlockAddresses;
2222     for (User *U : OldFn->users())
2223       if (auto *BA = dyn_cast<BlockAddress>(U))
2224         BlockAddresses.push_back(BA);
2225     for (auto *BA : BlockAddresses)
2226       BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock()));
2227 
2228     // Set of all "call-like" instructions that invoke the old function mapped
2229     // to their new replacements.
2230     SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
2231 
2232     // Callback to create a new "call-like" instruction for a given one.
2233     auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
2234       CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
2235       const AttributeList &OldCallAttributeList = OldCB->getAttributes();
2236 
2237       // Collect the new argument operands for the replacement call site.
2238       SmallVector<Value *, 16> NewArgOperands;
2239       SmallVector<AttributeSet, 16> NewArgOperandAttributes;
2240       for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
2241         unsigned NewFirstArgNum = NewArgOperands.size();
2242         (void)NewFirstArgNum; // only used inside assert.
2243         if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2244                 ARIs[OldArgNum]) {
2245           if (ARI->ACSRepairCB)
2246             ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
2247           assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
2248                      NewArgOperands.size() &&
2249                  "ACS repair callback did not provide as many operand as new "
2250                  "types were registered!");
2251           // TODO: Exose the attribute set to the ACS repair callback
2252           NewArgOperandAttributes.append(ARI->ReplacementTypes.size(),
2253                                          AttributeSet());
2254         } else {
2255           NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum));
2256           NewArgOperandAttributes.push_back(
2257               OldCallAttributeList.getParamAttrs(OldArgNum));
2258         }
2259       }
2260 
2261       assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
2262              "Mismatch # argument operands vs. # argument operand attributes!");
2263       assert(NewArgOperands.size() == NewFn->arg_size() &&
2264              "Mismatch # argument operands vs. # function arguments!");
2265 
2266       SmallVector<OperandBundleDef, 4> OperandBundleDefs;
2267       OldCB->getOperandBundlesAsDefs(OperandBundleDefs);
2268 
2269       // Create a new call or invoke instruction to replace the old one.
2270       CallBase *NewCB;
2271       if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
2272         NewCB =
2273             InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(),
2274                                NewArgOperands, OperandBundleDefs, "", OldCB);
2275       } else {
2276         auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs,
2277                                        "", OldCB);
2278         NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
2279         NewCB = NewCI;
2280       }
2281 
2282       // Copy over various properties and the new attributes.
2283       NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
2284       NewCB->setCallingConv(OldCB->getCallingConv());
2285       NewCB->takeName(OldCB);
2286       NewCB->setAttributes(AttributeList::get(
2287           Ctx, OldCallAttributeList.getFnAttrs(),
2288           OldCallAttributeList.getRetAttrs(), NewArgOperandAttributes));
2289 
2290       CallSitePairs.push_back({OldCB, NewCB});
2291       return true;
2292     };
2293 
2294     // Use the CallSiteReplacementCreator to create replacement call sites.
2295     bool AllCallSitesKnown;
2296     bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
2297                                         true, nullptr, AllCallSitesKnown);
2298     (void)Success;
2299     assert(Success && "Assumed call site replacement to succeed!");
2300 
2301     // Rewire the arguments.
2302     Argument *OldFnArgIt = OldFn->arg_begin();
2303     Argument *NewFnArgIt = NewFn->arg_begin();
2304     for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
2305          ++OldArgNum, ++OldFnArgIt) {
2306       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2307               ARIs[OldArgNum]) {
2308         if (ARI->CalleeRepairCB)
2309           ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
2310         NewFnArgIt += ARI->ReplacementTypes.size();
2311       } else {
2312         NewFnArgIt->takeName(&*OldFnArgIt);
2313         OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
2314         ++NewFnArgIt;
2315       }
2316     }
2317 
2318     // Eliminate the instructions *after* we visited all of them.
2319     for (auto &CallSitePair : CallSitePairs) {
2320       CallBase &OldCB = *CallSitePair.first;
2321       CallBase &NewCB = *CallSitePair.second;
2322       assert(OldCB.getType() == NewCB.getType() &&
2323              "Cannot handle call sites with different types!");
2324       ModifiedFns.insert(OldCB.getFunction());
2325       CGUpdater.replaceCallSite(OldCB, NewCB);
2326       OldCB.replaceAllUsesWith(&NewCB);
2327       OldCB.eraseFromParent();
2328     }
2329 
2330     // Replace the function in the call graph (if any).
2331     CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
2332 
2333     // If the old function was modified and needed to be reanalyzed, the new one
2334     // does now.
2335     if (ModifiedFns.erase(OldFn))
2336       ModifiedFns.insert(NewFn);
2337 
2338     Changed = ChangeStatus::CHANGED;
2339   }
2340 
2341   return Changed;
2342 }
2343 
2344 void InformationCache::initializeInformationCache(const Function &CF,
2345                                                   FunctionInfo &FI) {
2346   // As we do not modify the function here we can remove the const
2347   // withouth breaking implicit assumptions. At the end of the day, we could
2348   // initialize the cache eagerly which would look the same to the users.
2349   Function &F = const_cast<Function &>(CF);
2350 
2351   // Walk all instructions to find interesting instructions that might be
2352   // queried by abstract attributes during their initialization or update.
2353   // This has to happen before we create attributes.
2354 
2355   for (Instruction &I : instructions(&F)) {
2356     bool IsInterestingOpcode = false;
2357 
2358     // To allow easy access to all instructions in a function with a given
2359     // opcode we store them in the InfoCache. As not all opcodes are interesting
2360     // to concrete attributes we only cache the ones that are as identified in
2361     // the following switch.
2362     // Note: There are no concrete attributes now so this is initially empty.
2363     switch (I.getOpcode()) {
2364     default:
2365       assert(!isa<CallBase>(&I) &&
2366              "New call base instruction type needs to be known in the "
2367              "Attributor.");
2368       break;
2369     case Instruction::Call:
2370       // Calls are interesting on their own, additionally:
2371       // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
2372       // For `must-tail` calls we remember the caller and callee.
2373       if (auto *Assume = dyn_cast<AssumeInst>(&I)) {
2374         fillMapFromAssume(*Assume, KnowledgeMap);
2375       } else if (cast<CallInst>(I).isMustTailCall()) {
2376         FI.ContainsMustTailCall = true;
2377         if (const Function *Callee = cast<CallInst>(I).getCalledFunction())
2378           getFunctionInfo(*Callee).CalledViaMustTail = true;
2379       }
2380       LLVM_FALLTHROUGH;
2381     case Instruction::CallBr:
2382     case Instruction::Invoke:
2383     case Instruction::CleanupRet:
2384     case Instruction::CatchSwitch:
2385     case Instruction::AtomicRMW:
2386     case Instruction::AtomicCmpXchg:
2387     case Instruction::Br:
2388     case Instruction::Resume:
2389     case Instruction::Ret:
2390     case Instruction::Load:
2391       // The alignment of a pointer is interesting for loads.
2392     case Instruction::Store:
2393       // The alignment of a pointer is interesting for stores.
2394     case Instruction::Alloca:
2395     case Instruction::AddrSpaceCast:
2396       IsInterestingOpcode = true;
2397     }
2398     if (IsInterestingOpcode) {
2399       auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
2400       if (!Insts)
2401         Insts = new (Allocator) InstructionVectorTy();
2402       Insts->push_back(&I);
2403     }
2404     if (I.mayReadOrWriteMemory())
2405       FI.RWInsts.push_back(&I);
2406   }
2407 
2408   if (F.hasFnAttribute(Attribute::AlwaysInline) &&
2409       isInlineViable(F).isSuccess())
2410     InlineableFunctions.insert(&F);
2411 }
2412 
2413 AAResults *InformationCache::getAAResultsForFunction(const Function &F) {
2414   return AG.getAnalysis<AAManager>(F);
2415 }
2416 
2417 InformationCache::FunctionInfo::~FunctionInfo() {
2418   // The instruction vectors are allocated using a BumpPtrAllocator, we need to
2419   // manually destroy them.
2420   for (auto &It : OpcodeInstMap)
2421     It.getSecond()->~InstructionVectorTy();
2422 }
2423 
2424 void Attributor::recordDependence(const AbstractAttribute &FromAA,
2425                                   const AbstractAttribute &ToAA,
2426                                   DepClassTy DepClass) {
2427   if (DepClass == DepClassTy::NONE)
2428     return;
2429   // If we are outside of an update, thus before the actual fixpoint iteration
2430   // started (= when we create AAs), we do not track dependences because we will
2431   // put all AAs into the initial worklist anyway.
2432   if (DependenceStack.empty())
2433     return;
2434   if (FromAA.getState().isAtFixpoint())
2435     return;
2436   DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
2437 }
2438 
2439 void Attributor::rememberDependences() {
2440   assert(!DependenceStack.empty() && "No dependences to remember!");
2441 
2442   for (DepInfo &DI : *DependenceStack.back()) {
2443     assert((DI.DepClass == DepClassTy::REQUIRED ||
2444             DI.DepClass == DepClassTy::OPTIONAL) &&
2445            "Expected required or optional dependence (1 bit)!");
2446     auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
2447     DepAAs.push_back(AbstractAttribute::DepTy(
2448         const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
2449   }
2450 }
2451 
2452 void Attributor::identifyDefaultAbstractAttributes(Function &F) {
2453   if (!VisitedFunctions.insert(&F).second)
2454     return;
2455   if (F.isDeclaration())
2456     return;
2457 
2458   // In non-module runs we need to look at the call sites of a function to
2459   // determine if it is part of a must-tail call edge. This will influence what
2460   // attributes we can derive.
2461   InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
2462   if (!isModulePass() && !FI.CalledViaMustTail) {
2463     for (const Use &U : F.uses())
2464       if (const auto *CB = dyn_cast<CallBase>(U.getUser()))
2465         if (CB->isCallee(&U) && CB->isMustTailCall())
2466           FI.CalledViaMustTail = true;
2467   }
2468 
2469   IRPosition FPos = IRPosition::function(F);
2470 
2471   // Check for dead BasicBlocks in every function.
2472   // We need dead instruction detection because we do not want to deal with
2473   // broken IR in which SSA rules do not apply.
2474   getOrCreateAAFor<AAIsDead>(FPos);
2475 
2476   // Every function might be "will-return".
2477   getOrCreateAAFor<AAWillReturn>(FPos);
2478 
2479   // Every function might contain instructions that cause "undefined behavior".
2480   getOrCreateAAFor<AAUndefinedBehavior>(FPos);
2481 
2482   // Every function can be nounwind.
2483   getOrCreateAAFor<AANoUnwind>(FPos);
2484 
2485   // Every function might be marked "nosync"
2486   getOrCreateAAFor<AANoSync>(FPos);
2487 
2488   // Every function might be "no-free".
2489   getOrCreateAAFor<AANoFree>(FPos);
2490 
2491   // Every function might be "no-return".
2492   getOrCreateAAFor<AANoReturn>(FPos);
2493 
2494   // Every function might be "no-recurse".
2495   getOrCreateAAFor<AANoRecurse>(FPos);
2496 
2497   // Every function might be "readnone/readonly/writeonly/...".
2498   getOrCreateAAFor<AAMemoryBehavior>(FPos);
2499 
2500   // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
2501   getOrCreateAAFor<AAMemoryLocation>(FPos);
2502 
2503   // Every function can track active assumptions.
2504   getOrCreateAAFor<AAAssumptionInfo>(FPos);
2505 
2506   // Every function might be applicable for Heap-To-Stack conversion.
2507   if (EnableHeapToStack)
2508     getOrCreateAAFor<AAHeapToStack>(FPos);
2509 
2510   // Return attributes are only appropriate if the return type is non void.
2511   Type *ReturnType = F.getReturnType();
2512   if (!ReturnType->isVoidTy()) {
2513     // Argument attribute "returned" --- Create only one per function even
2514     // though it is an argument attribute.
2515     getOrCreateAAFor<AAReturnedValues>(FPos);
2516 
2517     IRPosition RetPos = IRPosition::returned(F);
2518 
2519     // Every returned value might be dead.
2520     getOrCreateAAFor<AAIsDead>(RetPos);
2521 
2522     // Every function might be simplified.
2523     getOrCreateAAFor<AAValueSimplify>(RetPos);
2524 
2525     // Every returned value might be marked noundef.
2526     getOrCreateAAFor<AANoUndef>(RetPos);
2527 
2528     if (ReturnType->isPointerTy()) {
2529 
2530       // Every function with pointer return type might be marked align.
2531       getOrCreateAAFor<AAAlign>(RetPos);
2532 
2533       // Every function with pointer return type might be marked nonnull.
2534       getOrCreateAAFor<AANonNull>(RetPos);
2535 
2536       // Every function with pointer return type might be marked noalias.
2537       getOrCreateAAFor<AANoAlias>(RetPos);
2538 
2539       // Every function with pointer return type might be marked
2540       // dereferenceable.
2541       getOrCreateAAFor<AADereferenceable>(RetPos);
2542     }
2543   }
2544 
2545   for (Argument &Arg : F.args()) {
2546     IRPosition ArgPos = IRPosition::argument(Arg);
2547 
2548     // Every argument might be simplified. We have to go through the Attributor
2549     // interface though as outside AAs can register custom simplification
2550     // callbacks.
2551     bool UsedAssumedInformation = false;
2552     getAssumedSimplified(ArgPos, /* AA */ nullptr, UsedAssumedInformation);
2553 
2554     // Every argument might be dead.
2555     getOrCreateAAFor<AAIsDead>(ArgPos);
2556 
2557     // Every argument might be marked noundef.
2558     getOrCreateAAFor<AANoUndef>(ArgPos);
2559 
2560     if (Arg.getType()->isPointerTy()) {
2561       // Every argument with pointer type might be marked nonnull.
2562       getOrCreateAAFor<AANonNull>(ArgPos);
2563 
2564       // Every argument with pointer type might be marked noalias.
2565       getOrCreateAAFor<AANoAlias>(ArgPos);
2566 
2567       // Every argument with pointer type might be marked dereferenceable.
2568       getOrCreateAAFor<AADereferenceable>(ArgPos);
2569 
2570       // Every argument with pointer type might be marked align.
2571       getOrCreateAAFor<AAAlign>(ArgPos);
2572 
2573       // Every argument with pointer type might be marked nocapture.
2574       getOrCreateAAFor<AANoCapture>(ArgPos);
2575 
2576       // Every argument with pointer type might be marked
2577       // "readnone/readonly/writeonly/..."
2578       getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
2579 
2580       // Every argument with pointer type might be marked nofree.
2581       getOrCreateAAFor<AANoFree>(ArgPos);
2582 
2583       // Every argument with pointer type might be privatizable (or promotable)
2584       getOrCreateAAFor<AAPrivatizablePtr>(ArgPos);
2585     }
2586   }
2587 
2588   auto CallSitePred = [&](Instruction &I) -> bool {
2589     auto &CB = cast<CallBase>(I);
2590     IRPosition CBRetPos = IRPosition::callsite_returned(CB);
2591     IRPosition CBFnPos = IRPosition::callsite_function(CB);
2592 
2593     // Call sites might be dead if they do not have side effects and no live
2594     // users. The return value might be dead if there are no live users.
2595     getOrCreateAAFor<AAIsDead>(CBRetPos);
2596 
2597     Function *Callee = CB.getCalledFunction();
2598     // TODO: Even if the callee is not known now we might be able to simplify
2599     //       the call/callee.
2600     if (!Callee)
2601       return true;
2602 
2603     // Every call site can track active assumptions.
2604     getOrCreateAAFor<AAAssumptionInfo>(CBFnPos);
2605 
2606     // Skip declarations except if annotations on their call sites were
2607     // explicitly requested.
2608     if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
2609         !Callee->hasMetadata(LLVMContext::MD_callback))
2610       return true;
2611 
2612     if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
2613 
2614       IRPosition CBRetPos = IRPosition::callsite_returned(CB);
2615       getOrCreateAAFor<AAValueSimplify>(CBRetPos);
2616     }
2617 
2618     for (int I = 0, E = CB.arg_size(); I < E; ++I) {
2619 
2620       IRPosition CBArgPos = IRPosition::callsite_argument(CB, I);
2621 
2622       // Every call site argument might be dead.
2623       getOrCreateAAFor<AAIsDead>(CBArgPos);
2624 
2625       // Call site argument might be simplified. We have to go through the
2626       // Attributor interface though as outside AAs can register custom
2627       // simplification callbacks.
2628       bool UsedAssumedInformation = false;
2629       getAssumedSimplified(CBArgPos, /* AA */ nullptr, UsedAssumedInformation);
2630 
2631       // Every call site argument might be marked "noundef".
2632       getOrCreateAAFor<AANoUndef>(CBArgPos);
2633 
2634       if (!CB.getArgOperand(I)->getType()->isPointerTy())
2635         continue;
2636 
2637       // Call site argument attribute "non-null".
2638       getOrCreateAAFor<AANonNull>(CBArgPos);
2639 
2640       // Call site argument attribute "nocapture".
2641       getOrCreateAAFor<AANoCapture>(CBArgPos);
2642 
2643       // Call site argument attribute "no-alias".
2644       getOrCreateAAFor<AANoAlias>(CBArgPos);
2645 
2646       // Call site argument attribute "dereferenceable".
2647       getOrCreateAAFor<AADereferenceable>(CBArgPos);
2648 
2649       // Call site argument attribute "align".
2650       getOrCreateAAFor<AAAlign>(CBArgPos);
2651 
2652       // Call site argument attribute
2653       // "readnone/readonly/writeonly/..."
2654       getOrCreateAAFor<AAMemoryBehavior>(CBArgPos);
2655 
2656       // Call site argument attribute "nofree".
2657       getOrCreateAAFor<AANoFree>(CBArgPos);
2658     }
2659     return true;
2660   };
2661 
2662   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
2663   bool Success;
2664   bool UsedAssumedInformation = false;
2665   Success = checkForAllInstructionsImpl(
2666       nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr,
2667       {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
2668        (unsigned)Instruction::Call},
2669       UsedAssumedInformation);
2670   (void)Success;
2671   assert(Success && "Expected the check call to be successful!");
2672 
2673   auto LoadStorePred = [&](Instruction &I) -> bool {
2674     if (isa<LoadInst>(I)) {
2675       getOrCreateAAFor<AAAlign>(
2676           IRPosition::value(*cast<LoadInst>(I).getPointerOperand()));
2677       if (SimplifyAllLoads)
2678         getOrCreateAAFor<AAValueSimplify>(IRPosition::value(I));
2679     } else
2680       getOrCreateAAFor<AAAlign>(
2681           IRPosition::value(*cast<StoreInst>(I).getPointerOperand()));
2682     return true;
2683   };
2684   Success = checkForAllInstructionsImpl(
2685       nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr,
2686       {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
2687       UsedAssumedInformation);
2688   (void)Success;
2689   assert(Success && "Expected the check call to be successful!");
2690 }
2691 
2692 /// Helpers to ease debugging through output streams and print calls.
2693 ///
2694 ///{
2695 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
2696   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
2697 }
2698 
2699 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
2700   switch (AP) {
2701   case IRPosition::IRP_INVALID:
2702     return OS << "inv";
2703   case IRPosition::IRP_FLOAT:
2704     return OS << "flt";
2705   case IRPosition::IRP_RETURNED:
2706     return OS << "fn_ret";
2707   case IRPosition::IRP_CALL_SITE_RETURNED:
2708     return OS << "cs_ret";
2709   case IRPosition::IRP_FUNCTION:
2710     return OS << "fn";
2711   case IRPosition::IRP_CALL_SITE:
2712     return OS << "cs";
2713   case IRPosition::IRP_ARGUMENT:
2714     return OS << "arg";
2715   case IRPosition::IRP_CALL_SITE_ARGUMENT:
2716     return OS << "cs_arg";
2717   }
2718   llvm_unreachable("Unknown attribute position!");
2719 }
2720 
2721 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
2722   const Value &AV = Pos.getAssociatedValue();
2723   OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
2724      << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
2725 
2726   if (Pos.hasCallBaseContext())
2727     OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
2728   return OS << "}";
2729 }
2730 
2731 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
2732   OS << "range-state(" << S.getBitWidth() << ")<";
2733   S.getKnown().print(OS);
2734   OS << " / ";
2735   S.getAssumed().print(OS);
2736   OS << ">";
2737 
2738   return OS << static_cast<const AbstractState &>(S);
2739 }
2740 
2741 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
2742   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
2743 }
2744 
2745 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
2746   AA.print(OS);
2747   return OS;
2748 }
2749 
2750 raw_ostream &llvm::operator<<(raw_ostream &OS,
2751                               const PotentialConstantIntValuesState &S) {
2752   OS << "set-state(< {";
2753   if (!S.isValidState())
2754     OS << "full-set";
2755   else {
2756     for (auto &it : S.getAssumedSet())
2757       OS << it << ", ";
2758     if (S.undefIsContained())
2759       OS << "undef ";
2760   }
2761   OS << "} >)";
2762 
2763   return OS;
2764 }
2765 
2766 void AbstractAttribute::print(raw_ostream &OS) const {
2767   OS << "[";
2768   OS << getName();
2769   OS << "] for CtxI ";
2770 
2771   if (auto *I = getCtxI()) {
2772     OS << "'";
2773     I->print(OS);
2774     OS << "'";
2775   } else
2776     OS << "<<null inst>>";
2777 
2778   OS << " at position " << getIRPosition() << " with state " << getAsStr()
2779      << '\n';
2780 }
2781 
2782 void AbstractAttribute::printWithDeps(raw_ostream &OS) const {
2783   print(OS);
2784 
2785   for (const auto &DepAA : Deps) {
2786     auto *AA = DepAA.getPointer();
2787     OS << "  updates ";
2788     AA->print(OS);
2789   }
2790 
2791   OS << '\n';
2792 }
2793 
2794 raw_ostream &llvm::operator<<(raw_ostream &OS,
2795                               const AAPointerInfo::Access &Acc) {
2796   OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst();
2797   if (Acc.getLocalInst() != Acc.getRemoteInst())
2798     OS << " via " << *Acc.getLocalInst();
2799   if (Acc.getContent().hasValue())
2800     OS << " [" << *Acc.getContent() << "]";
2801   return OS;
2802 }
2803 ///}
2804 
2805 /// ----------------------------------------------------------------------------
2806 ///                       Pass (Manager) Boilerplate
2807 /// ----------------------------------------------------------------------------
2808 
2809 static bool runAttributorOnFunctions(InformationCache &InfoCache,
2810                                      SetVector<Function *> &Functions,
2811                                      AnalysisGetter &AG,
2812                                      CallGraphUpdater &CGUpdater,
2813                                      bool DeleteFns) {
2814   if (Functions.empty())
2815     return false;
2816 
2817   LLVM_DEBUG({
2818     dbgs() << "[Attributor] Run on module with " << Functions.size()
2819            << " functions:\n";
2820     for (Function *Fn : Functions)
2821       dbgs() << "  - " << Fn->getName() << "\n";
2822   });
2823 
2824   // Create an Attributor and initially empty information cache that is filled
2825   // while we identify default attribute opportunities.
2826   Attributor A(Functions, InfoCache, CGUpdater, /* Allowed */ nullptr,
2827                DeleteFns);
2828 
2829   // Create shallow wrappers for all functions that are not IPO amendable
2830   if (AllowShallowWrappers)
2831     for (Function *F : Functions)
2832       if (!A.isFunctionIPOAmendable(*F))
2833         Attributor::createShallowWrapper(*F);
2834 
2835   // Internalize non-exact functions
2836   // TODO: for now we eagerly internalize functions without calculating the
2837   //       cost, we need a cost interface to determine whether internalizing
2838   //       a function is "benefitial"
2839   if (AllowDeepWrapper) {
2840     unsigned FunSize = Functions.size();
2841     for (unsigned u = 0; u < FunSize; u++) {
2842       Function *F = Functions[u];
2843       if (!F->isDeclaration() && !F->isDefinitionExact() && F->getNumUses() &&
2844           !GlobalValue::isInterposableLinkage(F->getLinkage())) {
2845         Function *NewF = Attributor::internalizeFunction(*F);
2846         assert(NewF && "Could not internalize function.");
2847         Functions.insert(NewF);
2848 
2849         // Update call graph
2850         CGUpdater.replaceFunctionWith(*F, *NewF);
2851         for (const Use &U : NewF->uses())
2852           if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) {
2853             auto *CallerF = CB->getCaller();
2854             CGUpdater.reanalyzeFunction(*CallerF);
2855           }
2856       }
2857     }
2858   }
2859 
2860   for (Function *F : Functions) {
2861     if (F->hasExactDefinition())
2862       NumFnWithExactDefinition++;
2863     else
2864       NumFnWithoutExactDefinition++;
2865 
2866     // We look at internal functions only on-demand but if any use is not a
2867     // direct call or outside the current set of analyzed functions, we have
2868     // to do it eagerly.
2869     if (F->hasLocalLinkage()) {
2870       if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
2871             const auto *CB = dyn_cast<CallBase>(U.getUser());
2872             return CB && CB->isCallee(&U) &&
2873                    Functions.count(const_cast<Function *>(CB->getCaller()));
2874           }))
2875         continue;
2876     }
2877 
2878     // Populate the Attributor with abstract attribute opportunities in the
2879     // function and the information cache with IR information.
2880     A.identifyDefaultAbstractAttributes(*F);
2881   }
2882 
2883   ChangeStatus Changed = A.run();
2884 
2885   LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
2886                     << " functions, result: " << Changed << ".\n");
2887   return Changed == ChangeStatus::CHANGED;
2888 }
2889 
2890 void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); }
2891 
2892 void AADepGraph::dumpGraph() {
2893   static std::atomic<int> CallTimes;
2894   std::string Prefix;
2895 
2896   if (!DepGraphDotFileNamePrefix.empty())
2897     Prefix = DepGraphDotFileNamePrefix;
2898   else
2899     Prefix = "dep_graph";
2900   std::string Filename =
2901       Prefix + "_" + std::to_string(CallTimes.load()) + ".dot";
2902 
2903   outs() << "Dependency graph dump to " << Filename << ".\n";
2904 
2905   std::error_code EC;
2906 
2907   raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
2908   if (!EC)
2909     llvm::WriteGraph(File, this);
2910 
2911   CallTimes++;
2912 }
2913 
2914 void AADepGraph::print() {
2915   for (auto DepAA : SyntheticRoot.Deps)
2916     cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs());
2917 }
2918 
2919 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
2920   FunctionAnalysisManager &FAM =
2921       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2922   AnalysisGetter AG(FAM);
2923 
2924   SetVector<Function *> Functions;
2925   for (Function &F : M)
2926     Functions.insert(&F);
2927 
2928   CallGraphUpdater CGUpdater;
2929   BumpPtrAllocator Allocator;
2930   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
2931   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
2932                                /* DeleteFns */ true)) {
2933     // FIXME: Think about passes we will preserve and add them here.
2934     return PreservedAnalyses::none();
2935   }
2936   return PreservedAnalyses::all();
2937 }
2938 
2939 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
2940                                            CGSCCAnalysisManager &AM,
2941                                            LazyCallGraph &CG,
2942                                            CGSCCUpdateResult &UR) {
2943   FunctionAnalysisManager &FAM =
2944       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2945   AnalysisGetter AG(FAM);
2946 
2947   SetVector<Function *> Functions;
2948   for (LazyCallGraph::Node &N : C)
2949     Functions.insert(&N.getFunction());
2950 
2951   if (Functions.empty())
2952     return PreservedAnalyses::all();
2953 
2954   Module &M = *Functions.back()->getParent();
2955   CallGraphUpdater CGUpdater;
2956   CGUpdater.initialize(CG, C, AM, UR);
2957   BumpPtrAllocator Allocator;
2958   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
2959   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
2960                                /* DeleteFns */ false)) {
2961     // FIXME: Think about passes we will preserve and add them here.
2962     PreservedAnalyses PA;
2963     PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
2964     return PA;
2965   }
2966   return PreservedAnalyses::all();
2967 }
2968 
2969 namespace llvm {
2970 
2971 template <> struct GraphTraits<AADepGraphNode *> {
2972   using NodeRef = AADepGraphNode *;
2973   using DepTy = PointerIntPair<AADepGraphNode *, 1>;
2974   using EdgeRef = PointerIntPair<AADepGraphNode *, 1>;
2975 
2976   static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; }
2977   static NodeRef DepGetVal(DepTy &DT) { return DT.getPointer(); }
2978 
2979   using ChildIteratorType =
2980       mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
2981   using ChildEdgeIteratorType = TinyPtrVector<DepTy>::iterator;
2982 
2983   static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); }
2984 
2985   static ChildIteratorType child_end(NodeRef N) { return N->child_end(); }
2986 };
2987 
2988 template <>
2989 struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> {
2990   static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
2991 
2992   using nodes_iterator =
2993       mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
2994 
2995   static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
2996 
2997   static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
2998 };
2999 
3000 template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
3001   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3002 
3003   static std::string getNodeLabel(const AADepGraphNode *Node,
3004                                   const AADepGraph *DG) {
3005     std::string AAString;
3006     raw_string_ostream O(AAString);
3007     Node->print(O);
3008     return AAString;
3009   }
3010 };
3011 
3012 } // end namespace llvm
3013 
3014 namespace {
3015 
3016 struct AttributorLegacyPass : public ModulePass {
3017   static char ID;
3018 
3019   AttributorLegacyPass() : ModulePass(ID) {
3020     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
3021   }
3022 
3023   bool runOnModule(Module &M) override {
3024     if (skipModule(M))
3025       return false;
3026 
3027     AnalysisGetter AG;
3028     SetVector<Function *> Functions;
3029     for (Function &F : M)
3030       Functions.insert(&F);
3031 
3032     CallGraphUpdater CGUpdater;
3033     BumpPtrAllocator Allocator;
3034     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
3035     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
3036                                     /* DeleteFns*/ true);
3037   }
3038 
3039   void getAnalysisUsage(AnalysisUsage &AU) const override {
3040     // FIXME: Think about passes we will preserve and add them here.
3041     AU.addRequired<TargetLibraryInfoWrapperPass>();
3042   }
3043 };
3044 
3045 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass {
3046   static char ID;
3047 
3048   AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) {
3049     initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
3050   }
3051 
3052   bool runOnSCC(CallGraphSCC &SCC) override {
3053     if (skipSCC(SCC))
3054       return false;
3055 
3056     SetVector<Function *> Functions;
3057     for (CallGraphNode *CGN : SCC)
3058       if (Function *Fn = CGN->getFunction())
3059         if (!Fn->isDeclaration())
3060           Functions.insert(Fn);
3061 
3062     if (Functions.empty())
3063       return false;
3064 
3065     AnalysisGetter AG;
3066     CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph());
3067     CallGraphUpdater CGUpdater;
3068     CGUpdater.initialize(CG, SCC);
3069     Module &M = *Functions.back()->getParent();
3070     BumpPtrAllocator Allocator;
3071     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
3072     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
3073                                     /* DeleteFns */ false);
3074   }
3075 
3076   void getAnalysisUsage(AnalysisUsage &AU) const override {
3077     // FIXME: Think about passes we will preserve and add them here.
3078     AU.addRequired<TargetLibraryInfoWrapperPass>();
3079     CallGraphSCCPass::getAnalysisUsage(AU);
3080   }
3081 };
3082 
3083 } // end anonymous namespace
3084 
3085 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
3086 Pass *llvm::createAttributorCGSCCLegacyPass() {
3087   return new AttributorCGSCCLegacyPass();
3088 }
3089 
3090 char AttributorLegacyPass::ID = 0;
3091 char AttributorCGSCCLegacyPass::ID = 0;
3092 
3093 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
3094                       "Deduce and propagate attributes", false, false)
3095 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3096 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
3097                     "Deduce and propagate attributes", false, false)
3098 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc",
3099                       "Deduce and propagate attributes (CGSCC pass)", false,
3100                       false)
3101 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3102 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
3103 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc",
3104                     "Deduce and propagate attributes (CGSCC pass)", false,
3105                     false)
3106