xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/IPO/Attributor.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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/Statistic.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/Analysis/MustExecute.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/NoFolder.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 
31 #include <cassert>
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "attributor"
36 
37 STATISTIC(NumFnDeleted, "Number of function deleted");
38 STATISTIC(NumFnWithExactDefinition,
39           "Number of functions with exact definitions");
40 STATISTIC(NumFnWithoutExactDefinition,
41           "Number of functions without exact definitions");
42 STATISTIC(NumFnShallowWrapperCreated, "Number of shallow wrappers created");
43 STATISTIC(NumAttributesTimedOut,
44           "Number of abstract attributes timed out before fixpoint");
45 STATISTIC(NumAttributesValidFixpoint,
46           "Number of abstract attributes in a valid fixpoint state");
47 STATISTIC(NumAttributesManifested,
48           "Number of abstract attributes manifested in IR");
49 STATISTIC(NumAttributesFixedDueToRequiredDependences,
50           "Number of abstract attributes fixed due to required dependences");
51 
52 // TODO: Determine a good default value.
53 //
54 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
55 // (when run with the first 5 abstract attributes). The results also indicate
56 // that we never reach 32 iterations but always find a fixpoint sooner.
57 //
58 // This will become more evolved once we perform two interleaved fixpoint
59 // iterations: bottom-up and top-down.
60 static cl::opt<unsigned>
61     MaxFixpointIterations("attributor-max-iterations", cl::Hidden,
62                           cl::desc("Maximal number of fixpoint iterations."),
63                           cl::init(32));
64 static cl::opt<bool> VerifyMaxFixpointIterations(
65     "attributor-max-iterations-verify", cl::Hidden,
66     cl::desc("Verify that max-iterations is a tight bound for a fixpoint"),
67     cl::init(false));
68 
69 static cl::opt<bool> AnnotateDeclarationCallSites(
70     "attributor-annotate-decl-cs", cl::Hidden,
71     cl::desc("Annotate call sites of function declarations."), cl::init(false));
72 
73 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
74                                        cl::init(true), cl::Hidden);
75 
76 static cl::opt<bool>
77     AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
78                          cl::desc("Allow the Attributor to create shallow "
79                                   "wrappers for non-exact definitions."),
80                          cl::init(false));
81 
82 static cl::list<std::string>
83     SeedAllowList("attributor-seed-allow-list", cl::Hidden,
84                   cl::desc("Comma seperated list of attrbute names that are "
85                            "allowed to be seeded."),
86                   cl::ZeroOrMore, cl::CommaSeparated);
87 
88 /// Logic operators for the change status enum class.
89 ///
90 ///{
91 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) {
92   return l == ChangeStatus::CHANGED ? l : r;
93 }
94 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) {
95   return l == ChangeStatus::UNCHANGED ? l : r;
96 }
97 ///}
98 
99 /// Return true if \p New is equal or worse than \p Old.
100 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
101   if (!Old.isIntAttribute())
102     return true;
103 
104   return Old.getValueAsInt() >= New.getValueAsInt();
105 }
106 
107 /// Return true if the information provided by \p Attr was added to the
108 /// attribute list \p Attrs. This is only the case if it was not already present
109 /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
110 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
111                              AttributeList &Attrs, int AttrIdx) {
112 
113   if (Attr.isEnumAttribute()) {
114     Attribute::AttrKind Kind = Attr.getKindAsEnum();
115     if (Attrs.hasAttribute(AttrIdx, Kind))
116       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
117         return false;
118     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
119     return true;
120   }
121   if (Attr.isStringAttribute()) {
122     StringRef Kind = Attr.getKindAsString();
123     if (Attrs.hasAttribute(AttrIdx, Kind))
124       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
125         return false;
126     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
127     return true;
128   }
129   if (Attr.isIntAttribute()) {
130     Attribute::AttrKind Kind = Attr.getKindAsEnum();
131     if (Attrs.hasAttribute(AttrIdx, Kind))
132       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
133         return false;
134     Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind);
135     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
136     return true;
137   }
138 
139   llvm_unreachable("Expected enum or string attribute!");
140 }
141 
142 Argument *IRPosition::getAssociatedArgument() const {
143   if (getPositionKind() == IRP_ARGUMENT)
144     return cast<Argument>(&getAnchorValue());
145 
146   // Not an Argument and no argument number means this is not a call site
147   // argument, thus we cannot find a callback argument to return.
148   int ArgNo = getArgNo();
149   if (ArgNo < 0)
150     return nullptr;
151 
152   // Use abstract call sites to make the connection between the call site
153   // values and the ones in callbacks. If a callback was found that makes use
154   // of the underlying call site operand, we want the corresponding callback
155   // callee argument and not the direct callee argument.
156   Optional<Argument *> CBCandidateArg;
157   SmallVector<const Use *, 4> CallbackUses;
158   const auto &CB = cast<CallBase>(getAnchorValue());
159   AbstractCallSite::getCallbackUses(CB, CallbackUses);
160   for (const Use *U : CallbackUses) {
161     AbstractCallSite ACS(U);
162     assert(ACS && ACS.isCallbackCall());
163     if (!ACS.getCalledFunction())
164       continue;
165 
166     for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
167 
168       // Test if the underlying call site operand is argument number u of the
169       // callback callee.
170       if (ACS.getCallArgOperandNo(u) != ArgNo)
171         continue;
172 
173       assert(ACS.getCalledFunction()->arg_size() > u &&
174              "ACS mapped into var-args arguments!");
175       if (CBCandidateArg.hasValue()) {
176         CBCandidateArg = nullptr;
177         break;
178       }
179       CBCandidateArg = ACS.getCalledFunction()->getArg(u);
180     }
181   }
182 
183   // If we found a unique callback candidate argument, return it.
184   if (CBCandidateArg.hasValue() && CBCandidateArg.getValue())
185     return CBCandidateArg.getValue();
186 
187   // If no callbacks were found, or none used the underlying call site operand
188   // exclusively, use the direct callee argument if available.
189   const Function *Callee = CB.getCalledFunction();
190   if (Callee && Callee->arg_size() > unsigned(ArgNo))
191     return Callee->getArg(ArgNo);
192 
193   return nullptr;
194 }
195 
196 ChangeStatus AbstractAttribute::update(Attributor &A) {
197   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
198   if (getState().isAtFixpoint())
199     return HasChanged;
200 
201   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
202 
203   HasChanged = updateImpl(A);
204 
205   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
206                     << "\n");
207 
208   return HasChanged;
209 }
210 
211 ChangeStatus
212 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP,
213                                    const ArrayRef<Attribute> &DeducedAttrs) {
214   Function *ScopeFn = IRP.getAnchorScope();
215   IRPosition::Kind PK = IRP.getPositionKind();
216 
217   // In the following some generic code that will manifest attributes in
218   // DeducedAttrs if they improve the current IR. Due to the different
219   // annotation positions we use the underlying AttributeList interface.
220 
221   AttributeList Attrs;
222   switch (PK) {
223   case IRPosition::IRP_INVALID:
224   case IRPosition::IRP_FLOAT:
225     return ChangeStatus::UNCHANGED;
226   case IRPosition::IRP_ARGUMENT:
227   case IRPosition::IRP_FUNCTION:
228   case IRPosition::IRP_RETURNED:
229     Attrs = ScopeFn->getAttributes();
230     break;
231   case IRPosition::IRP_CALL_SITE:
232   case IRPosition::IRP_CALL_SITE_RETURNED:
233   case IRPosition::IRP_CALL_SITE_ARGUMENT:
234     Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes();
235     break;
236   }
237 
238   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
239   LLVMContext &Ctx = IRP.getAnchorValue().getContext();
240   for (const Attribute &Attr : DeducedAttrs) {
241     if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx()))
242       continue;
243 
244     HasChanged = ChangeStatus::CHANGED;
245   }
246 
247   if (HasChanged == ChangeStatus::UNCHANGED)
248     return HasChanged;
249 
250   switch (PK) {
251   case IRPosition::IRP_ARGUMENT:
252   case IRPosition::IRP_FUNCTION:
253   case IRPosition::IRP_RETURNED:
254     ScopeFn->setAttributes(Attrs);
255     break;
256   case IRPosition::IRP_CALL_SITE:
257   case IRPosition::IRP_CALL_SITE_RETURNED:
258   case IRPosition::IRP_CALL_SITE_ARGUMENT:
259     cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs);
260     break;
261   case IRPosition::IRP_INVALID:
262   case IRPosition::IRP_FLOAT:
263     break;
264   }
265 
266   return HasChanged;
267 }
268 
269 const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey());
270 const IRPosition
271     IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey());
272 
273 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
274   IRPositions.emplace_back(IRP);
275 
276   const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue());
277   switch (IRP.getPositionKind()) {
278   case IRPosition::IRP_INVALID:
279   case IRPosition::IRP_FLOAT:
280   case IRPosition::IRP_FUNCTION:
281     return;
282   case IRPosition::IRP_ARGUMENT:
283   case IRPosition::IRP_RETURNED:
284     IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope()));
285     return;
286   case IRPosition::IRP_CALL_SITE:
287     assert(CB && "Expected call site!");
288     // TODO: We need to look at the operand bundles similar to the redirection
289     //       in CallBase.
290     if (!CB->hasOperandBundles())
291       if (const Function *Callee = CB->getCalledFunction())
292         IRPositions.emplace_back(IRPosition::function(*Callee));
293     return;
294   case IRPosition::IRP_CALL_SITE_RETURNED:
295     assert(CB && "Expected call site!");
296     // TODO: We need to look at the operand bundles similar to the redirection
297     //       in CallBase.
298     if (!CB->hasOperandBundles()) {
299       if (const Function *Callee = CB->getCalledFunction()) {
300         IRPositions.emplace_back(IRPosition::returned(*Callee));
301         IRPositions.emplace_back(IRPosition::function(*Callee));
302         for (const Argument &Arg : Callee->args())
303           if (Arg.hasReturnedAttr()) {
304             IRPositions.emplace_back(
305                 IRPosition::callsite_argument(*CB, Arg.getArgNo()));
306             IRPositions.emplace_back(
307                 IRPosition::value(*CB->getArgOperand(Arg.getArgNo())));
308             IRPositions.emplace_back(IRPosition::argument(Arg));
309           }
310       }
311     }
312     IRPositions.emplace_back(IRPosition::callsite_function(*CB));
313     return;
314   case IRPosition::IRP_CALL_SITE_ARGUMENT: {
315     int ArgNo = IRP.getArgNo();
316     assert(CB && ArgNo >= 0 && "Expected call site!");
317     // TODO: We need to look at the operand bundles similar to the redirection
318     //       in CallBase.
319     if (!CB->hasOperandBundles()) {
320       const Function *Callee = CB->getCalledFunction();
321       if (Callee && Callee->arg_size() > unsigned(ArgNo))
322         IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo)));
323       if (Callee)
324         IRPositions.emplace_back(IRPosition::function(*Callee));
325     }
326     IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
327     return;
328   }
329   }
330 }
331 
332 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs,
333                          bool IgnoreSubsumingPositions, Attributor *A) const {
334   SmallVector<Attribute, 4> Attrs;
335   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
336     for (Attribute::AttrKind AK : AKs)
337       if (EquivIRP.getAttrsFromIRAttr(AK, Attrs))
338         return true;
339     // The first position returned by the SubsumingPositionIterator is
340     // always the position itself. If we ignore subsuming positions we
341     // are done after the first iteration.
342     if (IgnoreSubsumingPositions)
343       break;
344   }
345   if (A)
346     for (Attribute::AttrKind AK : AKs)
347       if (getAttrsFromAssumes(AK, Attrs, *A))
348         return true;
349   return false;
350 }
351 
352 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
353                           SmallVectorImpl<Attribute> &Attrs,
354                           bool IgnoreSubsumingPositions, Attributor *A) const {
355   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
356     for (Attribute::AttrKind AK : AKs)
357       EquivIRP.getAttrsFromIRAttr(AK, Attrs);
358     // The first position returned by the SubsumingPositionIterator is
359     // always the position itself. If we ignore subsuming positions we
360     // are done after the first iteration.
361     if (IgnoreSubsumingPositions)
362       break;
363   }
364   if (A)
365     for (Attribute::AttrKind AK : AKs)
366       getAttrsFromAssumes(AK, Attrs, *A);
367 }
368 
369 bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK,
370                                     SmallVectorImpl<Attribute> &Attrs) const {
371   if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT)
372     return false;
373 
374   AttributeList AttrList;
375   if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
376     AttrList = CB->getAttributes();
377   else
378     AttrList = getAssociatedFunction()->getAttributes();
379 
380   bool HasAttr = AttrList.hasAttribute(getAttrIdx(), AK);
381   if (HasAttr)
382     Attrs.push_back(AttrList.getAttribute(getAttrIdx(), AK));
383   return HasAttr;
384 }
385 
386 bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK,
387                                      SmallVectorImpl<Attribute> &Attrs,
388                                      Attributor &A) const {
389   assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!");
390   Value &AssociatedValue = getAssociatedValue();
391 
392   const Assume2KnowledgeMap &A2K =
393       A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK});
394 
395   // Check if we found any potential assume use, if not we don't need to create
396   // explorer iterators.
397   if (A2K.empty())
398     return false;
399 
400   LLVMContext &Ctx = AssociatedValue.getContext();
401   unsigned AttrsSize = Attrs.size();
402   MustBeExecutedContextExplorer &Explorer =
403       A.getInfoCache().getMustBeExecutedContextExplorer();
404   auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI());
405   for (auto &It : A2K)
406     if (Explorer.findInContextOf(It.first, EIt, EEnd))
407       Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max));
408   return AttrsSize != Attrs.size();
409 }
410 
411 void IRPosition::verify() {
412 #ifdef EXPENSIVE_CHECKS
413   switch (getPositionKind()) {
414   case IRP_INVALID:
415     assert(!Enc.getOpaqueValue() &&
416            "Expected a nullptr for an invalid position!");
417     return;
418   case IRP_FLOAT:
419     assert((!isa<CallBase>(&getAssociatedValue()) &&
420             !isa<Argument>(&getAssociatedValue())) &&
421            "Expected specialized kind for call base and argument values!");
422     return;
423   case IRP_RETURNED:
424     assert(isa<Function>(getAsValuePtr()) &&
425            "Expected function for a 'returned' position!");
426     assert(getAsValuePtr() == &getAssociatedValue() &&
427            "Associated value mismatch!");
428     return;
429   case IRP_CALL_SITE_RETURNED:
430     assert((isa<CallBase>(getAsValuePtr())) &&
431            "Expected call base for 'call site returned' position!");
432     assert(getAsValuePtr() == &getAssociatedValue() &&
433            "Associated value mismatch!");
434     return;
435   case IRP_CALL_SITE:
436     assert((isa<CallBase>(getAsValuePtr())) &&
437            "Expected call base for 'call site function' position!");
438     assert(getAsValuePtr() == &getAssociatedValue() &&
439            "Associated value mismatch!");
440     return;
441   case IRP_FUNCTION:
442     assert(isa<Function>(getAsValuePtr()) &&
443            "Expected function for a 'function' position!");
444     assert(getAsValuePtr() == &getAssociatedValue() &&
445            "Associated value mismatch!");
446     return;
447   case IRP_ARGUMENT:
448     assert(isa<Argument>(getAsValuePtr()) &&
449            "Expected argument for a 'argument' position!");
450     assert(getAsValuePtr() == &getAssociatedValue() &&
451            "Associated value mismatch!");
452     return;
453   case IRP_CALL_SITE_ARGUMENT: {
454     Use *U = getAsUsePtr();
455     assert(U && "Expected use for a 'call site argument' position!");
456     assert(isa<CallBase>(U->getUser()) &&
457            "Expected call base user for a 'call site argument' position!");
458     assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
459            "Expected call base argument operand for a 'call site argument' "
460            "position");
461     assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
462                unsigned(getArgNo()) &&
463            "Argument number mismatch!");
464     assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
465     return;
466   }
467   }
468 #endif
469 }
470 
471 Optional<Constant *>
472 Attributor::getAssumedConstant(const Value &V, const AbstractAttribute &AA,
473                                bool &UsedAssumedInformation) {
474   const auto &ValueSimplifyAA = getAAFor<AAValueSimplify>(
475       AA, IRPosition::value(V), /* TrackDependence */ false);
476   Optional<Value *> SimplifiedV =
477       ValueSimplifyAA.getAssumedSimplifiedValue(*this);
478   bool IsKnown = ValueSimplifyAA.isKnown();
479   UsedAssumedInformation |= !IsKnown;
480   if (!SimplifiedV.hasValue()) {
481     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
482     return llvm::None;
483   }
484   if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) {
485     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
486     return llvm::None;
487   }
488   Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue());
489   if (CI && CI->getType() != V.getType()) {
490     // TODO: Check for a save conversion.
491     return nullptr;
492   }
493   if (CI)
494     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
495   return CI;
496 }
497 
498 Attributor::~Attributor() {
499   // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
500   // thus we cannot delete them. We can, and want to, destruct them though.
501   for (AbstractAttribute *AA : AllAbstractAttributes)
502     AA->~AbstractAttribute();
503 }
504 
505 bool Attributor::isAssumedDead(const AbstractAttribute &AA,
506                                const AAIsDead *FnLivenessAA,
507                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
508   const IRPosition &IRP = AA.getIRPosition();
509   if (!Functions.count(IRP.getAnchorScope()))
510     return false;
511   return isAssumedDead(IRP, &AA, FnLivenessAA, CheckBBLivenessOnly, DepClass);
512 }
513 
514 bool Attributor::isAssumedDead(const Use &U,
515                                const AbstractAttribute *QueryingAA,
516                                const AAIsDead *FnLivenessAA,
517                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
518   Instruction *UserI = dyn_cast<Instruction>(U.getUser());
519   if (!UserI)
520     return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA,
521                          CheckBBLivenessOnly, DepClass);
522 
523   if (auto *CB = dyn_cast<CallBase>(UserI)) {
524     // For call site argument uses we can check if the argument is
525     // unused/dead.
526     if (CB->isArgOperand(&U)) {
527       const IRPosition &CSArgPos =
528           IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
529       return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA,
530                            CheckBBLivenessOnly, DepClass);
531     }
532   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
533     const IRPosition &RetPos = IRPosition::returned(*RI->getFunction());
534     return isAssumedDead(RetPos, QueryingAA, FnLivenessAA, CheckBBLivenessOnly,
535                          DepClass);
536   } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) {
537     BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
538     return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA,
539                          CheckBBLivenessOnly, DepClass);
540   }
541 
542   return isAssumedDead(IRPosition::value(*UserI), QueryingAA, FnLivenessAA,
543                        CheckBBLivenessOnly, DepClass);
544 }
545 
546 bool Attributor::isAssumedDead(const Instruction &I,
547                                const AbstractAttribute *QueryingAA,
548                                const AAIsDead *FnLivenessAA,
549                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
550   if (!FnLivenessAA)
551     FnLivenessAA = lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction()),
552                                          QueryingAA,
553                                          /* TrackDependence */ false);
554 
555   // If we have a context instruction and a liveness AA we use it.
556   if (FnLivenessAA &&
557       FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() &&
558       FnLivenessAA->isAssumedDead(&I)) {
559     if (QueryingAA)
560       recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
561     return true;
562   }
563 
564   if (CheckBBLivenessOnly)
565     return false;
566 
567   const AAIsDead &IsDeadAA = getOrCreateAAFor<AAIsDead>(
568       IRPosition::value(I), QueryingAA, /* TrackDependence */ false);
569   // Don't check liveness for AAIsDead.
570   if (QueryingAA == &IsDeadAA)
571     return false;
572 
573   if (IsDeadAA.isAssumedDead()) {
574     if (QueryingAA)
575       recordDependence(IsDeadAA, *QueryingAA, DepClass);
576     return true;
577   }
578 
579   return false;
580 }
581 
582 bool Attributor::isAssumedDead(const IRPosition &IRP,
583                                const AbstractAttribute *QueryingAA,
584                                const AAIsDead *FnLivenessAA,
585                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
586   Instruction *CtxI = IRP.getCtxI();
587   if (CtxI &&
588       isAssumedDead(*CtxI, QueryingAA, FnLivenessAA,
589                     /* CheckBBLivenessOnly */ true,
590                     CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
591     return true;
592 
593   if (CheckBBLivenessOnly)
594     return false;
595 
596   // If we haven't succeeded we query the specific liveness info for the IRP.
597   const AAIsDead *IsDeadAA;
598   if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
599     IsDeadAA = &getOrCreateAAFor<AAIsDead>(
600         IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())),
601         QueryingAA, /* TrackDependence */ false);
602   else
603     IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA,
604                                            /* TrackDependence */ false);
605   // Don't check liveness for AAIsDead.
606   if (QueryingAA == IsDeadAA)
607     return false;
608 
609   if (IsDeadAA->isAssumedDead()) {
610     if (QueryingAA)
611       recordDependence(*IsDeadAA, *QueryingAA, DepClass);
612     return true;
613   }
614 
615   return false;
616 }
617 
618 bool Attributor::checkForAllUses(function_ref<bool(const Use &, bool &)> Pred,
619                                  const AbstractAttribute &QueryingAA,
620                                  const Value &V, DepClassTy LivenessDepClass) {
621 
622   // Check the trivial case first as it catches void values.
623   if (V.use_empty())
624     return true;
625 
626   // If the value is replaced by another one, for now a constant, we do not have
627   // uses. Note that this requires users of `checkForAllUses` to not recurse but
628   // instead use the `follow` callback argument to look at transitive users,
629   // however, that should be clear from the presence of the argument.
630   bool UsedAssumedInformation = false;
631   Optional<Constant *> C =
632       getAssumedConstant(V, QueryingAA, UsedAssumedInformation);
633   if (C.hasValue() && C.getValue()) {
634     LLVM_DEBUG(dbgs() << "[Attributor] Value is simplified, uses skipped: " << V
635                       << " -> " << *C.getValue() << "\n");
636     return true;
637   }
638 
639   const IRPosition &IRP = QueryingAA.getIRPosition();
640   SmallVector<const Use *, 16> Worklist;
641   SmallPtrSet<const Use *, 16> Visited;
642 
643   for (const Use &U : V.uses())
644     Worklist.push_back(&U);
645 
646   LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
647                     << " initial uses to check\n");
648 
649   const Function *ScopeFn = IRP.getAnchorScope();
650   const auto *LivenessAA =
651       ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn),
652                                     /* TrackDependence */ false)
653               : nullptr;
654 
655   while (!Worklist.empty()) {
656     const Use *U = Worklist.pop_back_val();
657     if (!Visited.insert(U).second)
658       continue;
659     LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << " in "
660                       << *U->getUser() << "\n");
661     if (isAssumedDead(*U, &QueryingAA, LivenessAA,
662                       /* CheckBBLivenessOnly */ false, LivenessDepClass)) {
663       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
664       continue;
665     }
666     if (U->getUser()->isDroppable()) {
667       LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n");
668       continue;
669     }
670 
671     bool Follow = false;
672     if (!Pred(*U, Follow))
673       return false;
674     if (!Follow)
675       continue;
676     for (const Use &UU : U->getUser()->uses())
677       Worklist.push_back(&UU);
678   }
679 
680   return true;
681 }
682 
683 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
684                                       const AbstractAttribute &QueryingAA,
685                                       bool RequireAllCallSites,
686                                       bool &AllCallSitesKnown) {
687   // We can try to determine information from
688   // the call sites. However, this is only possible all call sites are known,
689   // hence the function has internal linkage.
690   const IRPosition &IRP = QueryingAA.getIRPosition();
691   const Function *AssociatedFunction = IRP.getAssociatedFunction();
692   if (!AssociatedFunction) {
693     LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
694                       << "\n");
695     AllCallSitesKnown = false;
696     return false;
697   }
698 
699   return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
700                               &QueryingAA, AllCallSitesKnown);
701 }
702 
703 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
704                                       const Function &Fn,
705                                       bool RequireAllCallSites,
706                                       const AbstractAttribute *QueryingAA,
707                                       bool &AllCallSitesKnown) {
708   if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
709     LLVM_DEBUG(
710         dbgs()
711         << "[Attributor] Function " << Fn.getName()
712         << " has no internal linkage, hence not all call sites are known\n");
713     AllCallSitesKnown = false;
714     return false;
715   }
716 
717   // If we do not require all call sites we might not see all.
718   AllCallSitesKnown = RequireAllCallSites;
719 
720   SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses()));
721   for (unsigned u = 0; u < Uses.size(); ++u) {
722     const Use &U = *Uses[u];
723     LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << *U << " in "
724                       << *U.getUser() << "\n");
725     if (isAssumedDead(U, QueryingAA, nullptr, /* CheckBBLivenessOnly */ true)) {
726       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
727       continue;
728     }
729     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
730       if (CE->isCast() && CE->getType()->isPointerTy() &&
731           CE->getType()->getPointerElementType()->isFunctionTy()) {
732         for (const Use &CEU : CE->uses())
733           Uses.push_back(&CEU);
734         continue;
735       }
736     }
737 
738     AbstractCallSite ACS(&U);
739     if (!ACS) {
740       LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
741                         << " has non call site use " << *U.get() << " in "
742                         << *U.getUser() << "\n");
743       // BlockAddress users are allowed.
744       if (isa<BlockAddress>(U.getUser()))
745         continue;
746       return false;
747     }
748 
749     const Use *EffectiveUse =
750         ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
751     if (!ACS.isCallee(EffectiveUse)) {
752       if (!RequireAllCallSites)
753         continue;
754       LLVM_DEBUG(dbgs() << "[Attributor] User " << EffectiveUse->getUser()
755                         << " is an invalid use of " << Fn.getName() << "\n");
756       return false;
757     }
758 
759     // Make sure the arguments that can be matched between the call site and the
760     // callee argee on their type. It is unlikely they do not and it doesn't
761     // make sense for all attributes to know/care about this.
762     assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
763     unsigned MinArgsParams =
764         std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size());
765     for (unsigned u = 0; u < MinArgsParams; ++u) {
766       Value *CSArgOp = ACS.getCallArgOperand(u);
767       if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) {
768         LLVM_DEBUG(
769             dbgs() << "[Attributor] Call site / callee argument type mismatch ["
770                    << u << "@" << Fn.getName() << ": "
771                    << *Fn.getArg(u)->getType() << " vs. "
772                    << *ACS.getCallArgOperand(u)->getType() << "\n");
773         return false;
774       }
775     }
776 
777     if (Pred(ACS))
778       continue;
779 
780     LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
781                       << *ACS.getInstruction() << "\n");
782     return false;
783   }
784 
785   return true;
786 }
787 
788 bool Attributor::checkForAllReturnedValuesAndReturnInsts(
789     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred,
790     const AbstractAttribute &QueryingAA) {
791 
792   const IRPosition &IRP = QueryingAA.getIRPosition();
793   // Since we need to provide return instructions we have to have an exact
794   // definition.
795   const Function *AssociatedFunction = IRP.getAssociatedFunction();
796   if (!AssociatedFunction)
797     return false;
798 
799   // If this is a call site query we use the call site specific return values
800   // and liveness information.
801   // TODO: use the function scope once we have call site AAReturnedValues.
802   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
803   const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
804   if (!AARetVal.getState().isValidState())
805     return false;
806 
807   return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
808 }
809 
810 bool Attributor::checkForAllReturnedValues(
811     function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) {
812 
813   const IRPosition &IRP = QueryingAA.getIRPosition();
814   const Function *AssociatedFunction = IRP.getAssociatedFunction();
815   if (!AssociatedFunction)
816     return false;
817 
818   // TODO: use the function scope once we have call site AAReturnedValues.
819   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
820   const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
821   if (!AARetVal.getState().isValidState())
822     return false;
823 
824   return AARetVal.checkForAllReturnedValuesAndReturnInsts(
825       [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) {
826         return Pred(RV);
827       });
828 }
829 
830 static bool checkForAllInstructionsImpl(
831     Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
832     function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
833     const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes,
834     bool CheckBBLivenessOnly = false) {
835   for (unsigned Opcode : Opcodes) {
836     // Check if we have instructions with this opcode at all first.
837     auto *Insts = OpcodeInstMap.lookup(Opcode);
838     if (!Insts)
839       continue;
840 
841     for (Instruction *I : *Insts) {
842       // Skip dead instructions.
843       if (A && A->isAssumedDead(IRPosition::value(*I), QueryingAA, LivenessAA,
844                                 CheckBBLivenessOnly))
845         continue;
846 
847       if (!Pred(*I))
848         return false;
849     }
850   }
851   return true;
852 }
853 
854 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
855                                          const AbstractAttribute &QueryingAA,
856                                          const ArrayRef<unsigned> &Opcodes,
857                                          bool CheckBBLivenessOnly) {
858 
859   const IRPosition &IRP = QueryingAA.getIRPosition();
860   // Since we need to provide instructions we have to have an exact definition.
861   const Function *AssociatedFunction = IRP.getAssociatedFunction();
862   if (!AssociatedFunction)
863     return false;
864 
865   // TODO: use the function scope once we have call site AAReturnedValues.
866   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
867   const auto &LivenessAA =
868       getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false);
869 
870   auto &OpcodeInstMap =
871       InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction);
872   if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA,
873                                    &LivenessAA, Opcodes, CheckBBLivenessOnly))
874     return false;
875 
876   return true;
877 }
878 
879 bool Attributor::checkForAllReadWriteInstructions(
880     function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA) {
881 
882   const Function *AssociatedFunction =
883       QueryingAA.getIRPosition().getAssociatedFunction();
884   if (!AssociatedFunction)
885     return false;
886 
887   // TODO: use the function scope once we have call site AAReturnedValues.
888   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
889   const auto &LivenessAA =
890       getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false);
891 
892   for (Instruction *I :
893        InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
894     // Skip dead instructions.
895     if (isAssumedDead(IRPosition::value(*I), &QueryingAA, &LivenessAA))
896       continue;
897 
898     if (!Pred(*I))
899       return false;
900   }
901 
902   return true;
903 }
904 
905 void Attributor::runTillFixpoint() {
906   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
907                     << AllAbstractAttributes.size()
908                     << " abstract attributes.\n");
909 
910   // Now that all abstract attributes are collected and initialized we start
911   // the abstract analysis.
912 
913   unsigned IterationCounter = 1;
914 
915   SmallVector<AbstractAttribute *, 32> ChangedAAs;
916   SetVector<AbstractAttribute *> Worklist, InvalidAAs;
917   Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end());
918 
919   do {
920     // Remember the size to determine new attributes.
921     size_t NumAAs = AllAbstractAttributes.size();
922     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
923                       << ", Worklist size: " << Worklist.size() << "\n");
924 
925     // For invalid AAs we can fix dependent AAs that have a required dependence,
926     // thereby folding long dependence chains in a single step without the need
927     // to run updates.
928     for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
929       AbstractAttribute *InvalidAA = InvalidAAs[u];
930 
931       // Check the dependences to fast track invalidation.
932       LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has "
933                         << InvalidAA->Deps.size()
934                         << " required & optional dependences\n");
935       while (!InvalidAA->Deps.empty()) {
936         const auto &Dep = InvalidAA->Deps.back();
937         InvalidAA->Deps.pop_back();
938         AbstractAttribute *DepAA = Dep.getPointer();
939         if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) {
940           Worklist.insert(DepAA);
941           continue;
942         }
943         DepAA->getState().indicatePessimisticFixpoint();
944         assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
945         if (!DepAA->getState().isValidState())
946           InvalidAAs.insert(DepAA);
947         else
948           ChangedAAs.push_back(DepAA);
949       }
950     }
951 
952     // Add all abstract attributes that are potentially dependent on one that
953     // changed to the work list.
954     for (AbstractAttribute *ChangedAA : ChangedAAs)
955       while (!ChangedAA->Deps.empty()) {
956         Worklist.insert(ChangedAA->Deps.back().getPointer());
957         ChangedAA->Deps.pop_back();
958       }
959 
960     LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
961                       << ", Worklist+Dependent size: " << Worklist.size()
962                       << "\n");
963 
964     // Reset the changed and invalid set.
965     ChangedAAs.clear();
966     InvalidAAs.clear();
967 
968     // Update all abstract attribute in the work list and record the ones that
969     // changed.
970     for (AbstractAttribute *AA : Worklist) {
971       const auto &AAState = AA->getState();
972       if (!AAState.isAtFixpoint())
973         if (updateAA(*AA) == ChangeStatus::CHANGED)
974           ChangedAAs.push_back(AA);
975 
976       // Use the InvalidAAs vector to propagate invalid states fast transitively
977       // without requiring updates.
978       if (!AAState.isValidState())
979         InvalidAAs.insert(AA);
980     }
981 
982     // Add attributes to the changed set if they have been created in the last
983     // iteration.
984     ChangedAAs.append(AllAbstractAttributes.begin() + NumAAs,
985                       AllAbstractAttributes.end());
986 
987     // Reset the work list and repopulate with the changed abstract attributes.
988     // Note that dependent ones are added above.
989     Worklist.clear();
990     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
991 
992   } while (!Worklist.empty() && (IterationCounter++ < MaxFixpointIterations ||
993                                  VerifyMaxFixpointIterations));
994 
995   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
996                     << IterationCounter << "/" << MaxFixpointIterations
997                     << " iterations\n");
998 
999   // Reset abstract arguments not settled in a sound fixpoint by now. This
1000   // happens when we stopped the fixpoint iteration early. Note that only the
1001   // ones marked as "changed" *and* the ones transitively depending on them
1002   // need to be reverted to a pessimistic state. Others might not be in a
1003   // fixpoint state but we can use the optimistic results for them anyway.
1004   SmallPtrSet<AbstractAttribute *, 32> Visited;
1005   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
1006     AbstractAttribute *ChangedAA = ChangedAAs[u];
1007     if (!Visited.insert(ChangedAA).second)
1008       continue;
1009 
1010     AbstractState &State = ChangedAA->getState();
1011     if (!State.isAtFixpoint()) {
1012       State.indicatePessimisticFixpoint();
1013 
1014       NumAttributesTimedOut++;
1015     }
1016 
1017     while (!ChangedAA->Deps.empty()) {
1018       ChangedAAs.push_back(ChangedAA->Deps.back().getPointer());
1019       ChangedAA->Deps.pop_back();
1020     }
1021   }
1022 
1023   LLVM_DEBUG({
1024     if (!Visited.empty())
1025       dbgs() << "\n[Attributor] Finalized " << Visited.size()
1026              << " abstract attributes.\n";
1027   });
1028 
1029   if (VerifyMaxFixpointIterations &&
1030       IterationCounter != MaxFixpointIterations) {
1031     errs() << "\n[Attributor] Fixpoint iteration done after: "
1032            << IterationCounter << "/" << MaxFixpointIterations
1033            << " iterations\n";
1034     llvm_unreachable("The fixpoint was not reached with exactly the number of "
1035                      "specified iterations!");
1036   }
1037 }
1038 
1039 ChangeStatus Attributor::manifestAttributes() {
1040   size_t NumFinalAAs = AllAbstractAttributes.size();
1041 
1042   unsigned NumManifested = 0;
1043   unsigned NumAtFixpoint = 0;
1044   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
1045   for (AbstractAttribute *AA : AllAbstractAttributes) {
1046     AbstractState &State = AA->getState();
1047 
1048     // If there is not already a fixpoint reached, we can now take the
1049     // optimistic state. This is correct because we enforced a pessimistic one
1050     // on abstract attributes that were transitively dependent on a changed one
1051     // already above.
1052     if (!State.isAtFixpoint())
1053       State.indicateOptimisticFixpoint();
1054 
1055     // If the state is invalid, we do not try to manifest it.
1056     if (!State.isValidState())
1057       continue;
1058 
1059     // Skip dead code.
1060     if (isAssumedDead(*AA, nullptr, /* CheckBBLivenessOnly */ true))
1061       continue;
1062     // Manifest the state and record if we changed the IR.
1063     ChangeStatus LocalChange = AA->manifest(*this);
1064     if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
1065       AA->trackStatistics();
1066     LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
1067                       << "\n");
1068 
1069     ManifestChange = ManifestChange | LocalChange;
1070 
1071     NumAtFixpoint++;
1072     NumManifested += (LocalChange == ChangeStatus::CHANGED);
1073   }
1074 
1075   (void)NumManifested;
1076   (void)NumAtFixpoint;
1077   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
1078                     << " arguments while " << NumAtFixpoint
1079                     << " were in a valid fixpoint state\n");
1080 
1081   NumAttributesManifested += NumManifested;
1082   NumAttributesValidFixpoint += NumAtFixpoint;
1083 
1084   (void)NumFinalAAs;
1085   if (NumFinalAAs != AllAbstractAttributes.size()) {
1086     for (unsigned u = NumFinalAAs; u < AllAbstractAttributes.size(); ++u)
1087       errs() << "Unexpected abstract attribute: " << *AllAbstractAttributes[u]
1088              << " :: "
1089              << AllAbstractAttributes[u]->getIRPosition().getAssociatedValue()
1090              << "\n";
1091     llvm_unreachable("Expected the final number of abstract attributes to "
1092                      "remain unchanged!");
1093   }
1094   return ManifestChange;
1095 }
1096 
1097 ChangeStatus Attributor::cleanupIR() {
1098   // Delete stuff at the end to avoid invalid references and a nice order.
1099   LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least "
1100                     << ToBeDeletedFunctions.size() << " functions and "
1101                     << ToBeDeletedBlocks.size() << " blocks and "
1102                     << ToBeDeletedInsts.size() << " instructions and "
1103                     << ToBeChangedUses.size() << " uses\n");
1104 
1105   SmallVector<WeakTrackingVH, 32> DeadInsts;
1106   SmallVector<Instruction *, 32> TerminatorsToFold;
1107 
1108   for (auto &It : ToBeChangedUses) {
1109     Use *U = It.first;
1110     Value *NewV = It.second;
1111     Value *OldV = U->get();
1112 
1113     // Do not replace uses in returns if the value is a must-tail call we will
1114     // not delete.
1115     if (isa<ReturnInst>(U->getUser()))
1116       if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
1117         if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
1118           continue;
1119 
1120     LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
1121                       << " instead of " << *OldV << "\n");
1122     U->set(NewV);
1123     // Do not modify call instructions outside the SCC.
1124     if (auto *CB = dyn_cast<CallBase>(OldV))
1125       if (!Functions.count(CB->getCaller()))
1126         continue;
1127     if (Instruction *I = dyn_cast<Instruction>(OldV)) {
1128       CGModifiedFunctions.insert(I->getFunction());
1129       if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) &&
1130           isInstructionTriviallyDead(I))
1131         DeadInsts.push_back(I);
1132     }
1133     if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) {
1134       Instruction *UserI = cast<Instruction>(U->getUser());
1135       if (isa<UndefValue>(NewV)) {
1136         ToBeChangedToUnreachableInsts.insert(UserI);
1137       } else {
1138         TerminatorsToFold.push_back(UserI);
1139       }
1140     }
1141   }
1142   for (auto &V : InvokeWithDeadSuccessor)
1143     if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
1144       bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
1145       bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
1146       bool Invoke2CallAllowed =
1147           !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction());
1148       assert((UnwindBBIsDead || NormalBBIsDead) &&
1149              "Invoke does not have dead successors!");
1150       BasicBlock *BB = II->getParent();
1151       BasicBlock *NormalDestBB = II->getNormalDest();
1152       if (UnwindBBIsDead) {
1153         Instruction *NormalNextIP = &NormalDestBB->front();
1154         if (Invoke2CallAllowed) {
1155           changeToCall(II);
1156           NormalNextIP = BB->getTerminator();
1157         }
1158         if (NormalBBIsDead)
1159           ToBeChangedToUnreachableInsts.insert(NormalNextIP);
1160       } else {
1161         assert(NormalBBIsDead && "Broken invariant!");
1162         if (!NormalDestBB->getUniquePredecessor())
1163           NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead");
1164         ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front());
1165       }
1166     }
1167   for (Instruction *I : TerminatorsToFold) {
1168     CGModifiedFunctions.insert(I->getFunction());
1169     ConstantFoldTerminator(I->getParent());
1170   }
1171   for (auto &V : ToBeChangedToUnreachableInsts)
1172     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
1173       CGModifiedFunctions.insert(I->getFunction());
1174       changeToUnreachable(I, /* UseLLVMTrap */ false);
1175     }
1176 
1177   for (auto &V : ToBeDeletedInsts) {
1178     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
1179       I->dropDroppableUses();
1180       CGModifiedFunctions.insert(I->getFunction());
1181       if (!I->getType()->isVoidTy())
1182         I->replaceAllUsesWith(UndefValue::get(I->getType()));
1183       if (!isa<PHINode>(I) && isInstructionTriviallyDead(I))
1184         DeadInsts.push_back(I);
1185       else
1186         I->eraseFromParent();
1187     }
1188   }
1189 
1190   LLVM_DEBUG(dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size()
1191                     << "\n");
1192 
1193   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
1194 
1195   if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
1196     SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
1197     ToBeDeletedBBs.reserve(NumDeadBlocks);
1198     for (BasicBlock *BB : ToBeDeletedBlocks) {
1199       CGModifiedFunctions.insert(BB->getParent());
1200       ToBeDeletedBBs.push_back(BB);
1201     }
1202     // Actually we do not delete the blocks but squash them into a single
1203     // unreachable but untangling branches that jump here is something we need
1204     // to do in a more generic way.
1205     DetatchDeadBlocks(ToBeDeletedBBs, nullptr);
1206   }
1207 
1208   // Identify dead internal functions and delete them. This happens outside
1209   // the other fixpoint analysis as we might treat potentially dead functions
1210   // as live to lower the number of iterations. If they happen to be dead, the
1211   // below fixpoint loop will identify and eliminate them.
1212   SmallVector<Function *, 8> InternalFns;
1213   for (Function *F : Functions)
1214     if (F->hasLocalLinkage())
1215       InternalFns.push_back(F);
1216 
1217   bool FoundDeadFn = true;
1218   while (FoundDeadFn) {
1219     FoundDeadFn = false;
1220     for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) {
1221       Function *F = InternalFns[u];
1222       if (!F)
1223         continue;
1224 
1225       bool AllCallSitesKnown;
1226       if (!checkForAllCallSites(
1227               [this](AbstractCallSite ACS) {
1228                 return ToBeDeletedFunctions.count(
1229                     ACS.getInstruction()->getFunction());
1230               },
1231               *F, true, nullptr, AllCallSitesKnown))
1232         continue;
1233 
1234       ToBeDeletedFunctions.insert(F);
1235       InternalFns[u] = nullptr;
1236       FoundDeadFn = true;
1237     }
1238   }
1239 
1240   // Rewrite the functions as requested during manifest.
1241   ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
1242 
1243   for (Function *Fn : CGModifiedFunctions)
1244     CGUpdater.reanalyzeFunction(*Fn);
1245 
1246   for (Function *Fn : ToBeDeletedFunctions)
1247     CGUpdater.removeFunction(*Fn);
1248 
1249   NumFnDeleted += ToBeDeletedFunctions.size();
1250 
1251   LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << NumFnDeleted
1252                     << " functions after manifest.\n");
1253 
1254 #ifdef EXPENSIVE_CHECKS
1255   for (Function *F : Functions) {
1256     if (ToBeDeletedFunctions.count(F))
1257       continue;
1258     assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
1259   }
1260 #endif
1261 
1262   return ManifestChange;
1263 }
1264 
1265 ChangeStatus Attributor::run() {
1266   SeedingPeriod = false;
1267   runTillFixpoint();
1268   ChangeStatus ManifestChange = manifestAttributes();
1269   ChangeStatus CleanupChange = cleanupIR();
1270   return ManifestChange | CleanupChange;
1271 }
1272 
1273 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
1274   // Use a new dependence vector for this update.
1275   DependenceVector DV;
1276   DependenceStack.push_back(&DV);
1277 
1278   auto &AAState = AA.getState();
1279   ChangeStatus CS = ChangeStatus::UNCHANGED;
1280   if (!isAssumedDead(AA, nullptr, /* CheckBBLivenessOnly */ true))
1281     CS = AA.update(*this);
1282 
1283   if (DV.empty()) {
1284     // If the attribute did not query any non-fix information, the state
1285     // will not change and we can indicate that right away.
1286     AAState.indicateOptimisticFixpoint();
1287   }
1288 
1289   if (!AAState.isAtFixpoint())
1290     rememberDependences();
1291 
1292   // Verify the stack was used properly, that is we pop the dependence vector we
1293   // put there earlier.
1294   DependenceVector *PoppedDV = DependenceStack.pop_back_val();
1295   (void)PoppedDV;
1296   assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
1297 
1298   return CS;
1299 }
1300 
1301 /// Create a shallow wrapper for \p F such that \p F has internal linkage
1302 /// afterwards. It also sets the original \p F 's name to anonymous
1303 ///
1304 /// A wrapper is a function with the same type (and attributes) as \p F
1305 /// that will only call \p F and return the result, if any.
1306 ///
1307 /// Assuming the declaration of looks like:
1308 ///   rty F(aty0 arg0, ..., atyN argN);
1309 ///
1310 /// The wrapper will then look as follows:
1311 ///   rty wrapper(aty0 arg0, ..., atyN argN) {
1312 ///     return F(arg0, ..., argN);
1313 ///   }
1314 ///
1315 static void createShallowWrapper(Function &F) {
1316   assert(AllowShallowWrappers &&
1317          "Cannot create a wrapper if it is not allowed!");
1318   assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
1319 
1320   Module &M = *F.getParent();
1321   LLVMContext &Ctx = M.getContext();
1322   FunctionType *FnTy = F.getFunctionType();
1323 
1324   Function *Wrapper =
1325       Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName());
1326   F.setName(""); // set the inside function anonymous
1327   M.getFunctionList().insert(F.getIterator(), Wrapper);
1328 
1329   F.setLinkage(GlobalValue::InternalLinkage);
1330 
1331   F.replaceAllUsesWith(Wrapper);
1332   assert(F.use_empty() && "Uses remained after wrapper was created!");
1333 
1334   // Move the COMDAT section to the wrapper.
1335   // TODO: Check if we need to keep it for F as well.
1336   Wrapper->setComdat(F.getComdat());
1337   F.setComdat(nullptr);
1338 
1339   // Copy all metadata and attributes but keep them on F as well.
1340   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1341   F.getAllMetadata(MDs);
1342   for (auto MDIt : MDs)
1343     Wrapper->addMetadata(MDIt.first, *MDIt.second);
1344   Wrapper->setAttributes(F.getAttributes());
1345 
1346   // Create the call in the wrapper.
1347   BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper);
1348 
1349   SmallVector<Value *, 8> Args;
1350   auto FArgIt = F.arg_begin();
1351   for (Argument &Arg : Wrapper->args()) {
1352     Args.push_back(&Arg);
1353     Arg.setName((FArgIt++)->getName());
1354   }
1355 
1356   CallInst *CI = CallInst::Create(&F, Args, "", EntryBB);
1357   CI->setTailCall(true);
1358   CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1359   ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB);
1360 
1361   NumFnShallowWrapperCreated++;
1362 }
1363 
1364 bool Attributor::isValidFunctionSignatureRewrite(
1365     Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
1366 
1367   auto CallSiteCanBeChanged = [](AbstractCallSite ACS) {
1368     // Forbid the call site to cast the function return type. If we need to
1369     // rewrite these functions we need to re-create a cast for the new call site
1370     // (if the old had uses).
1371     if (!ACS.getCalledFunction() ||
1372         ACS.getInstruction()->getType() !=
1373             ACS.getCalledFunction()->getReturnType())
1374       return false;
1375     // Forbid must-tail calls for now.
1376     return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
1377   };
1378 
1379   Function *Fn = Arg.getParent();
1380   // Avoid var-arg functions for now.
1381   if (Fn->isVarArg()) {
1382     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
1383     return false;
1384   }
1385 
1386   // Avoid functions with complicated argument passing semantics.
1387   AttributeList FnAttributeList = Fn->getAttributes();
1388   if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
1389       FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
1390       FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
1391       FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
1392     LLVM_DEBUG(
1393         dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
1394     return false;
1395   }
1396 
1397   // Avoid callbacks for now.
1398   bool AllCallSitesKnown;
1399   if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr,
1400                             AllCallSitesKnown)) {
1401     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
1402     return false;
1403   }
1404 
1405   auto InstPred = [](Instruction &I) {
1406     if (auto *CI = dyn_cast<CallInst>(&I))
1407       return !CI->isMustTailCall();
1408     return true;
1409   };
1410 
1411   // Forbid must-tail calls for now.
1412   // TODO:
1413   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
1414   if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr,
1415                                    nullptr, {Instruction::Call})) {
1416     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
1417     return false;
1418   }
1419 
1420   return true;
1421 }
1422 
1423 bool Attributor::registerFunctionSignatureRewrite(
1424     Argument &Arg, ArrayRef<Type *> ReplacementTypes,
1425     ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
1426     ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
1427   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
1428                     << Arg.getParent()->getName() << " with "
1429                     << ReplacementTypes.size() << " replacements\n");
1430   assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
1431          "Cannot register an invalid rewrite");
1432 
1433   Function *Fn = Arg.getParent();
1434   SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
1435       ArgumentReplacementMap[Fn];
1436   if (ARIs.empty())
1437     ARIs.resize(Fn->arg_size());
1438 
1439   // If we have a replacement already with less than or equal new arguments,
1440   // ignore this request.
1441   std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
1442   if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
1443     LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
1444     return false;
1445   }
1446 
1447   // If we have a replacement already but we like the new one better, delete
1448   // the old.
1449   ARI.reset();
1450 
1451   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
1452                     << Arg.getParent()->getName() << " with "
1453                     << ReplacementTypes.size() << " replacements\n");
1454 
1455   // Remember the replacement.
1456   ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
1457                                         std::move(CalleeRepairCB),
1458                                         std::move(ACSRepairCB)));
1459 
1460   return true;
1461 }
1462 
1463 bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
1464   if (SeedAllowList.size() == 0)
1465     return true;
1466   return std::count(SeedAllowList.begin(), SeedAllowList.end(), AA.getName());
1467 }
1468 
1469 ChangeStatus Attributor::rewriteFunctionSignatures(
1470     SmallPtrSetImpl<Function *> &ModifiedFns) {
1471   ChangeStatus Changed = ChangeStatus::UNCHANGED;
1472 
1473   for (auto &It : ArgumentReplacementMap) {
1474     Function *OldFn = It.getFirst();
1475 
1476     // Deleted functions do not require rewrites.
1477     if (ToBeDeletedFunctions.count(OldFn))
1478       continue;
1479 
1480     const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
1481         It.getSecond();
1482     assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
1483 
1484     SmallVector<Type *, 16> NewArgumentTypes;
1485     SmallVector<AttributeSet, 16> NewArgumentAttributes;
1486 
1487     // Collect replacement argument types and copy over existing attributes.
1488     AttributeList OldFnAttributeList = OldFn->getAttributes();
1489     for (Argument &Arg : OldFn->args()) {
1490       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
1491               ARIs[Arg.getArgNo()]) {
1492         NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
1493                                 ARI->ReplacementTypes.end());
1494         NewArgumentAttributes.append(ARI->getNumReplacementArgs(),
1495                                      AttributeSet());
1496       } else {
1497         NewArgumentTypes.push_back(Arg.getType());
1498         NewArgumentAttributes.push_back(
1499             OldFnAttributeList.getParamAttributes(Arg.getArgNo()));
1500       }
1501     }
1502 
1503     FunctionType *OldFnTy = OldFn->getFunctionType();
1504     Type *RetTy = OldFnTy->getReturnType();
1505 
1506     // Construct the new function type using the new arguments types.
1507     FunctionType *NewFnTy =
1508         FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg());
1509 
1510     LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
1511                       << "' from " << *OldFn->getFunctionType() << " to "
1512                       << *NewFnTy << "\n");
1513 
1514     // Create the new function body and insert it into the module.
1515     Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(),
1516                                        OldFn->getAddressSpace(), "");
1517     OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn);
1518     NewFn->takeName(OldFn);
1519     NewFn->copyAttributesFrom(OldFn);
1520 
1521     // Patch the pointer to LLVM function in debug info descriptor.
1522     NewFn->setSubprogram(OldFn->getSubprogram());
1523     OldFn->setSubprogram(nullptr);
1524 
1525     // Recompute the parameter attributes list based on the new arguments for
1526     // the function.
1527     LLVMContext &Ctx = OldFn->getContext();
1528     NewFn->setAttributes(AttributeList::get(
1529         Ctx, OldFnAttributeList.getFnAttributes(),
1530         OldFnAttributeList.getRetAttributes(), NewArgumentAttributes));
1531 
1532     // Since we have now created the new function, splice the body of the old
1533     // function right into the new function, leaving the old rotting hulk of the
1534     // function empty.
1535     NewFn->getBasicBlockList().splice(NewFn->begin(),
1536                                       OldFn->getBasicBlockList());
1537 
1538     // Fixup block addresses to reference new function.
1539     SmallVector<BlockAddress *, 8u> BlockAddresses;
1540     for (User *U : OldFn->users())
1541       if (auto *BA = dyn_cast<BlockAddress>(U))
1542         BlockAddresses.push_back(BA);
1543     for (auto *BA : BlockAddresses)
1544       BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock()));
1545 
1546     // Set of all "call-like" instructions that invoke the old function mapped
1547     // to their new replacements.
1548     SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
1549 
1550     // Callback to create a new "call-like" instruction for a given one.
1551     auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
1552       CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
1553       const AttributeList &OldCallAttributeList = OldCB->getAttributes();
1554 
1555       // Collect the new argument operands for the replacement call site.
1556       SmallVector<Value *, 16> NewArgOperands;
1557       SmallVector<AttributeSet, 16> NewArgOperandAttributes;
1558       for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
1559         unsigned NewFirstArgNum = NewArgOperands.size();
1560         (void)NewFirstArgNum; // only used inside assert.
1561         if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
1562                 ARIs[OldArgNum]) {
1563           if (ARI->ACSRepairCB)
1564             ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
1565           assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
1566                      NewArgOperands.size() &&
1567                  "ACS repair callback did not provide as many operand as new "
1568                  "types were registered!");
1569           // TODO: Exose the attribute set to the ACS repair callback
1570           NewArgOperandAttributes.append(ARI->ReplacementTypes.size(),
1571                                          AttributeSet());
1572         } else {
1573           NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum));
1574           NewArgOperandAttributes.push_back(
1575               OldCallAttributeList.getParamAttributes(OldArgNum));
1576         }
1577       }
1578 
1579       assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
1580              "Mismatch # argument operands vs. # argument operand attributes!");
1581       assert(NewArgOperands.size() == NewFn->arg_size() &&
1582              "Mismatch # argument operands vs. # function arguments!");
1583 
1584       SmallVector<OperandBundleDef, 4> OperandBundleDefs;
1585       OldCB->getOperandBundlesAsDefs(OperandBundleDefs);
1586 
1587       // Create a new call or invoke instruction to replace the old one.
1588       CallBase *NewCB;
1589       if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
1590         NewCB =
1591             InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(),
1592                                NewArgOperands, OperandBundleDefs, "", OldCB);
1593       } else {
1594         auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs,
1595                                        "", OldCB);
1596         NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
1597         NewCB = NewCI;
1598       }
1599 
1600       // Copy over various properties and the new attributes.
1601       NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
1602       NewCB->setCallingConv(OldCB->getCallingConv());
1603       NewCB->takeName(OldCB);
1604       NewCB->setAttributes(AttributeList::get(
1605           Ctx, OldCallAttributeList.getFnAttributes(),
1606           OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes));
1607 
1608       CallSitePairs.push_back({OldCB, NewCB});
1609       return true;
1610     };
1611 
1612     // Use the CallSiteReplacementCreator to create replacement call sites.
1613     bool AllCallSitesKnown;
1614     bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
1615                                         true, nullptr, AllCallSitesKnown);
1616     (void)Success;
1617     assert(Success && "Assumed call site replacement to succeed!");
1618 
1619     // Rewire the arguments.
1620     auto OldFnArgIt = OldFn->arg_begin();
1621     auto NewFnArgIt = NewFn->arg_begin();
1622     for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
1623          ++OldArgNum, ++OldFnArgIt) {
1624       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
1625               ARIs[OldArgNum]) {
1626         if (ARI->CalleeRepairCB)
1627           ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
1628         NewFnArgIt += ARI->ReplacementTypes.size();
1629       } else {
1630         NewFnArgIt->takeName(&*OldFnArgIt);
1631         OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
1632         ++NewFnArgIt;
1633       }
1634     }
1635 
1636     // Eliminate the instructions *after* we visited all of them.
1637     for (auto &CallSitePair : CallSitePairs) {
1638       CallBase &OldCB = *CallSitePair.first;
1639       CallBase &NewCB = *CallSitePair.second;
1640       assert(OldCB.getType() == NewCB.getType() &&
1641              "Cannot handle call sites with different types!");
1642       ModifiedFns.insert(OldCB.getFunction());
1643       CGUpdater.replaceCallSite(OldCB, NewCB);
1644       OldCB.replaceAllUsesWith(&NewCB);
1645       OldCB.eraseFromParent();
1646     }
1647 
1648     // Replace the function in the call graph (if any).
1649     CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
1650 
1651     // If the old function was modified and needed to be reanalyzed, the new one
1652     // does now.
1653     if (ModifiedFns.erase(OldFn))
1654       ModifiedFns.insert(NewFn);
1655 
1656     Changed = ChangeStatus::CHANGED;
1657   }
1658 
1659   return Changed;
1660 }
1661 
1662 void InformationCache::initializeInformationCache(const Function &CF,
1663                                                   FunctionInfo &FI) {
1664   // As we do not modify the function here we can remove the const
1665   // withouth breaking implicit assumptions. At the end of the day, we could
1666   // initialize the cache eagerly which would look the same to the users.
1667   Function &F = const_cast<Function &>(CF);
1668 
1669   // Walk all instructions to find interesting instructions that might be
1670   // queried by abstract attributes during their initialization or update.
1671   // This has to happen before we create attributes.
1672 
1673   for (Instruction &I : instructions(&F)) {
1674     bool IsInterestingOpcode = false;
1675 
1676     // To allow easy access to all instructions in a function with a given
1677     // opcode we store them in the InfoCache. As not all opcodes are interesting
1678     // to concrete attributes we only cache the ones that are as identified in
1679     // the following switch.
1680     // Note: There are no concrete attributes now so this is initially empty.
1681     switch (I.getOpcode()) {
1682     default:
1683       assert(!isa<CallBase>(&I) &&
1684              "New call base instruction type needs to be known in the "
1685              "Attributor.");
1686       break;
1687     case Instruction::Call:
1688       // Calls are interesting on their own, additionally:
1689       // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
1690       // For `must-tail` calls we remember the caller and callee.
1691       if (IntrinsicInst *Assume = dyn_cast<IntrinsicInst>(&I)) {
1692         if (Assume->getIntrinsicID() == Intrinsic::assume)
1693           fillMapFromAssume(*Assume, KnowledgeMap);
1694       } else if (cast<CallInst>(I).isMustTailCall()) {
1695         FI.ContainsMustTailCall = true;
1696         if (const Function *Callee = cast<CallInst>(I).getCalledFunction())
1697           getFunctionInfo(*Callee).CalledViaMustTail = true;
1698       }
1699       LLVM_FALLTHROUGH;
1700     case Instruction::CallBr:
1701     case Instruction::Invoke:
1702     case Instruction::CleanupRet:
1703     case Instruction::CatchSwitch:
1704     case Instruction::AtomicRMW:
1705     case Instruction::AtomicCmpXchg:
1706     case Instruction::Br:
1707     case Instruction::Resume:
1708     case Instruction::Ret:
1709     case Instruction::Load:
1710       // The alignment of a pointer is interesting for loads.
1711     case Instruction::Store:
1712       // The alignment of a pointer is interesting for stores.
1713       IsInterestingOpcode = true;
1714     }
1715     if (IsInterestingOpcode) {
1716       auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
1717       if (!Insts)
1718         Insts = new (Allocator) InstructionVectorTy();
1719       Insts->push_back(&I);
1720     }
1721     if (I.mayReadOrWriteMemory())
1722       FI.RWInsts.push_back(&I);
1723   }
1724 
1725   if (F.hasFnAttribute(Attribute::AlwaysInline) &&
1726       isInlineViable(F).isSuccess())
1727     InlineableFunctions.insert(&F);
1728 }
1729 
1730 InformationCache::FunctionInfo::~FunctionInfo() {
1731   // The instruction vectors are allocated using a BumpPtrAllocator, we need to
1732   // manually destroy them.
1733   for (auto &It : OpcodeInstMap)
1734     It.getSecond()->~InstructionVectorTy();
1735 }
1736 
1737 void Attributor::recordDependence(const AbstractAttribute &FromAA,
1738                                   const AbstractAttribute &ToAA,
1739                                   DepClassTy DepClass) {
1740   // If we are outside of an update, thus before the actual fixpoint iteration
1741   // started (= when we create AAs), we do not track dependences because we will
1742   // put all AAs into the initial worklist anyway.
1743   if (DependenceStack.empty())
1744     return;
1745   if (FromAA.getState().isAtFixpoint())
1746     return;
1747   DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
1748 }
1749 
1750 void Attributor::rememberDependences() {
1751   assert(!DependenceStack.empty() && "No dependences to remember!");
1752 
1753   for (DepInfo &DI : *DependenceStack.back()) {
1754     auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
1755     DepAAs.push_back(AbstractAttribute::DepTy(
1756         const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
1757   }
1758 }
1759 
1760 void Attributor::identifyDefaultAbstractAttributes(Function &F) {
1761   if (!VisitedFunctions.insert(&F).second)
1762     return;
1763   if (F.isDeclaration())
1764     return;
1765 
1766   // In non-module runs we need to look at the call sites of a function to
1767   // determine if it is part of a must-tail call edge. This will influence what
1768   // attributes we can derive.
1769   InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
1770   if (!isModulePass() && !FI.CalledViaMustTail) {
1771     for (const Use &U : F.uses())
1772       if (const auto *CB = dyn_cast<CallBase>(U.getUser()))
1773         if (CB->isCallee(&U) && CB->isMustTailCall())
1774           FI.CalledViaMustTail = true;
1775   }
1776 
1777   IRPosition FPos = IRPosition::function(F);
1778 
1779   // Check for dead BasicBlocks in every function.
1780   // We need dead instruction detection because we do not want to deal with
1781   // broken IR in which SSA rules do not apply.
1782   getOrCreateAAFor<AAIsDead>(FPos);
1783 
1784   // Every function might be "will-return".
1785   getOrCreateAAFor<AAWillReturn>(FPos);
1786 
1787   // Every function might contain instructions that cause "undefined behavior".
1788   getOrCreateAAFor<AAUndefinedBehavior>(FPos);
1789 
1790   // Every function can be nounwind.
1791   getOrCreateAAFor<AANoUnwind>(FPos);
1792 
1793   // Every function might be marked "nosync"
1794   getOrCreateAAFor<AANoSync>(FPos);
1795 
1796   // Every function might be "no-free".
1797   getOrCreateAAFor<AANoFree>(FPos);
1798 
1799   // Every function might be "no-return".
1800   getOrCreateAAFor<AANoReturn>(FPos);
1801 
1802   // Every function might be "no-recurse".
1803   getOrCreateAAFor<AANoRecurse>(FPos);
1804 
1805   // Every function might be "readnone/readonly/writeonly/...".
1806   getOrCreateAAFor<AAMemoryBehavior>(FPos);
1807 
1808   // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
1809   getOrCreateAAFor<AAMemoryLocation>(FPos);
1810 
1811   // Every function might be applicable for Heap-To-Stack conversion.
1812   if (EnableHeapToStack)
1813     getOrCreateAAFor<AAHeapToStack>(FPos);
1814 
1815   // Return attributes are only appropriate if the return type is non void.
1816   Type *ReturnType = F.getReturnType();
1817   if (!ReturnType->isVoidTy()) {
1818     // Argument attribute "returned" --- Create only one per function even
1819     // though it is an argument attribute.
1820     getOrCreateAAFor<AAReturnedValues>(FPos);
1821 
1822     IRPosition RetPos = IRPosition::returned(F);
1823 
1824     // Every returned value might be dead.
1825     getOrCreateAAFor<AAIsDead>(RetPos);
1826 
1827     // Every function might be simplified.
1828     getOrCreateAAFor<AAValueSimplify>(RetPos);
1829 
1830     if (ReturnType->isPointerTy()) {
1831 
1832       // Every function with pointer return type might be marked align.
1833       getOrCreateAAFor<AAAlign>(RetPos);
1834 
1835       // Every function with pointer return type might be marked nonnull.
1836       getOrCreateAAFor<AANonNull>(RetPos);
1837 
1838       // Every function with pointer return type might be marked noalias.
1839       getOrCreateAAFor<AANoAlias>(RetPos);
1840 
1841       // Every function with pointer return type might be marked
1842       // dereferenceable.
1843       getOrCreateAAFor<AADereferenceable>(RetPos);
1844     }
1845   }
1846 
1847   for (Argument &Arg : F.args()) {
1848     IRPosition ArgPos = IRPosition::argument(Arg);
1849 
1850     // Every argument might be simplified.
1851     getOrCreateAAFor<AAValueSimplify>(ArgPos);
1852 
1853     // Every argument might be dead.
1854     getOrCreateAAFor<AAIsDead>(ArgPos);
1855 
1856     if (Arg.getType()->isPointerTy()) {
1857       // Every argument with pointer type might be marked nonnull.
1858       getOrCreateAAFor<AANonNull>(ArgPos);
1859 
1860       // Every argument with pointer type might be marked noalias.
1861       getOrCreateAAFor<AANoAlias>(ArgPos);
1862 
1863       // Every argument with pointer type might be marked dereferenceable.
1864       getOrCreateAAFor<AADereferenceable>(ArgPos);
1865 
1866       // Every argument with pointer type might be marked align.
1867       getOrCreateAAFor<AAAlign>(ArgPos);
1868 
1869       // Every argument with pointer type might be marked nocapture.
1870       getOrCreateAAFor<AANoCapture>(ArgPos);
1871 
1872       // Every argument with pointer type might be marked
1873       // "readnone/readonly/writeonly/..."
1874       getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
1875 
1876       // Every argument with pointer type might be marked nofree.
1877       getOrCreateAAFor<AANoFree>(ArgPos);
1878 
1879       // Every argument with pointer type might be privatizable (or promotable)
1880       getOrCreateAAFor<AAPrivatizablePtr>(ArgPos);
1881     }
1882   }
1883 
1884   auto CallSitePred = [&](Instruction &I) -> bool {
1885     auto &CB = cast<CallBase>(I);
1886     IRPosition CBRetPos = IRPosition::callsite_returned(CB);
1887 
1888     // Call sites might be dead if they do not have side effects and no live
1889     // users. The return value might be dead if there are no live users.
1890     getOrCreateAAFor<AAIsDead>(CBRetPos);
1891 
1892     Function *Callee = CB.getCalledFunction();
1893     // TODO: Even if the callee is not known now we might be able to simplify
1894     //       the call/callee.
1895     if (!Callee)
1896       return true;
1897 
1898     // Skip declarations except if annotations on their call sites were
1899     // explicitly requested.
1900     if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
1901         !Callee->hasMetadata(LLVMContext::MD_callback))
1902       return true;
1903 
1904     if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
1905 
1906       IRPosition CBRetPos = IRPosition::callsite_returned(CB);
1907 
1908       // Call site return integer values might be limited by a constant range.
1909       if (Callee->getReturnType()->isIntegerTy())
1910         getOrCreateAAFor<AAValueConstantRange>(CBRetPos);
1911     }
1912 
1913     for (int I = 0, E = CB.getNumArgOperands(); I < E; ++I) {
1914 
1915       IRPosition CBArgPos = IRPosition::callsite_argument(CB, I);
1916 
1917       // Every call site argument might be dead.
1918       getOrCreateAAFor<AAIsDead>(CBArgPos);
1919 
1920       // Call site argument might be simplified.
1921       getOrCreateAAFor<AAValueSimplify>(CBArgPos);
1922 
1923       if (!CB.getArgOperand(I)->getType()->isPointerTy())
1924         continue;
1925 
1926       // Call site argument attribute "non-null".
1927       getOrCreateAAFor<AANonNull>(CBArgPos);
1928 
1929       // Call site argument attribute "nocapture".
1930       getOrCreateAAFor<AANoCapture>(CBArgPos);
1931 
1932       // Call site argument attribute "no-alias".
1933       getOrCreateAAFor<AANoAlias>(CBArgPos);
1934 
1935       // Call site argument attribute "dereferenceable".
1936       getOrCreateAAFor<AADereferenceable>(CBArgPos);
1937 
1938       // Call site argument attribute "align".
1939       getOrCreateAAFor<AAAlign>(CBArgPos);
1940 
1941       // Call site argument attribute
1942       // "readnone/readonly/writeonly/..."
1943       getOrCreateAAFor<AAMemoryBehavior>(CBArgPos);
1944 
1945       // Call site argument attribute "nofree".
1946       getOrCreateAAFor<AANoFree>(CBArgPos);
1947     }
1948     return true;
1949   };
1950 
1951   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
1952   bool Success;
1953   Success = checkForAllInstructionsImpl(
1954       nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr,
1955       {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
1956        (unsigned)Instruction::Call});
1957   (void)Success;
1958   assert(Success && "Expected the check call to be successful!");
1959 
1960   auto LoadStorePred = [&](Instruction &I) -> bool {
1961     if (isa<LoadInst>(I))
1962       getOrCreateAAFor<AAAlign>(
1963           IRPosition::value(*cast<LoadInst>(I).getPointerOperand()));
1964     else
1965       getOrCreateAAFor<AAAlign>(
1966           IRPosition::value(*cast<StoreInst>(I).getPointerOperand()));
1967     return true;
1968   };
1969   Success = checkForAllInstructionsImpl(
1970       nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr,
1971       {(unsigned)Instruction::Load, (unsigned)Instruction::Store});
1972   (void)Success;
1973   assert(Success && "Expected the check call to be successful!");
1974 }
1975 
1976 /// Helpers to ease debugging through output streams and print calls.
1977 ///
1978 ///{
1979 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
1980   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
1981 }
1982 
1983 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
1984   switch (AP) {
1985   case IRPosition::IRP_INVALID:
1986     return OS << "inv";
1987   case IRPosition::IRP_FLOAT:
1988     return OS << "flt";
1989   case IRPosition::IRP_RETURNED:
1990     return OS << "fn_ret";
1991   case IRPosition::IRP_CALL_SITE_RETURNED:
1992     return OS << "cs_ret";
1993   case IRPosition::IRP_FUNCTION:
1994     return OS << "fn";
1995   case IRPosition::IRP_CALL_SITE:
1996     return OS << "cs";
1997   case IRPosition::IRP_ARGUMENT:
1998     return OS << "arg";
1999   case IRPosition::IRP_CALL_SITE_ARGUMENT:
2000     return OS << "cs_arg";
2001   }
2002   llvm_unreachable("Unknown attribute position!");
2003 }
2004 
2005 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
2006   const Value &AV = Pos.getAssociatedValue();
2007   return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
2008             << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}";
2009 }
2010 
2011 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
2012   OS << "range-state(" << S.getBitWidth() << ")<";
2013   S.getKnown().print(OS);
2014   OS << " / ";
2015   S.getAssumed().print(OS);
2016   OS << ">";
2017 
2018   return OS << static_cast<const AbstractState &>(S);
2019 }
2020 
2021 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
2022   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
2023 }
2024 
2025 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
2026   AA.print(OS);
2027   return OS;
2028 }
2029 
2030 void AbstractAttribute::print(raw_ostream &OS) const {
2031   OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState()
2032      << "]";
2033 }
2034 ///}
2035 
2036 /// ----------------------------------------------------------------------------
2037 ///                       Pass (Manager) Boilerplate
2038 /// ----------------------------------------------------------------------------
2039 
2040 static bool runAttributorOnFunctions(InformationCache &InfoCache,
2041                                      SetVector<Function *> &Functions,
2042                                      AnalysisGetter &AG,
2043                                      CallGraphUpdater &CGUpdater) {
2044   if (Functions.empty())
2045     return false;
2046 
2047   LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << Functions.size()
2048                     << " functions.\n");
2049 
2050   // Create an Attributor and initially empty information cache that is filled
2051   // while we identify default attribute opportunities.
2052   Attributor A(Functions, InfoCache, CGUpdater);
2053 
2054   // Create shallow wrappers for all functions that are not IPO amendable
2055   if (AllowShallowWrappers)
2056     for (Function *F : Functions)
2057       if (!A.isFunctionIPOAmendable(*F))
2058         createShallowWrapper(*F);
2059 
2060   for (Function *F : Functions) {
2061     if (F->hasExactDefinition())
2062       NumFnWithExactDefinition++;
2063     else
2064       NumFnWithoutExactDefinition++;
2065 
2066     // We look at internal functions only on-demand but if any use is not a
2067     // direct call or outside the current set of analyzed functions, we have to
2068     // do it eagerly.
2069     if (F->hasLocalLinkage()) {
2070       if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
2071             const auto *CB = dyn_cast<CallBase>(U.getUser());
2072             return CB && CB->isCallee(&U) &&
2073                    Functions.count(const_cast<Function *>(CB->getCaller()));
2074           }))
2075         continue;
2076     }
2077 
2078     // Populate the Attributor with abstract attribute opportunities in the
2079     // function and the information cache with IR information.
2080     A.identifyDefaultAbstractAttributes(*F);
2081   }
2082 
2083   ChangeStatus Changed = A.run();
2084   LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
2085                     << " functions, result: " << Changed << ".\n");
2086   return Changed == ChangeStatus::CHANGED;
2087 }
2088 
2089 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
2090   FunctionAnalysisManager &FAM =
2091       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2092   AnalysisGetter AG(FAM);
2093 
2094   SetVector<Function *> Functions;
2095   for (Function &F : M)
2096     Functions.insert(&F);
2097 
2098   CallGraphUpdater CGUpdater;
2099   BumpPtrAllocator Allocator;
2100   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
2101   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) {
2102     // FIXME: Think about passes we will preserve and add them here.
2103     return PreservedAnalyses::none();
2104   }
2105   return PreservedAnalyses::all();
2106 }
2107 
2108 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
2109                                            CGSCCAnalysisManager &AM,
2110                                            LazyCallGraph &CG,
2111                                            CGSCCUpdateResult &UR) {
2112   FunctionAnalysisManager &FAM =
2113       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2114   AnalysisGetter AG(FAM);
2115 
2116   SetVector<Function *> Functions;
2117   for (LazyCallGraph::Node &N : C)
2118     Functions.insert(&N.getFunction());
2119 
2120   if (Functions.empty())
2121     return PreservedAnalyses::all();
2122 
2123   Module &M = *Functions.back()->getParent();
2124   CallGraphUpdater CGUpdater;
2125   CGUpdater.initialize(CG, C, AM, UR);
2126   BumpPtrAllocator Allocator;
2127   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
2128   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) {
2129     // FIXME: Think about passes we will preserve and add them here.
2130     return PreservedAnalyses::none();
2131   }
2132   return PreservedAnalyses::all();
2133 }
2134 
2135 namespace {
2136 
2137 struct AttributorLegacyPass : public ModulePass {
2138   static char ID;
2139 
2140   AttributorLegacyPass() : ModulePass(ID) {
2141     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
2142   }
2143 
2144   bool runOnModule(Module &M) override {
2145     if (skipModule(M))
2146       return false;
2147 
2148     AnalysisGetter AG;
2149     SetVector<Function *> Functions;
2150     for (Function &F : M)
2151       Functions.insert(&F);
2152 
2153     CallGraphUpdater CGUpdater;
2154     BumpPtrAllocator Allocator;
2155     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
2156     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater);
2157   }
2158 
2159   void getAnalysisUsage(AnalysisUsage &AU) const override {
2160     // FIXME: Think about passes we will preserve and add them here.
2161     AU.addRequired<TargetLibraryInfoWrapperPass>();
2162   }
2163 };
2164 
2165 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass {
2166   CallGraphUpdater CGUpdater;
2167   static char ID;
2168 
2169   AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) {
2170     initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
2171   }
2172 
2173   bool runOnSCC(CallGraphSCC &SCC) override {
2174     if (skipSCC(SCC))
2175       return false;
2176 
2177     SetVector<Function *> Functions;
2178     for (CallGraphNode *CGN : SCC)
2179       if (Function *Fn = CGN->getFunction())
2180         if (!Fn->isDeclaration())
2181           Functions.insert(Fn);
2182 
2183     if (Functions.empty())
2184       return false;
2185 
2186     AnalysisGetter AG;
2187     CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph());
2188     CGUpdater.initialize(CG, SCC);
2189     Module &M = *Functions.back()->getParent();
2190     BumpPtrAllocator Allocator;
2191     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
2192     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater);
2193   }
2194 
2195   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
2196 
2197   void getAnalysisUsage(AnalysisUsage &AU) const override {
2198     // FIXME: Think about passes we will preserve and add them here.
2199     AU.addRequired<TargetLibraryInfoWrapperPass>();
2200     CallGraphSCCPass::getAnalysisUsage(AU);
2201   }
2202 };
2203 
2204 } // end anonymous namespace
2205 
2206 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
2207 Pass *llvm::createAttributorCGSCCLegacyPass() {
2208   return new AttributorCGSCCLegacyPass();
2209 }
2210 
2211 char AttributorLegacyPass::ID = 0;
2212 char AttributorCGSCCLegacyPass::ID = 0;
2213 
2214 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
2215                       "Deduce and propagate attributes", false, false)
2216 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2217 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
2218                     "Deduce and propagate attributes", false, false)
2219 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc",
2220                       "Deduce and propagate attributes (CGSCC pass)", false,
2221                       false)
2222 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2223 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
2224 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc",
2225                     "Deduce and propagate attributes (CGSCC pass)", false,
2226                     false)
2227