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