1 //===- AttributorAttributes.cpp - Attributes for Attributor 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 // See the Attributor.h file comment and the class descriptions in that file for
10 // more information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/Attributor.h"
15 
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/CaptureTracking.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/Analysis/MemoryBuiltins.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/NoFolder.h"
26 #include "llvm/Transforms/IPO/ArgumentPromotion.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 static cl::opt<bool> ManifestInternal(
36     "attributor-manifest-internal", cl::Hidden,
37     cl::desc("Manifest Attributor internal string attributes."),
38     cl::init(false));
39 
40 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128),
41                                        cl::Hidden);
42 
43 // Some helper macros to deal with statistics tracking.
44 //
45 // Usage:
46 // For simple IR attribute tracking overload trackStatistics in the abstract
47 // attribute and choose the right STATS_DECLTRACK_********* macro,
48 // e.g.,:
49 //  void trackStatistics() const override {
50 //    STATS_DECLTRACK_ARG_ATTR(returned)
51 //  }
52 // If there is a single "increment" side one can use the macro
53 // STATS_DECLTRACK with a custom message. If there are multiple increment
54 // sides, STATS_DECL and STATS_TRACK can also be used separatly.
55 //
56 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME)                                     \
57   ("Number of " #TYPE " marked '" #NAME "'")
58 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
59 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
60 #define STATS_DECL(NAME, TYPE, MSG)                                            \
61   STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
62 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
63 #define STATS_DECLTRACK(NAME, TYPE, MSG)                                       \
64   {                                                                            \
65     STATS_DECL(NAME, TYPE, MSG)                                                \
66     STATS_TRACK(NAME, TYPE)                                                    \
67   }
68 #define STATS_DECLTRACK_ARG_ATTR(NAME)                                         \
69   STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
70 #define STATS_DECLTRACK_CSARG_ATTR(NAME)                                       \
71   STATS_DECLTRACK(NAME, CSArguments,                                           \
72                   BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
73 #define STATS_DECLTRACK_FN_ATTR(NAME)                                          \
74   STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
75 #define STATS_DECLTRACK_CS_ATTR(NAME)                                          \
76   STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
77 #define STATS_DECLTRACK_FNRET_ATTR(NAME)                                       \
78   STATS_DECLTRACK(NAME, FunctionReturn,                                        \
79                   BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
80 #define STATS_DECLTRACK_CSRET_ATTR(NAME)                                       \
81   STATS_DECLTRACK(NAME, CSReturn,                                              \
82                   BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
83 #define STATS_DECLTRACK_FLOATING_ATTR(NAME)                                    \
84   STATS_DECLTRACK(NAME, Floating,                                              \
85                   ("Number of floating values known to be '" #NAME "'"))
86 
87 // Specialization of the operator<< for abstract attributes subclasses. This
88 // disambiguates situations where multiple operators are applicable.
89 namespace llvm {
90 #define PIPE_OPERATOR(CLASS)                                                   \
91   raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) {                  \
92     return OS << static_cast<const AbstractAttribute &>(AA);                   \
93   }
94 
95 PIPE_OPERATOR(AAIsDead)
96 PIPE_OPERATOR(AANoUnwind)
97 PIPE_OPERATOR(AANoSync)
98 PIPE_OPERATOR(AANoRecurse)
99 PIPE_OPERATOR(AAWillReturn)
100 PIPE_OPERATOR(AANoReturn)
101 PIPE_OPERATOR(AAReturnedValues)
102 PIPE_OPERATOR(AANonNull)
103 PIPE_OPERATOR(AANoAlias)
104 PIPE_OPERATOR(AADereferenceable)
105 PIPE_OPERATOR(AAAlign)
106 PIPE_OPERATOR(AANoCapture)
107 PIPE_OPERATOR(AAValueSimplify)
108 PIPE_OPERATOR(AANoFree)
109 PIPE_OPERATOR(AAHeapToStack)
110 PIPE_OPERATOR(AAReachability)
111 PIPE_OPERATOR(AAMemoryBehavior)
112 PIPE_OPERATOR(AAMemoryLocation)
113 PIPE_OPERATOR(AAValueConstantRange)
114 PIPE_OPERATOR(AAPrivatizablePtr)
115 
116 #undef PIPE_OPERATOR
117 } // namespace llvm
118 
119 namespace {
120 
121 static Optional<ConstantInt *>
122 getAssumedConstantInt(Attributor &A, const Value &V,
123                       const AbstractAttribute &AA,
124                       bool &UsedAssumedInformation) {
125   Optional<Constant *> C = A.getAssumedConstant(V, AA, UsedAssumedInformation);
126   if (C.hasValue())
127     return dyn_cast_or_null<ConstantInt>(C.getValue());
128   return llvm::None;
129 }
130 
131 /// Get pointer operand of memory accessing instruction. If \p I is
132 /// not a memory accessing instruction, return nullptr. If \p AllowVolatile,
133 /// is set to false and the instruction is volatile, return nullptr.
134 static const Value *getPointerOperand(const Instruction *I,
135                                       bool AllowVolatile) {
136   if (auto *LI = dyn_cast<LoadInst>(I)) {
137     if (!AllowVolatile && LI->isVolatile())
138       return nullptr;
139     return LI->getPointerOperand();
140   }
141 
142   if (auto *SI = dyn_cast<StoreInst>(I)) {
143     if (!AllowVolatile && SI->isVolatile())
144       return nullptr;
145     return SI->getPointerOperand();
146   }
147 
148   if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) {
149     if (!AllowVolatile && CXI->isVolatile())
150       return nullptr;
151     return CXI->getPointerOperand();
152   }
153 
154   if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) {
155     if (!AllowVolatile && RMWI->isVolatile())
156       return nullptr;
157     return RMWI->getPointerOperand();
158   }
159 
160   return nullptr;
161 }
162 
163 /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and
164 /// advanced by \p Offset bytes. To aid later analysis the method tries to build
165 /// getelement pointer instructions that traverse the natural type of \p Ptr if
166 /// possible. If that fails, the remaining offset is adjusted byte-wise, hence
167 /// through a cast to i8*.
168 ///
169 /// TODO: This could probably live somewhere more prominantly if it doesn't
170 ///       already exist.
171 static Value *constructPointer(Type *ResTy, Value *Ptr, int64_t Offset,
172                                IRBuilder<NoFolder> &IRB, const DataLayout &DL) {
173   assert(Offset >= 0 && "Negative offset not supported yet!");
174   LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset
175                     << "-bytes as " << *ResTy << "\n");
176 
177   // The initial type we are trying to traverse to get nice GEPs.
178   Type *Ty = Ptr->getType();
179 
180   SmallVector<Value *, 4> Indices;
181   std::string GEPName = Ptr->getName().str();
182   while (Offset) {
183     uint64_t Idx, Rem;
184 
185     if (auto *STy = dyn_cast<StructType>(Ty)) {
186       const StructLayout *SL = DL.getStructLayout(STy);
187       if (int64_t(SL->getSizeInBytes()) < Offset)
188         break;
189       Idx = SL->getElementContainingOffset(Offset);
190       assert(Idx < STy->getNumElements() && "Offset calculation error!");
191       Rem = Offset - SL->getElementOffset(Idx);
192       Ty = STy->getElementType(Idx);
193     } else if (auto *PTy = dyn_cast<PointerType>(Ty)) {
194       Ty = PTy->getElementType();
195       if (!Ty->isSized())
196         break;
197       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
198       assert(ElementSize && "Expected type with size!");
199       Idx = Offset / ElementSize;
200       Rem = Offset % ElementSize;
201     } else {
202       // Non-aggregate type, we cast and make byte-wise progress now.
203       break;
204     }
205 
206     LLVM_DEBUG(errs() << "Ty: " << *Ty << " Offset: " << Offset
207                       << " Idx: " << Idx << " Rem: " << Rem << "\n");
208 
209     GEPName += "." + std::to_string(Idx);
210     Indices.push_back(ConstantInt::get(IRB.getInt32Ty(), Idx));
211     Offset = Rem;
212   }
213 
214   // Create a GEP if we collected indices above.
215   if (Indices.size())
216     Ptr = IRB.CreateGEP(Ptr, Indices, GEPName);
217 
218   // If an offset is left we use byte-wise adjustment.
219   if (Offset) {
220     Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy());
221     Ptr = IRB.CreateGEP(Ptr, IRB.getInt32(Offset),
222                         GEPName + ".b" + Twine(Offset));
223   }
224 
225   // Ensure the result has the requested type.
226   Ptr = IRB.CreateBitOrPointerCast(Ptr, ResTy, Ptr->getName() + ".cast");
227 
228   LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n");
229   return Ptr;
230 }
231 
232 /// Recursively visit all values that might become \p IRP at some point. This
233 /// will be done by looking through cast instructions, selects, phis, and calls
234 /// with the "returned" attribute. Once we cannot look through the value any
235 /// further, the callback \p VisitValueCB is invoked and passed the current
236 /// value, the \p State, and a flag to indicate if we stripped anything.
237 /// Stripped means that we unpacked the value associated with \p IRP at least
238 /// once. Note that the value used for the callback may still be the value
239 /// associated with \p IRP (due to PHIs). To limit how much effort is invested,
240 /// we will never visit more values than specified by \p MaxValues.
241 template <typename AAType, typename StateTy>
242 static bool genericValueTraversal(
243     Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State,
244     function_ref<bool(Value &, const Instruction *, StateTy &, bool)>
245         VisitValueCB,
246     const Instruction *CtxI, int MaxValues = 16,
247     function_ref<Value *(Value *)> StripCB = nullptr) {
248 
249   const AAIsDead *LivenessAA = nullptr;
250   if (IRP.getAnchorScope())
251     LivenessAA = &A.getAAFor<AAIsDead>(
252         QueryingAA, IRPosition::function(*IRP.getAnchorScope()),
253         /* TrackDependence */ false);
254   bool AnyDead = false;
255 
256   using Item = std::pair<Value *, const Instruction *>;
257   SmallSet<Item, 16> Visited;
258   SmallVector<Item, 16> Worklist;
259   Worklist.push_back({&IRP.getAssociatedValue(), CtxI});
260 
261   int Iteration = 0;
262   do {
263     Item I = Worklist.pop_back_val();
264     Value *V = I.first;
265     CtxI = I.second;
266     if (StripCB)
267       V = StripCB(V);
268 
269     // Check if we should process the current value. To prevent endless
270     // recursion keep a record of the values we followed!
271     if (!Visited.insert(I).second)
272       continue;
273 
274     // Make sure we limit the compile time for complex expressions.
275     if (Iteration++ >= MaxValues)
276       return false;
277 
278     // Explicitly look through calls with a "returned" attribute if we do
279     // not have a pointer as stripPointerCasts only works on them.
280     Value *NewV = nullptr;
281     if (V->getType()->isPointerTy()) {
282       NewV = V->stripPointerCasts();
283     } else {
284       auto *CB = dyn_cast<CallBase>(V);
285       if (CB && CB->getCalledFunction()) {
286         for (Argument &Arg : CB->getCalledFunction()->args())
287           if (Arg.hasReturnedAttr()) {
288             NewV = CB->getArgOperand(Arg.getArgNo());
289             break;
290           }
291       }
292     }
293     if (NewV && NewV != V) {
294       Worklist.push_back({NewV, CtxI});
295       continue;
296     }
297 
298     // Look through select instructions, visit both potential values.
299     if (auto *SI = dyn_cast<SelectInst>(V)) {
300       Worklist.push_back({SI->getTrueValue(), CtxI});
301       Worklist.push_back({SI->getFalseValue(), CtxI});
302       continue;
303     }
304 
305     // Look through phi nodes, visit all live operands.
306     if (auto *PHI = dyn_cast<PHINode>(V)) {
307       assert(LivenessAA &&
308              "Expected liveness in the presence of instructions!");
309       for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
310         BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
311         if (A.isAssumedDead(*IncomingBB->getTerminator(), &QueryingAA,
312                             LivenessAA,
313                             /* CheckBBLivenessOnly */ true)) {
314           AnyDead = true;
315           continue;
316         }
317         Worklist.push_back(
318             {PHI->getIncomingValue(u), IncomingBB->getTerminator()});
319       }
320       continue;
321     }
322 
323     // Once a leaf is reached we inform the user through the callback.
324     if (!VisitValueCB(*V, CtxI, State, Iteration > 1))
325       return false;
326   } while (!Worklist.empty());
327 
328   // If we actually used liveness information so we have to record a dependence.
329   if (AnyDead)
330     A.recordDependence(*LivenessAA, QueryingAA, DepClassTy::OPTIONAL);
331 
332   // All values have been visited.
333   return true;
334 }
335 
336 static const Value *
337 getBasePointerOfAccessPointerOperand(const Instruction *I, int64_t &BytesOffset,
338                                      const DataLayout &DL,
339                                      bool AllowNonInbounds = false) {
340   const Value *Ptr = getPointerOperand(I, /* AllowVolatile */ false);
341   if (!Ptr)
342     return nullptr;
343 
344   return GetPointerBaseWithConstantOffset(Ptr, BytesOffset, DL,
345                                           AllowNonInbounds);
346 }
347 
348 /// Helper function to clamp a state \p S of type \p StateType with the
349 /// information in \p R and indicate/return if \p S did change (as-in update is
350 /// required to be run again).
351 template <typename StateType>
352 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) {
353   auto Assumed = S.getAssumed();
354   S ^= R;
355   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
356                                    : ChangeStatus::CHANGED;
357 }
358 
359 /// Clamp the information known for all returned values of a function
360 /// (identified by \p QueryingAA) into \p S.
361 template <typename AAType, typename StateType = typename AAType::StateType>
362 static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA,
363                                      StateType &S) {
364   LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
365                     << QueryingAA << " into " << S << "\n");
366 
367   assert((QueryingAA.getIRPosition().getPositionKind() ==
368               IRPosition::IRP_RETURNED ||
369           QueryingAA.getIRPosition().getPositionKind() ==
370               IRPosition::IRP_CALL_SITE_RETURNED) &&
371          "Can only clamp returned value states for a function returned or call "
372          "site returned position!");
373 
374   // Use an optional state as there might not be any return values and we want
375   // to join (IntegerState::operator&) the state of all there are.
376   Optional<StateType> T;
377 
378   // Callback for each possibly returned value.
379   auto CheckReturnValue = [&](Value &RV) -> bool {
380     const IRPosition &RVPos = IRPosition::value(RV);
381     const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos);
382     LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr()
383                       << " @ " << RVPos << "\n");
384     const StateType &AAS = static_cast<const StateType &>(AA.getState());
385     if (T.hasValue())
386       *T &= AAS;
387     else
388       T = AAS;
389     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
390                       << "\n");
391     return T->isValidState();
392   };
393 
394   if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
395     S.indicatePessimisticFixpoint();
396   else if (T.hasValue())
397     S ^= *T;
398 }
399 
400 /// Helper class to compose two generic deduction
401 template <typename AAType, typename Base, typename StateType,
402           template <typename...> class F, template <typename...> class G>
403 struct AAComposeTwoGenericDeduction
404     : public F<AAType, G<AAType, Base, StateType>, StateType> {
405   AAComposeTwoGenericDeduction(const IRPosition &IRP, Attributor &A)
406       : F<AAType, G<AAType, Base, StateType>, StateType>(IRP, A) {}
407 
408   void initialize(Attributor &A) override {
409     F<AAType, G<AAType, Base, StateType>, StateType>::initialize(A);
410     G<AAType, Base, StateType>::initialize(A);
411   }
412 
413   /// See AbstractAttribute::updateImpl(...).
414   ChangeStatus updateImpl(Attributor &A) override {
415     ChangeStatus ChangedF =
416         F<AAType, G<AAType, Base, StateType>, StateType>::updateImpl(A);
417     ChangeStatus ChangedG = G<AAType, Base, StateType>::updateImpl(A);
418     return ChangedF | ChangedG;
419   }
420 };
421 
422 /// Helper class for generic deduction: return value -> returned position.
423 template <typename AAType, typename Base,
424           typename StateType = typename Base::StateType>
425 struct AAReturnedFromReturnedValues : public Base {
426   AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A)
427       : Base(IRP, A) {}
428 
429   /// See AbstractAttribute::updateImpl(...).
430   ChangeStatus updateImpl(Attributor &A) override {
431     StateType S(StateType::getBestState(this->getState()));
432     clampReturnedValueStates<AAType, StateType>(A, *this, S);
433     // TODO: If we know we visited all returned values, thus no are assumed
434     // dead, we can take the known information from the state T.
435     return clampStateAndIndicateChange<StateType>(this->getState(), S);
436   }
437 };
438 
439 /// Clamp the information known at all call sites for a given argument
440 /// (identified by \p QueryingAA) into \p S.
441 template <typename AAType, typename StateType = typename AAType::StateType>
442 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
443                                         StateType &S) {
444   LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
445                     << QueryingAA << " into " << S << "\n");
446 
447   assert(QueryingAA.getIRPosition().getPositionKind() ==
448              IRPosition::IRP_ARGUMENT &&
449          "Can only clamp call site argument states for an argument position!");
450 
451   // Use an optional state as there might not be any return values and we want
452   // to join (IntegerState::operator&) the state of all there are.
453   Optional<StateType> T;
454 
455   // The argument number which is also the call site argument number.
456   unsigned ArgNo = QueryingAA.getIRPosition().getArgNo();
457 
458   auto CallSiteCheck = [&](AbstractCallSite ACS) {
459     const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
460     // Check if a coresponding argument was found or if it is on not associated
461     // (which can happen for callback calls).
462     if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
463       return false;
464 
465     const AAType &AA = A.getAAFor<AAType>(QueryingAA, ACSArgPos);
466     LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction()
467                       << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n");
468     const StateType &AAS = static_cast<const StateType &>(AA.getState());
469     if (T.hasValue())
470       *T &= AAS;
471     else
472       T = AAS;
473     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
474                       << "\n");
475     return T->isValidState();
476   };
477 
478   bool AllCallSitesKnown;
479   if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true,
480                               AllCallSitesKnown))
481     S.indicatePessimisticFixpoint();
482   else if (T.hasValue())
483     S ^= *T;
484 }
485 
486 /// Helper class for generic deduction: call site argument -> argument position.
487 template <typename AAType, typename Base,
488           typename StateType = typename AAType::StateType>
489 struct AAArgumentFromCallSiteArguments : public Base {
490   AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A)
491       : Base(IRP, A) {}
492 
493   /// See AbstractAttribute::updateImpl(...).
494   ChangeStatus updateImpl(Attributor &A) override {
495     StateType S(StateType::getBestState(this->getState()));
496     clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
497     // TODO: If we know we visited all incoming values, thus no are assumed
498     // dead, we can take the known information from the state T.
499     return clampStateAndIndicateChange<StateType>(this->getState(), S);
500   }
501 };
502 
503 /// Helper class for generic replication: function returned -> cs returned.
504 template <typename AAType, typename Base,
505           typename StateType = typename Base::StateType>
506 struct AACallSiteReturnedFromReturned : public Base {
507   AACallSiteReturnedFromReturned(const IRPosition &IRP, Attributor &A)
508       : Base(IRP, A) {}
509 
510   /// See AbstractAttribute::updateImpl(...).
511   ChangeStatus updateImpl(Attributor &A) override {
512     assert(this->getIRPosition().getPositionKind() ==
513                IRPosition::IRP_CALL_SITE_RETURNED &&
514            "Can only wrap function returned positions for call site returned "
515            "positions!");
516     auto &S = this->getState();
517 
518     const Function *AssociatedFunction =
519         this->getIRPosition().getAssociatedFunction();
520     if (!AssociatedFunction)
521       return S.indicatePessimisticFixpoint();
522 
523     IRPosition FnPos = IRPosition::returned(*AssociatedFunction);
524     const AAType &AA = A.getAAFor<AAType>(*this, FnPos);
525     return clampStateAndIndicateChange(
526         S, static_cast<const StateType &>(AA.getState()));
527   }
528 };
529 
530 /// Helper class for generic deduction using must-be-executed-context
531 /// Base class is required to have `followUse` method.
532 
533 /// bool followUse(Attributor &A, const Use *U, const Instruction *I)
534 /// U - Underlying use.
535 /// I - The user of the \p U.
536 /// `followUse` returns true if the value should be tracked transitively.
537 
538 template <typename AAType, typename Base,
539           typename StateType = typename AAType::StateType>
540 struct AAFromMustBeExecutedContext : public Base {
541   AAFromMustBeExecutedContext(const IRPosition &IRP, Attributor &A)
542       : Base(IRP, A) {}
543 
544   void initialize(Attributor &A) override {
545     Base::initialize(A);
546     const IRPosition &IRP = this->getIRPosition();
547     Instruction *CtxI = IRP.getCtxI();
548 
549     if (!CtxI)
550       return;
551 
552     for (const Use &U : IRP.getAssociatedValue().uses())
553       Uses.insert(&U);
554   }
555 
556   /// Helper function to accumulate uses.
557   void followUsesInContext(Attributor &A,
558                            MustBeExecutedContextExplorer &Explorer,
559                            const Instruction *CtxI,
560                            SetVector<const Use *> &Uses, StateType &State) {
561     auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI);
562     for (unsigned u = 0; u < Uses.size(); ++u) {
563       const Use *U = Uses[u];
564       if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
565         bool Found = Explorer.findInContextOf(UserI, EIt, EEnd);
566         if (Found && Base::followUse(A, U, UserI, State))
567           for (const Use &Us : UserI->uses())
568             Uses.insert(&Us);
569       }
570     }
571   }
572 
573   /// See AbstractAttribute::updateImpl(...).
574   ChangeStatus updateImpl(Attributor &A) override {
575     auto BeforeState = this->getState();
576     auto &S = this->getState();
577     Instruction *CtxI = this->getIRPosition().getCtxI();
578     if (!CtxI)
579       return ChangeStatus::UNCHANGED;
580 
581     MustBeExecutedContextExplorer &Explorer =
582         A.getInfoCache().getMustBeExecutedContextExplorer();
583 
584     followUsesInContext(A, Explorer, CtxI, Uses, S);
585 
586     if (this->isAtFixpoint())
587       return ChangeStatus::CHANGED;
588 
589     SmallVector<const BranchInst *, 4> BrInsts;
590     auto Pred = [&](const Instruction *I) {
591       if (const BranchInst *Br = dyn_cast<BranchInst>(I))
592         if (Br->isConditional())
593           BrInsts.push_back(Br);
594       return true;
595     };
596 
597     // Here, accumulate conditional branch instructions in the context. We
598     // explore the child paths and collect the known states. The disjunction of
599     // those states can be merged to its own state. Let ParentState_i be a state
600     // to indicate the known information for an i-th branch instruction in the
601     // context. ChildStates are created for its successors respectively.
602     //
603     // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1}
604     // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2}
605     //      ...
606     // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m}
607     //
608     // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m
609     //
610     // FIXME: Currently, recursive branches are not handled. For example, we
611     // can't deduce that ptr must be dereferenced in below function.
612     //
613     // void f(int a, int c, int *ptr) {
614     //    if(a)
615     //      if (b) {
616     //        *ptr = 0;
617     //      } else {
618     //        *ptr = 1;
619     //      }
620     //    else {
621     //      if (b) {
622     //        *ptr = 0;
623     //      } else {
624     //        *ptr = 1;
625     //      }
626     //    }
627     // }
628 
629     Explorer.checkForAllContext(CtxI, Pred);
630     for (const BranchInst *Br : BrInsts) {
631       StateType ParentState;
632 
633       // The known state of the parent state is a conjunction of children's
634       // known states so it is initialized with a best state.
635       ParentState.indicateOptimisticFixpoint();
636 
637       for (const BasicBlock *BB : Br->successors()) {
638         StateType ChildState;
639 
640         size_t BeforeSize = Uses.size();
641         followUsesInContext(A, Explorer, &BB->front(), Uses, ChildState);
642 
643         // Erase uses which only appear in the child.
644         for (auto It = Uses.begin() + BeforeSize; It != Uses.end();)
645           It = Uses.erase(It);
646 
647         ParentState &= ChildState;
648       }
649 
650       // Use only known state.
651       S += ParentState;
652     }
653 
654     return BeforeState == S ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED;
655   }
656 
657 private:
658   /// Container for (transitive) uses of the associated value.
659   SetVector<const Use *> Uses;
660 };
661 
662 template <typename AAType, typename Base,
663           typename StateType = typename AAType::StateType>
664 using AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext =
665     AAComposeTwoGenericDeduction<AAType, Base, StateType,
666                                  AAFromMustBeExecutedContext,
667                                  AAArgumentFromCallSiteArguments>;
668 
669 template <typename AAType, typename Base,
670           typename StateType = typename AAType::StateType>
671 using AACallSiteReturnedFromReturnedAndMustBeExecutedContext =
672     AAComposeTwoGenericDeduction<AAType, Base, StateType,
673                                  AAFromMustBeExecutedContext,
674                                  AACallSiteReturnedFromReturned>;
675 
676 /// -----------------------NoUnwind Function Attribute--------------------------
677 
678 struct AANoUnwindImpl : AANoUnwind {
679   AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {}
680 
681   const std::string getAsStr() const override {
682     return getAssumed() ? "nounwind" : "may-unwind";
683   }
684 
685   /// See AbstractAttribute::updateImpl(...).
686   ChangeStatus updateImpl(Attributor &A) override {
687     auto Opcodes = {
688         (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
689         (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
690         (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
691 
692     auto CheckForNoUnwind = [&](Instruction &I) {
693       if (!I.mayThrow())
694         return true;
695 
696       if (const auto *CB = dyn_cast<CallBase>(&I)) {
697         const auto &NoUnwindAA =
698             A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(*CB));
699         return NoUnwindAA.isAssumedNoUnwind();
700       }
701       return false;
702     };
703 
704     if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes))
705       return indicatePessimisticFixpoint();
706 
707     return ChangeStatus::UNCHANGED;
708   }
709 };
710 
711 struct AANoUnwindFunction final : public AANoUnwindImpl {
712   AANoUnwindFunction(const IRPosition &IRP, Attributor &A)
713       : AANoUnwindImpl(IRP, A) {}
714 
715   /// See AbstractAttribute::trackStatistics()
716   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
717 };
718 
719 /// NoUnwind attribute deduction for a call sites.
720 struct AANoUnwindCallSite final : AANoUnwindImpl {
721   AANoUnwindCallSite(const IRPosition &IRP, Attributor &A)
722       : AANoUnwindImpl(IRP, A) {}
723 
724   /// See AbstractAttribute::initialize(...).
725   void initialize(Attributor &A) override {
726     AANoUnwindImpl::initialize(A);
727     Function *F = getAssociatedFunction();
728     if (!F)
729       indicatePessimisticFixpoint();
730   }
731 
732   /// See AbstractAttribute::updateImpl(...).
733   ChangeStatus updateImpl(Attributor &A) override {
734     // TODO: Once we have call site specific value information we can provide
735     //       call site specific liveness information and then it makes
736     //       sense to specialize attributes for call sites arguments instead of
737     //       redirecting requests to the callee argument.
738     Function *F = getAssociatedFunction();
739     const IRPosition &FnPos = IRPosition::function(*F);
740     auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos);
741     return clampStateAndIndicateChange(
742         getState(),
743         static_cast<const AANoUnwind::StateType &>(FnAA.getState()));
744   }
745 
746   /// See AbstractAttribute::trackStatistics()
747   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
748 };
749 
750 /// --------------------- Function Return Values -------------------------------
751 
752 /// "Attribute" that collects all potential returned values and the return
753 /// instructions that they arise from.
754 ///
755 /// If there is a unique returned value R, the manifest method will:
756 ///   - mark R with the "returned" attribute, if R is an argument.
757 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
758 
759   /// Mapping of values potentially returned by the associated function to the
760   /// return instructions that might return them.
761   MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues;
762 
763   /// Mapping to remember the number of returned values for a call site such
764   /// that we can avoid updates if nothing changed.
765   DenseMap<const CallBase *, unsigned> NumReturnedValuesPerKnownAA;
766 
767   /// Set of unresolved calls returned by the associated function.
768   SmallSetVector<CallBase *, 4> UnresolvedCalls;
769 
770   /// State flags
771   ///
772   ///{
773   bool IsFixed = false;
774   bool IsValidState = true;
775   ///}
776 
777 public:
778   AAReturnedValuesImpl(const IRPosition &IRP, Attributor &A)
779       : AAReturnedValues(IRP, A) {}
780 
781   /// See AbstractAttribute::initialize(...).
782   void initialize(Attributor &A) override {
783     // Reset the state.
784     IsFixed = false;
785     IsValidState = true;
786     ReturnedValues.clear();
787 
788     Function *F = getAssociatedFunction();
789     if (!F) {
790       indicatePessimisticFixpoint();
791       return;
792     }
793     assert(!F->getReturnType()->isVoidTy() &&
794            "Did not expect a void return type!");
795 
796     // The map from instruction opcodes to those instructions in the function.
797     auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
798 
799     // Look through all arguments, if one is marked as returned we are done.
800     for (Argument &Arg : F->args()) {
801       if (Arg.hasReturnedAttr()) {
802         auto &ReturnInstSet = ReturnedValues[&Arg];
803         if (auto *Insts = OpcodeInstMap.lookup(Instruction::Ret))
804           for (Instruction *RI : *Insts)
805             ReturnInstSet.insert(cast<ReturnInst>(RI));
806 
807         indicateOptimisticFixpoint();
808         return;
809       }
810     }
811 
812     if (!A.isFunctionIPOAmendable(*F))
813       indicatePessimisticFixpoint();
814   }
815 
816   /// See AbstractAttribute::manifest(...).
817   ChangeStatus manifest(Attributor &A) override;
818 
819   /// See AbstractAttribute::getState(...).
820   AbstractState &getState() override { return *this; }
821 
822   /// See AbstractAttribute::getState(...).
823   const AbstractState &getState() const override { return *this; }
824 
825   /// See AbstractAttribute::updateImpl(Attributor &A).
826   ChangeStatus updateImpl(Attributor &A) override;
827 
828   llvm::iterator_range<iterator> returned_values() override {
829     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
830   }
831 
832   llvm::iterator_range<const_iterator> returned_values() const override {
833     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
834   }
835 
836   const SmallSetVector<CallBase *, 4> &getUnresolvedCalls() const override {
837     return UnresolvedCalls;
838   }
839 
840   /// Return the number of potential return values, -1 if unknown.
841   size_t getNumReturnValues() const override {
842     return isValidState() ? ReturnedValues.size() : -1;
843   }
844 
845   /// Return an assumed unique return value if a single candidate is found. If
846   /// there cannot be one, return a nullptr. If it is not clear yet, return the
847   /// Optional::NoneType.
848   Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
849 
850   /// See AbstractState::checkForAllReturnedValues(...).
851   bool checkForAllReturnedValuesAndReturnInsts(
852       function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
853       const override;
854 
855   /// Pretty print the attribute similar to the IR representation.
856   const std::string getAsStr() const override;
857 
858   /// See AbstractState::isAtFixpoint().
859   bool isAtFixpoint() const override { return IsFixed; }
860 
861   /// See AbstractState::isValidState().
862   bool isValidState() const override { return IsValidState; }
863 
864   /// See AbstractState::indicateOptimisticFixpoint(...).
865   ChangeStatus indicateOptimisticFixpoint() override {
866     IsFixed = true;
867     return ChangeStatus::UNCHANGED;
868   }
869 
870   ChangeStatus indicatePessimisticFixpoint() override {
871     IsFixed = true;
872     IsValidState = false;
873     return ChangeStatus::CHANGED;
874   }
875 };
876 
877 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
878   ChangeStatus Changed = ChangeStatus::UNCHANGED;
879 
880   // Bookkeeping.
881   assert(isValidState());
882   STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
883                   "Number of function with known return values");
884 
885   // Check if we have an assumed unique return value that we could manifest.
886   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
887 
888   if (!UniqueRV.hasValue() || !UniqueRV.getValue())
889     return Changed;
890 
891   // Bookkeeping.
892   STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
893                   "Number of function with unique return");
894 
895   // Callback to replace the uses of CB with the constant C.
896   auto ReplaceCallSiteUsersWith = [&A](CallBase &CB, Constant &C) {
897     if (CB.getNumUses() == 0)
898       return ChangeStatus::UNCHANGED;
899     if (A.changeValueAfterManifest(CB, C))
900       return ChangeStatus::CHANGED;
901     return ChangeStatus::UNCHANGED;
902   };
903 
904   // If the assumed unique return value is an argument, annotate it.
905   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
906     // TODO: This should be handled differently!
907     this->AnchorVal = UniqueRVArg;
908     this->KindOrArgNo = UniqueRVArg->getArgNo();
909     Changed = IRAttribute::manifest(A);
910   } else if (auto *RVC = dyn_cast<Constant>(UniqueRV.getValue())) {
911     // We can replace the returned value with the unique returned constant.
912     Value &AnchorValue = getAnchorValue();
913     if (Function *F = dyn_cast<Function>(&AnchorValue)) {
914       for (const Use &U : F->uses())
915         if (CallBase *CB = dyn_cast<CallBase>(U.getUser()))
916           if (CB->isCallee(&U)) {
917             Constant *RVCCast =
918                 CB->getType() == RVC->getType()
919                     ? RVC
920                     : ConstantExpr::getTruncOrBitCast(RVC, CB->getType());
921             Changed = ReplaceCallSiteUsersWith(*CB, *RVCCast) | Changed;
922           }
923     } else {
924       assert(isa<CallBase>(AnchorValue) &&
925              "Expcected a function or call base anchor!");
926       Constant *RVCCast =
927           AnchorValue.getType() == RVC->getType()
928               ? RVC
929               : ConstantExpr::getTruncOrBitCast(RVC, AnchorValue.getType());
930       Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVCCast);
931     }
932     if (Changed == ChangeStatus::CHANGED)
933       STATS_DECLTRACK(UniqueConstantReturnValue, FunctionReturn,
934                       "Number of function returns replaced by constant return");
935   }
936 
937   return Changed;
938 }
939 
940 const std::string AAReturnedValuesImpl::getAsStr() const {
941   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
942          (isValidState() ? std::to_string(getNumReturnValues()) : "?") +
943          ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]";
944 }
945 
946 Optional<Value *>
947 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
948   // If checkForAllReturnedValues provides a unique value, ignoring potential
949   // undef values that can also be present, it is assumed to be the actual
950   // return value and forwarded to the caller of this method. If there are
951   // multiple, a nullptr is returned indicating there cannot be a unique
952   // returned value.
953   Optional<Value *> UniqueRV;
954 
955   auto Pred = [&](Value &RV) -> bool {
956     // If we found a second returned value and neither the current nor the saved
957     // one is an undef, there is no unique returned value. Undefs are special
958     // since we can pretend they have any value.
959     if (UniqueRV.hasValue() && UniqueRV != &RV &&
960         !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
961       UniqueRV = nullptr;
962       return false;
963     }
964 
965     // Do not overwrite a value with an undef.
966     if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
967       UniqueRV = &RV;
968 
969     return true;
970   };
971 
972   if (!A.checkForAllReturnedValues(Pred, *this))
973     UniqueRV = nullptr;
974 
975   return UniqueRV;
976 }
977 
978 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
979     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
980     const {
981   if (!isValidState())
982     return false;
983 
984   // Check all returned values but ignore call sites as long as we have not
985   // encountered an overdefined one during an update.
986   for (auto &It : ReturnedValues) {
987     Value *RV = It.first;
988 
989     CallBase *CB = dyn_cast<CallBase>(RV);
990     if (CB && !UnresolvedCalls.count(CB))
991       continue;
992 
993     if (!Pred(*RV, It.second))
994       return false;
995   }
996 
997   return true;
998 }
999 
1000 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
1001   size_t NumUnresolvedCalls = UnresolvedCalls.size();
1002   bool Changed = false;
1003 
1004   // State used in the value traversals starting in returned values.
1005   struct RVState {
1006     // The map in which we collect return values -> return instrs.
1007     decltype(ReturnedValues) &RetValsMap;
1008     // The flag to indicate a change.
1009     bool &Changed;
1010     // The return instrs we come from.
1011     SmallSetVector<ReturnInst *, 4> RetInsts;
1012   };
1013 
1014   // Callback for a leaf value returned by the associated function.
1015   auto VisitValueCB = [](Value &Val, const Instruction *, RVState &RVS,
1016                          bool) -> bool {
1017     auto Size = RVS.RetValsMap[&Val].size();
1018     RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end());
1019     bool Inserted = RVS.RetValsMap[&Val].size() != Size;
1020     RVS.Changed |= Inserted;
1021     LLVM_DEBUG({
1022       if (Inserted)
1023         dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val
1024                << " => " << RVS.RetInsts.size() << "\n";
1025     });
1026     return true;
1027   };
1028 
1029   // Helper method to invoke the generic value traversal.
1030   auto VisitReturnedValue = [&](Value &RV, RVState &RVS,
1031                                 const Instruction *CtxI) {
1032     IRPosition RetValPos = IRPosition::value(RV);
1033     return genericValueTraversal<AAReturnedValues, RVState>(
1034         A, RetValPos, *this, RVS, VisitValueCB, CtxI);
1035   };
1036 
1037   // Callback for all "return intructions" live in the associated function.
1038   auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) {
1039     ReturnInst &Ret = cast<ReturnInst>(I);
1040     RVState RVS({ReturnedValues, Changed, {}});
1041     RVS.RetInsts.insert(&Ret);
1042     return VisitReturnedValue(*Ret.getReturnValue(), RVS, &I);
1043   };
1044 
1045   // Start by discovering returned values from all live returned instructions in
1046   // the associated function.
1047   if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}))
1048     return indicatePessimisticFixpoint();
1049 
1050   // Once returned values "directly" present in the code are handled we try to
1051   // resolve returned calls.
1052   decltype(ReturnedValues) NewRVsMap;
1053   for (auto &It : ReturnedValues) {
1054     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first
1055                       << " by #" << It.second.size() << " RIs\n");
1056     CallBase *CB = dyn_cast<CallBase>(It.first);
1057     if (!CB || UnresolvedCalls.count(CB))
1058       continue;
1059 
1060     if (!CB->getCalledFunction()) {
1061       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
1062                         << "\n");
1063       UnresolvedCalls.insert(CB);
1064       continue;
1065     }
1066 
1067     // TODO: use the function scope once we have call site AAReturnedValues.
1068     const auto &RetValAA = A.getAAFor<AAReturnedValues>(
1069         *this, IRPosition::function(*CB->getCalledFunction()));
1070     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: "
1071                       << RetValAA << "\n");
1072 
1073     // Skip dead ends, thus if we do not know anything about the returned
1074     // call we mark it as unresolved and it will stay that way.
1075     if (!RetValAA.getState().isValidState()) {
1076       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB
1077                         << "\n");
1078       UnresolvedCalls.insert(CB);
1079       continue;
1080     }
1081 
1082     // Do not try to learn partial information. If the callee has unresolved
1083     // return values we will treat the call as unresolved/opaque.
1084     auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls();
1085     if (!RetValAAUnresolvedCalls.empty()) {
1086       UnresolvedCalls.insert(CB);
1087       continue;
1088     }
1089 
1090     // Now check if we can track transitively returned values. If possible, thus
1091     // if all return value can be represented in the current scope, do so.
1092     bool Unresolved = false;
1093     for (auto &RetValAAIt : RetValAA.returned_values()) {
1094       Value *RetVal = RetValAAIt.first;
1095       if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) ||
1096           isa<Constant>(RetVal))
1097         continue;
1098       // Anything that did not fit in the above categories cannot be resolved,
1099       // mark the call as unresolved.
1100       LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value "
1101                            "cannot be translated: "
1102                         << *RetVal << "\n");
1103       UnresolvedCalls.insert(CB);
1104       Unresolved = true;
1105       break;
1106     }
1107 
1108     if (Unresolved)
1109       continue;
1110 
1111     // Now track transitively returned values.
1112     unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB];
1113     if (NumRetAA == RetValAA.getNumReturnValues()) {
1114       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Skip call as it has not "
1115                            "changed since it was seen last\n");
1116       continue;
1117     }
1118     NumRetAA = RetValAA.getNumReturnValues();
1119 
1120     for (auto &RetValAAIt : RetValAA.returned_values()) {
1121       Value *RetVal = RetValAAIt.first;
1122       if (Argument *Arg = dyn_cast<Argument>(RetVal)) {
1123         // Arguments are mapped to call site operands and we begin the traversal
1124         // again.
1125         bool Unused = false;
1126         RVState RVS({NewRVsMap, Unused, RetValAAIt.second});
1127         VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS, CB);
1128         continue;
1129       } else if (isa<CallBase>(RetVal)) {
1130         // Call sites are resolved by the callee attribute over time, no need to
1131         // do anything for us.
1132         continue;
1133       } else if (isa<Constant>(RetVal)) {
1134         // Constants are valid everywhere, we can simply take them.
1135         NewRVsMap[RetVal].insert(It.second.begin(), It.second.end());
1136         continue;
1137       }
1138     }
1139   }
1140 
1141   // To avoid modifications to the ReturnedValues map while we iterate over it
1142   // we kept record of potential new entries in a copy map, NewRVsMap.
1143   for (auto &It : NewRVsMap) {
1144     assert(!It.second.empty() && "Entry does not add anything.");
1145     auto &ReturnInsts = ReturnedValues[It.first];
1146     for (ReturnInst *RI : It.second)
1147       if (ReturnInsts.insert(RI)) {
1148         LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
1149                           << *It.first << " => " << *RI << "\n");
1150         Changed = true;
1151       }
1152   }
1153 
1154   Changed |= (NumUnresolvedCalls != UnresolvedCalls.size());
1155   return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
1156 }
1157 
1158 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
1159   AAReturnedValuesFunction(const IRPosition &IRP, Attributor &A)
1160       : AAReturnedValuesImpl(IRP, A) {}
1161 
1162   /// See AbstractAttribute::trackStatistics()
1163   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
1164 };
1165 
1166 /// Returned values information for a call sites.
1167 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl {
1168   AAReturnedValuesCallSite(const IRPosition &IRP, Attributor &A)
1169       : AAReturnedValuesImpl(IRP, A) {}
1170 
1171   /// See AbstractAttribute::initialize(...).
1172   void initialize(Attributor &A) override {
1173     // TODO: Once we have call site specific value information we can provide
1174     //       call site specific liveness information and then it makes
1175     //       sense to specialize attributes for call sites instead of
1176     //       redirecting requests to the callee.
1177     llvm_unreachable("Abstract attributes for returned values are not "
1178                      "supported for call sites yet!");
1179   }
1180 
1181   /// See AbstractAttribute::updateImpl(...).
1182   ChangeStatus updateImpl(Attributor &A) override {
1183     return indicatePessimisticFixpoint();
1184   }
1185 
1186   /// See AbstractAttribute::trackStatistics()
1187   void trackStatistics() const override {}
1188 };
1189 
1190 /// ------------------------ NoSync Function Attribute -------------------------
1191 
1192 struct AANoSyncImpl : AANoSync {
1193   AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {}
1194 
1195   const std::string getAsStr() const override {
1196     return getAssumed() ? "nosync" : "may-sync";
1197   }
1198 
1199   /// See AbstractAttribute::updateImpl(...).
1200   ChangeStatus updateImpl(Attributor &A) override;
1201 
1202   /// Helper function used to determine whether an instruction is non-relaxed
1203   /// atomic. In other words, if an atomic instruction does not have unordered
1204   /// or monotonic ordering
1205   static bool isNonRelaxedAtomic(Instruction *I);
1206 
1207   /// Helper function used to determine whether an instruction is volatile.
1208   static bool isVolatile(Instruction *I);
1209 
1210   /// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
1211   /// memset).
1212   static bool isNoSyncIntrinsic(Instruction *I);
1213 };
1214 
1215 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) {
1216   if (!I->isAtomic())
1217     return false;
1218 
1219   AtomicOrdering Ordering;
1220   switch (I->getOpcode()) {
1221   case Instruction::AtomicRMW:
1222     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
1223     break;
1224   case Instruction::Store:
1225     Ordering = cast<StoreInst>(I)->getOrdering();
1226     break;
1227   case Instruction::Load:
1228     Ordering = cast<LoadInst>(I)->getOrdering();
1229     break;
1230   case Instruction::Fence: {
1231     auto *FI = cast<FenceInst>(I);
1232     if (FI->getSyncScopeID() == SyncScope::SingleThread)
1233       return false;
1234     Ordering = FI->getOrdering();
1235     break;
1236   }
1237   case Instruction::AtomicCmpXchg: {
1238     AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
1239     AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
1240     // Only if both are relaxed, than it can be treated as relaxed.
1241     // Otherwise it is non-relaxed.
1242     if (Success != AtomicOrdering::Unordered &&
1243         Success != AtomicOrdering::Monotonic)
1244       return true;
1245     if (Failure != AtomicOrdering::Unordered &&
1246         Failure != AtomicOrdering::Monotonic)
1247       return true;
1248     return false;
1249   }
1250   default:
1251     llvm_unreachable(
1252         "New atomic operations need to be known in the attributor.");
1253   }
1254 
1255   // Relaxed.
1256   if (Ordering == AtomicOrdering::Unordered ||
1257       Ordering == AtomicOrdering::Monotonic)
1258     return false;
1259   return true;
1260 }
1261 
1262 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
1263 /// FIXME: We should ipmrove the handling of intrinsics.
1264 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) {
1265   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1266     switch (II->getIntrinsicID()) {
1267     /// Element wise atomic memory intrinsics are can only be unordered,
1268     /// therefore nosync.
1269     case Intrinsic::memset_element_unordered_atomic:
1270     case Intrinsic::memmove_element_unordered_atomic:
1271     case Intrinsic::memcpy_element_unordered_atomic:
1272       return true;
1273     case Intrinsic::memset:
1274     case Intrinsic::memmove:
1275     case Intrinsic::memcpy:
1276       if (!cast<MemIntrinsic>(II)->isVolatile())
1277         return true;
1278       return false;
1279     default:
1280       return false;
1281     }
1282   }
1283   return false;
1284 }
1285 
1286 bool AANoSyncImpl::isVolatile(Instruction *I) {
1287   assert(!isa<CallBase>(I) && "Calls should not be checked here");
1288 
1289   switch (I->getOpcode()) {
1290   case Instruction::AtomicRMW:
1291     return cast<AtomicRMWInst>(I)->isVolatile();
1292   case Instruction::Store:
1293     return cast<StoreInst>(I)->isVolatile();
1294   case Instruction::Load:
1295     return cast<LoadInst>(I)->isVolatile();
1296   case Instruction::AtomicCmpXchg:
1297     return cast<AtomicCmpXchgInst>(I)->isVolatile();
1298   default:
1299     return false;
1300   }
1301 }
1302 
1303 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
1304 
1305   auto CheckRWInstForNoSync = [&](Instruction &I) {
1306     /// We are looking for volatile instructions or Non-Relaxed atomics.
1307     /// FIXME: We should improve the handling of intrinsics.
1308 
1309     if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
1310       return true;
1311 
1312     if (const auto *CB = dyn_cast<CallBase>(&I)) {
1313       if (CB->hasFnAttr(Attribute::NoSync))
1314         return true;
1315 
1316       const auto &NoSyncAA =
1317           A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(*CB));
1318       if (NoSyncAA.isAssumedNoSync())
1319         return true;
1320       return false;
1321     }
1322 
1323     if (!isVolatile(&I) && !isNonRelaxedAtomic(&I))
1324       return true;
1325 
1326     return false;
1327   };
1328 
1329   auto CheckForNoSync = [&](Instruction &I) {
1330     // At this point we handled all read/write effects and they are all
1331     // nosync, so they can be skipped.
1332     if (I.mayReadOrWriteMemory())
1333       return true;
1334 
1335     // non-convergent and readnone imply nosync.
1336     return !cast<CallBase>(I).isConvergent();
1337   };
1338 
1339   if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) ||
1340       !A.checkForAllCallLikeInstructions(CheckForNoSync, *this))
1341     return indicatePessimisticFixpoint();
1342 
1343   return ChangeStatus::UNCHANGED;
1344 }
1345 
1346 struct AANoSyncFunction final : public AANoSyncImpl {
1347   AANoSyncFunction(const IRPosition &IRP, Attributor &A)
1348       : AANoSyncImpl(IRP, A) {}
1349 
1350   /// See AbstractAttribute::trackStatistics()
1351   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
1352 };
1353 
1354 /// NoSync attribute deduction for a call sites.
1355 struct AANoSyncCallSite final : AANoSyncImpl {
1356   AANoSyncCallSite(const IRPosition &IRP, Attributor &A)
1357       : AANoSyncImpl(IRP, A) {}
1358 
1359   /// See AbstractAttribute::initialize(...).
1360   void initialize(Attributor &A) override {
1361     AANoSyncImpl::initialize(A);
1362     Function *F = getAssociatedFunction();
1363     if (!F)
1364       indicatePessimisticFixpoint();
1365   }
1366 
1367   /// See AbstractAttribute::updateImpl(...).
1368   ChangeStatus updateImpl(Attributor &A) override {
1369     // TODO: Once we have call site specific value information we can provide
1370     //       call site specific liveness information and then it makes
1371     //       sense to specialize attributes for call sites arguments instead of
1372     //       redirecting requests to the callee argument.
1373     Function *F = getAssociatedFunction();
1374     const IRPosition &FnPos = IRPosition::function(*F);
1375     auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos);
1376     return clampStateAndIndicateChange(
1377         getState(), static_cast<const AANoSync::StateType &>(FnAA.getState()));
1378   }
1379 
1380   /// See AbstractAttribute::trackStatistics()
1381   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
1382 };
1383 
1384 /// ------------------------ No-Free Attributes ----------------------------
1385 
1386 struct AANoFreeImpl : public AANoFree {
1387   AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {}
1388 
1389   /// See AbstractAttribute::updateImpl(...).
1390   ChangeStatus updateImpl(Attributor &A) override {
1391     auto CheckForNoFree = [&](Instruction &I) {
1392       const auto &CB = cast<CallBase>(I);
1393       if (CB.hasFnAttr(Attribute::NoFree))
1394         return true;
1395 
1396       const auto &NoFreeAA =
1397           A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(CB));
1398       return NoFreeAA.isAssumedNoFree();
1399     };
1400 
1401     if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this))
1402       return indicatePessimisticFixpoint();
1403     return ChangeStatus::UNCHANGED;
1404   }
1405 
1406   /// See AbstractAttribute::getAsStr().
1407   const std::string getAsStr() const override {
1408     return getAssumed() ? "nofree" : "may-free";
1409   }
1410 };
1411 
1412 struct AANoFreeFunction final : public AANoFreeImpl {
1413   AANoFreeFunction(const IRPosition &IRP, Attributor &A)
1414       : AANoFreeImpl(IRP, A) {}
1415 
1416   /// See AbstractAttribute::trackStatistics()
1417   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
1418 };
1419 
1420 /// NoFree attribute deduction for a call sites.
1421 struct AANoFreeCallSite final : AANoFreeImpl {
1422   AANoFreeCallSite(const IRPosition &IRP, Attributor &A)
1423       : AANoFreeImpl(IRP, A) {}
1424 
1425   /// See AbstractAttribute::initialize(...).
1426   void initialize(Attributor &A) override {
1427     AANoFreeImpl::initialize(A);
1428     Function *F = getAssociatedFunction();
1429     if (!F)
1430       indicatePessimisticFixpoint();
1431   }
1432 
1433   /// See AbstractAttribute::updateImpl(...).
1434   ChangeStatus updateImpl(Attributor &A) override {
1435     // TODO: Once we have call site specific value information we can provide
1436     //       call site specific liveness information and then it makes
1437     //       sense to specialize attributes for call sites arguments instead of
1438     //       redirecting requests to the callee argument.
1439     Function *F = getAssociatedFunction();
1440     const IRPosition &FnPos = IRPosition::function(*F);
1441     auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos);
1442     return clampStateAndIndicateChange(
1443         getState(), static_cast<const AANoFree::StateType &>(FnAA.getState()));
1444   }
1445 
1446   /// See AbstractAttribute::trackStatistics()
1447   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
1448 };
1449 
1450 /// NoFree attribute for floating values.
1451 struct AANoFreeFloating : AANoFreeImpl {
1452   AANoFreeFloating(const IRPosition &IRP, Attributor &A)
1453       : AANoFreeImpl(IRP, A) {}
1454 
1455   /// See AbstractAttribute::trackStatistics()
1456   void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
1457 
1458   /// See Abstract Attribute::updateImpl(...).
1459   ChangeStatus updateImpl(Attributor &A) override {
1460     const IRPosition &IRP = getIRPosition();
1461 
1462     const auto &NoFreeAA =
1463         A.getAAFor<AANoFree>(*this, IRPosition::function_scope(IRP));
1464     if (NoFreeAA.isAssumedNoFree())
1465       return ChangeStatus::UNCHANGED;
1466 
1467     Value &AssociatedValue = getIRPosition().getAssociatedValue();
1468     auto Pred = [&](const Use &U, bool &Follow) -> bool {
1469       Instruction *UserI = cast<Instruction>(U.getUser());
1470       if (auto *CB = dyn_cast<CallBase>(UserI)) {
1471         if (CB->isBundleOperand(&U))
1472           return false;
1473         if (!CB->isArgOperand(&U))
1474           return true;
1475         unsigned ArgNo = CB->getArgOperandNo(&U);
1476 
1477         const auto &NoFreeArg = A.getAAFor<AANoFree>(
1478             *this, IRPosition::callsite_argument(*CB, ArgNo));
1479         return NoFreeArg.isAssumedNoFree();
1480       }
1481 
1482       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
1483           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
1484         Follow = true;
1485         return true;
1486       }
1487       if (isa<ReturnInst>(UserI))
1488         return true;
1489 
1490       // Unknown user.
1491       return false;
1492     };
1493     if (!A.checkForAllUses(Pred, *this, AssociatedValue))
1494       return indicatePessimisticFixpoint();
1495 
1496     return ChangeStatus::UNCHANGED;
1497   }
1498 };
1499 
1500 /// NoFree attribute for a call site argument.
1501 struct AANoFreeArgument final : AANoFreeFloating {
1502   AANoFreeArgument(const IRPosition &IRP, Attributor &A)
1503       : AANoFreeFloating(IRP, A) {}
1504 
1505   /// See AbstractAttribute::trackStatistics()
1506   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
1507 };
1508 
1509 /// NoFree attribute for call site arguments.
1510 struct AANoFreeCallSiteArgument final : AANoFreeFloating {
1511   AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A)
1512       : AANoFreeFloating(IRP, A) {}
1513 
1514   /// See AbstractAttribute::updateImpl(...).
1515   ChangeStatus updateImpl(Attributor &A) override {
1516     // TODO: Once we have call site specific value information we can provide
1517     //       call site specific liveness information and then it makes
1518     //       sense to specialize attributes for call sites arguments instead of
1519     //       redirecting requests to the callee argument.
1520     Argument *Arg = getAssociatedArgument();
1521     if (!Arg)
1522       return indicatePessimisticFixpoint();
1523     const IRPosition &ArgPos = IRPosition::argument(*Arg);
1524     auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos);
1525     return clampStateAndIndicateChange(
1526         getState(), static_cast<const AANoFree::StateType &>(ArgAA.getState()));
1527   }
1528 
1529   /// See AbstractAttribute::trackStatistics()
1530   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)};
1531 };
1532 
1533 /// NoFree attribute for function return value.
1534 struct AANoFreeReturned final : AANoFreeFloating {
1535   AANoFreeReturned(const IRPosition &IRP, Attributor &A)
1536       : AANoFreeFloating(IRP, A) {
1537     llvm_unreachable("NoFree is not applicable to function returns!");
1538   }
1539 
1540   /// See AbstractAttribute::initialize(...).
1541   void initialize(Attributor &A) override {
1542     llvm_unreachable("NoFree is not applicable to function returns!");
1543   }
1544 
1545   /// See AbstractAttribute::updateImpl(...).
1546   ChangeStatus updateImpl(Attributor &A) override {
1547     llvm_unreachable("NoFree is not applicable to function returns!");
1548   }
1549 
1550   /// See AbstractAttribute::trackStatistics()
1551   void trackStatistics() const override {}
1552 };
1553 
1554 /// NoFree attribute deduction for a call site return value.
1555 struct AANoFreeCallSiteReturned final : AANoFreeFloating {
1556   AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A)
1557       : AANoFreeFloating(IRP, A) {}
1558 
1559   ChangeStatus manifest(Attributor &A) override {
1560     return ChangeStatus::UNCHANGED;
1561   }
1562   /// See AbstractAttribute::trackStatistics()
1563   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
1564 };
1565 
1566 /// ------------------------ NonNull Argument Attribute ------------------------
1567 static int64_t getKnownNonNullAndDerefBytesForUse(
1568     Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
1569     const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
1570   TrackUse = false;
1571 
1572   const Value *UseV = U->get();
1573   if (!UseV->getType()->isPointerTy())
1574     return 0;
1575 
1576   Type *PtrTy = UseV->getType();
1577   const Function *F = I->getFunction();
1578   bool NullPointerIsDefined =
1579       F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true;
1580   const DataLayout &DL = A.getInfoCache().getDL();
1581   if (const auto *CB = dyn_cast<CallBase>(I)) {
1582     if (CB->isBundleOperand(U))
1583       return 0;
1584 
1585     if (CB->isCallee(U)) {
1586       IsNonNull |= !NullPointerIsDefined;
1587       return 0;
1588     }
1589 
1590     unsigned ArgNo = CB->getArgOperandNo(U);
1591     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
1592     // As long as we only use known information there is no need to track
1593     // dependences here.
1594     auto &DerefAA = A.getAAFor<AADereferenceable>(QueryingAA, IRP,
1595                                                   /* TrackDependence */ false);
1596     IsNonNull |= DerefAA.isKnownNonNull();
1597     return DerefAA.getKnownDereferenceableBytes();
1598   }
1599 
1600   // We need to follow common pointer manipulation uses to the accesses they
1601   // feed into. We can try to be smart to avoid looking through things we do not
1602   // like for now, e.g., non-inbounds GEPs.
1603   if (isa<CastInst>(I)) {
1604     TrackUse = true;
1605     return 0;
1606   }
1607   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
1608     if (GEP->hasAllConstantIndices()) {
1609       TrackUse = true;
1610       return 0;
1611     }
1612 
1613   int64_t Offset;
1614   if (const Value *Base = getBasePointerOfAccessPointerOperand(I, Offset, DL)) {
1615     if (Base == &AssociatedValue &&
1616         getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
1617       int64_t DerefBytes =
1618           (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType()) + Offset;
1619 
1620       IsNonNull |= !NullPointerIsDefined;
1621       return std::max(int64_t(0), DerefBytes);
1622     }
1623   }
1624 
1625   /// Corner case when an offset is 0.
1626   if (const Value *Base = getBasePointerOfAccessPointerOperand(
1627           I, Offset, DL, /*AllowNonInbounds*/ true)) {
1628     if (Offset == 0 && Base == &AssociatedValue &&
1629         getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
1630       int64_t DerefBytes =
1631           (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType());
1632       IsNonNull |= !NullPointerIsDefined;
1633       return std::max(int64_t(0), DerefBytes);
1634     }
1635   }
1636 
1637   return 0;
1638 }
1639 
1640 struct AANonNullImpl : AANonNull {
1641   AANonNullImpl(const IRPosition &IRP, Attributor &A)
1642       : AANonNull(IRP, A),
1643         NullIsDefined(NullPointerIsDefined(
1644             getAnchorScope(),
1645             getAssociatedValue().getType()->getPointerAddressSpace())) {}
1646 
1647   /// See AbstractAttribute::initialize(...).
1648   void initialize(Attributor &A) override {
1649     if (!NullIsDefined &&
1650         hasAttr({Attribute::NonNull, Attribute::Dereferenceable},
1651                 /* IgnoreSubsumingPositions */ false, &A))
1652       indicateOptimisticFixpoint();
1653     else if (isa<ConstantPointerNull>(getAssociatedValue()))
1654       indicatePessimisticFixpoint();
1655     else
1656       AANonNull::initialize(A);
1657   }
1658 
1659   /// See AAFromMustBeExecutedContext
1660   bool followUse(Attributor &A, const Use *U, const Instruction *I,
1661                  AANonNull::StateType &State) {
1662     bool IsNonNull = false;
1663     bool TrackUse = false;
1664     getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
1665                                        IsNonNull, TrackUse);
1666     State.setKnown(IsNonNull);
1667     return TrackUse;
1668   }
1669 
1670   /// See AbstractAttribute::getAsStr().
1671   const std::string getAsStr() const override {
1672     return getAssumed() ? "nonnull" : "may-null";
1673   }
1674 
1675   /// Flag to determine if the underlying value can be null and still allow
1676   /// valid accesses.
1677   const bool NullIsDefined;
1678 };
1679 
1680 /// NonNull attribute for a floating value.
1681 struct AANonNullFloating
1682     : AAFromMustBeExecutedContext<AANonNull, AANonNullImpl> {
1683   using Base = AAFromMustBeExecutedContext<AANonNull, AANonNullImpl>;
1684   AANonNullFloating(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
1685 
1686   /// See AbstractAttribute::updateImpl(...).
1687   ChangeStatus updateImpl(Attributor &A) override {
1688     ChangeStatus Change = Base::updateImpl(A);
1689     if (isKnownNonNull())
1690       return Change;
1691 
1692     if (!NullIsDefined) {
1693       const auto &DerefAA =
1694           A.getAAFor<AADereferenceable>(*this, getIRPosition());
1695       if (DerefAA.getAssumedDereferenceableBytes())
1696         return Change;
1697     }
1698 
1699     const DataLayout &DL = A.getDataLayout();
1700 
1701     DominatorTree *DT = nullptr;
1702     AssumptionCache *AC = nullptr;
1703     InformationCache &InfoCache = A.getInfoCache();
1704     if (const Function *Fn = getAnchorScope()) {
1705       DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn);
1706       AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn);
1707     }
1708 
1709     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
1710                             AANonNull::StateType &T, bool Stripped) -> bool {
1711       const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V));
1712       if (!Stripped && this == &AA) {
1713         if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT))
1714           T.indicatePessimisticFixpoint();
1715       } else {
1716         // Use abstract attribute information.
1717         const AANonNull::StateType &NS =
1718             static_cast<const AANonNull::StateType &>(AA.getState());
1719         T ^= NS;
1720       }
1721       return T.isValidState();
1722     };
1723 
1724     StateType T;
1725     if (!genericValueTraversal<AANonNull, StateType>(
1726             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
1727       return indicatePessimisticFixpoint();
1728 
1729     return clampStateAndIndicateChange(getState(), T);
1730   }
1731 
1732   /// See AbstractAttribute::trackStatistics()
1733   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
1734 };
1735 
1736 /// NonNull attribute for function return value.
1737 struct AANonNullReturned final
1738     : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> {
1739   AANonNullReturned(const IRPosition &IRP, Attributor &A)
1740       : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP, A) {}
1741 
1742   /// See AbstractAttribute::trackStatistics()
1743   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
1744 };
1745 
1746 /// NonNull attribute for function argument.
1747 struct AANonNullArgument final
1748     : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull,
1749                                                               AANonNullImpl> {
1750   AANonNullArgument(const IRPosition &IRP, Attributor &A)
1751       : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull,
1752                                                                 AANonNullImpl>(
1753             IRP, A) {}
1754 
1755   /// See AbstractAttribute::trackStatistics()
1756   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
1757 };
1758 
1759 struct AANonNullCallSiteArgument final : AANonNullFloating {
1760   AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A)
1761       : AANonNullFloating(IRP, A) {}
1762 
1763   /// See AbstractAttribute::trackStatistics()
1764   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
1765 };
1766 
1767 /// NonNull attribute for a call site return position.
1768 struct AANonNullCallSiteReturned final
1769     : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull,
1770                                                              AANonNullImpl> {
1771   AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A)
1772       : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull,
1773                                                                AANonNullImpl>(
1774             IRP, A) {}
1775 
1776   /// See AbstractAttribute::trackStatistics()
1777   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
1778 };
1779 
1780 /// ------------------------ No-Recurse Attributes ----------------------------
1781 
1782 struct AANoRecurseImpl : public AANoRecurse {
1783   AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {}
1784 
1785   /// See AbstractAttribute::getAsStr()
1786   const std::string getAsStr() const override {
1787     return getAssumed() ? "norecurse" : "may-recurse";
1788   }
1789 };
1790 
1791 struct AANoRecurseFunction final : AANoRecurseImpl {
1792   AANoRecurseFunction(const IRPosition &IRP, Attributor &A)
1793       : AANoRecurseImpl(IRP, A) {}
1794 
1795   /// See AbstractAttribute::initialize(...).
1796   void initialize(Attributor &A) override {
1797     AANoRecurseImpl::initialize(A);
1798     if (const Function *F = getAnchorScope())
1799       if (A.getInfoCache().getSccSize(*F) != 1)
1800         indicatePessimisticFixpoint();
1801   }
1802 
1803   /// See AbstractAttribute::updateImpl(...).
1804   ChangeStatus updateImpl(Attributor &A) override {
1805 
1806     // If all live call sites are known to be no-recurse, we are as well.
1807     auto CallSitePred = [&](AbstractCallSite ACS) {
1808       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
1809           *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
1810           /* TrackDependence */ false, DepClassTy::OPTIONAL);
1811       return NoRecurseAA.isKnownNoRecurse();
1812     };
1813     bool AllCallSitesKnown;
1814     if (A.checkForAllCallSites(CallSitePred, *this, true, AllCallSitesKnown)) {
1815       // If we know all call sites and all are known no-recurse, we are done.
1816       // If all known call sites, which might not be all that exist, are known
1817       // to be no-recurse, we are not done but we can continue to assume
1818       // no-recurse. If one of the call sites we have not visited will become
1819       // live, another update is triggered.
1820       if (AllCallSitesKnown)
1821         indicateOptimisticFixpoint();
1822       return ChangeStatus::UNCHANGED;
1823     }
1824 
1825     // If the above check does not hold anymore we look at the calls.
1826     auto CheckForNoRecurse = [&](Instruction &I) {
1827       const auto &CB = cast<CallBase>(I);
1828       if (CB.hasFnAttr(Attribute::NoRecurse))
1829         return true;
1830 
1831       const auto &NoRecurseAA =
1832           A.getAAFor<AANoRecurse>(*this, IRPosition::callsite_function(CB));
1833       if (!NoRecurseAA.isAssumedNoRecurse())
1834         return false;
1835 
1836       // Recursion to the same function
1837       if (CB.getCalledFunction() == getAnchorScope())
1838         return false;
1839 
1840       return true;
1841     };
1842 
1843     if (!A.checkForAllCallLikeInstructions(CheckForNoRecurse, *this))
1844       return indicatePessimisticFixpoint();
1845     return ChangeStatus::UNCHANGED;
1846   }
1847 
1848   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
1849 };
1850 
1851 /// NoRecurse attribute deduction for a call sites.
1852 struct AANoRecurseCallSite final : AANoRecurseImpl {
1853   AANoRecurseCallSite(const IRPosition &IRP, Attributor &A)
1854       : AANoRecurseImpl(IRP, A) {}
1855 
1856   /// See AbstractAttribute::initialize(...).
1857   void initialize(Attributor &A) override {
1858     AANoRecurseImpl::initialize(A);
1859     Function *F = getAssociatedFunction();
1860     if (!F)
1861       indicatePessimisticFixpoint();
1862   }
1863 
1864   /// See AbstractAttribute::updateImpl(...).
1865   ChangeStatus updateImpl(Attributor &A) override {
1866     // TODO: Once we have call site specific value information we can provide
1867     //       call site specific liveness information and then it makes
1868     //       sense to specialize attributes for call sites arguments instead of
1869     //       redirecting requests to the callee argument.
1870     Function *F = getAssociatedFunction();
1871     const IRPosition &FnPos = IRPosition::function(*F);
1872     auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos);
1873     return clampStateAndIndicateChange(
1874         getState(),
1875         static_cast<const AANoRecurse::StateType &>(FnAA.getState()));
1876   }
1877 
1878   /// See AbstractAttribute::trackStatistics()
1879   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
1880 };
1881 
1882 /// -------------------- Undefined-Behavior Attributes ------------------------
1883 
1884 struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
1885   AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A)
1886       : AAUndefinedBehavior(IRP, A) {}
1887 
1888   /// See AbstractAttribute::updateImpl(...).
1889   // through a pointer (i.e. also branches etc.)
1890   ChangeStatus updateImpl(Attributor &A) override {
1891     const size_t UBPrevSize = KnownUBInsts.size();
1892     const size_t NoUBPrevSize = AssumedNoUBInsts.size();
1893 
1894     auto InspectMemAccessInstForUB = [&](Instruction &I) {
1895       // Skip instructions that are already saved.
1896       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
1897         return true;
1898 
1899       // If we reach here, we know we have an instruction
1900       // that accesses memory through a pointer operand,
1901       // for which getPointerOperand() should give it to us.
1902       const Value *PtrOp = getPointerOperand(&I, /* AllowVolatile */ true);
1903       assert(PtrOp &&
1904              "Expected pointer operand of memory accessing instruction");
1905 
1906       // Either we stopped and the appropriate action was taken,
1907       // or we got back a simplified value to continue.
1908       Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I);
1909       if (!SimplifiedPtrOp.hasValue())
1910         return true;
1911       const Value *PtrOpVal = SimplifiedPtrOp.getValue();
1912 
1913       // A memory access through a pointer is considered UB
1914       // only if the pointer has constant null value.
1915       // TODO: Expand it to not only check constant values.
1916       if (!isa<ConstantPointerNull>(PtrOpVal)) {
1917         AssumedNoUBInsts.insert(&I);
1918         return true;
1919       }
1920       const Type *PtrTy = PtrOpVal->getType();
1921 
1922       // Because we only consider instructions inside functions,
1923       // assume that a parent function exists.
1924       const Function *F = I.getFunction();
1925 
1926       // A memory access using constant null pointer is only considered UB
1927       // if null pointer is _not_ defined for the target platform.
1928       if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()))
1929         AssumedNoUBInsts.insert(&I);
1930       else
1931         KnownUBInsts.insert(&I);
1932       return true;
1933     };
1934 
1935     auto InspectBrInstForUB = [&](Instruction &I) {
1936       // A conditional branch instruction is considered UB if it has `undef`
1937       // condition.
1938 
1939       // Skip instructions that are already saved.
1940       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
1941         return true;
1942 
1943       // We know we have a branch instruction.
1944       auto BrInst = cast<BranchInst>(&I);
1945 
1946       // Unconditional branches are never considered UB.
1947       if (BrInst->isUnconditional())
1948         return true;
1949 
1950       // Either we stopped and the appropriate action was taken,
1951       // or we got back a simplified value to continue.
1952       Optional<Value *> SimplifiedCond =
1953           stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst);
1954       if (!SimplifiedCond.hasValue())
1955         return true;
1956       AssumedNoUBInsts.insert(&I);
1957       return true;
1958     };
1959 
1960     A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
1961                               {Instruction::Load, Instruction::Store,
1962                                Instruction::AtomicCmpXchg,
1963                                Instruction::AtomicRMW},
1964                               /* CheckBBLivenessOnly */ true);
1965     A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br},
1966                               /* CheckBBLivenessOnly */ true);
1967     if (NoUBPrevSize != AssumedNoUBInsts.size() ||
1968         UBPrevSize != KnownUBInsts.size())
1969       return ChangeStatus::CHANGED;
1970     return ChangeStatus::UNCHANGED;
1971   }
1972 
1973   bool isKnownToCauseUB(Instruction *I) const override {
1974     return KnownUBInsts.count(I);
1975   }
1976 
1977   bool isAssumedToCauseUB(Instruction *I) const override {
1978     // In simple words, if an instruction is not in the assumed to _not_
1979     // cause UB, then it is assumed UB (that includes those
1980     // in the KnownUBInsts set). The rest is boilerplate
1981     // is to ensure that it is one of the instructions we test
1982     // for UB.
1983 
1984     switch (I->getOpcode()) {
1985     case Instruction::Load:
1986     case Instruction::Store:
1987     case Instruction::AtomicCmpXchg:
1988     case Instruction::AtomicRMW:
1989       return !AssumedNoUBInsts.count(I);
1990     case Instruction::Br: {
1991       auto BrInst = cast<BranchInst>(I);
1992       if (BrInst->isUnconditional())
1993         return false;
1994       return !AssumedNoUBInsts.count(I);
1995     } break;
1996     default:
1997       return false;
1998     }
1999     return false;
2000   }
2001 
2002   ChangeStatus manifest(Attributor &A) override {
2003     if (KnownUBInsts.empty())
2004       return ChangeStatus::UNCHANGED;
2005     for (Instruction *I : KnownUBInsts)
2006       A.changeToUnreachableAfterManifest(I);
2007     return ChangeStatus::CHANGED;
2008   }
2009 
2010   /// See AbstractAttribute::getAsStr()
2011   const std::string getAsStr() const override {
2012     return getAssumed() ? "undefined-behavior" : "no-ub";
2013   }
2014 
2015   /// Note: The correctness of this analysis depends on the fact that the
2016   /// following 2 sets will stop changing after some point.
2017   /// "Change" here means that their size changes.
2018   /// The size of each set is monotonically increasing
2019   /// (we only add items to them) and it is upper bounded by the number of
2020   /// instructions in the processed function (we can never save more
2021   /// elements in either set than this number). Hence, at some point,
2022   /// they will stop increasing.
2023   /// Consequently, at some point, both sets will have stopped
2024   /// changing, effectively making the analysis reach a fixpoint.
2025 
2026   /// Note: These 2 sets are disjoint and an instruction can be considered
2027   /// one of 3 things:
2028   /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
2029   ///    the KnownUBInsts set.
2030   /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
2031   ///    has a reason to assume it).
2032   /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
2033   ///    could not find a reason to assume or prove that it can cause UB,
2034   ///    hence it assumes it doesn't. We have a set for these instructions
2035   ///    so that we don't reprocess them in every update.
2036   ///    Note however that instructions in this set may cause UB.
2037 
2038 protected:
2039   /// A set of all live instructions _known_ to cause UB.
2040   SmallPtrSet<Instruction *, 8> KnownUBInsts;
2041 
2042 private:
2043   /// A set of all the (live) instructions that are assumed to _not_ cause UB.
2044   SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
2045 
2046   // Should be called on updates in which if we're processing an instruction
2047   // \p I that depends on a value \p V, one of the following has to happen:
2048   // - If the value is assumed, then stop.
2049   // - If the value is known but undef, then consider it UB.
2050   // - Otherwise, do specific processing with the simplified value.
2051   // We return None in the first 2 cases to signify that an appropriate
2052   // action was taken and the caller should stop.
2053   // Otherwise, we return the simplified value that the caller should
2054   // use for specific processing.
2055   Optional<Value *> stopOnUndefOrAssumed(Attributor &A, const Value *V,
2056                                          Instruction *I) {
2057     const auto &ValueSimplifyAA =
2058         A.getAAFor<AAValueSimplify>(*this, IRPosition::value(*V));
2059     Optional<Value *> SimplifiedV =
2060         ValueSimplifyAA.getAssumedSimplifiedValue(A);
2061     if (!ValueSimplifyAA.isKnown()) {
2062       // Don't depend on assumed values.
2063       return llvm::None;
2064     }
2065     if (!SimplifiedV.hasValue()) {
2066       // If it is known (which we tested above) but it doesn't have a value,
2067       // then we can assume `undef` and hence the instruction is UB.
2068       KnownUBInsts.insert(I);
2069       return llvm::None;
2070     }
2071     Value *Val = SimplifiedV.getValue();
2072     if (isa<UndefValue>(Val)) {
2073       KnownUBInsts.insert(I);
2074       return llvm::None;
2075     }
2076     return Val;
2077   }
2078 };
2079 
2080 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
2081   AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
2082       : AAUndefinedBehaviorImpl(IRP, A) {}
2083 
2084   /// See AbstractAttribute::trackStatistics()
2085   void trackStatistics() const override {
2086     STATS_DECL(UndefinedBehaviorInstruction, Instruction,
2087                "Number of instructions known to have UB");
2088     BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
2089         KnownUBInsts.size();
2090   }
2091 };
2092 
2093 /// ------------------------ Will-Return Attributes ----------------------------
2094 
2095 // Helper function that checks whether a function has any cycle which we don't
2096 // know if it is bounded or not.
2097 // Loops with maximum trip count are considered bounded, any other cycle not.
2098 static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
2099   ScalarEvolution *SE =
2100       A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
2101   LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
2102   // If either SCEV or LoopInfo is not available for the function then we assume
2103   // any cycle to be unbounded cycle.
2104   // We use scc_iterator which uses Tarjan algorithm to find all the maximal
2105   // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
2106   if (!SE || !LI) {
2107     for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
2108       if (SCCI.hasCycle())
2109         return true;
2110     return false;
2111   }
2112 
2113   // If there's irreducible control, the function may contain non-loop cycles.
2114   if (mayContainIrreducibleControl(F, LI))
2115     return true;
2116 
2117   // Any loop that does not have a max trip count is considered unbounded cycle.
2118   for (auto *L : LI->getLoopsInPreorder()) {
2119     if (!SE->getSmallConstantMaxTripCount(L))
2120       return true;
2121   }
2122   return false;
2123 }
2124 
2125 struct AAWillReturnImpl : public AAWillReturn {
2126   AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
2127       : AAWillReturn(IRP, A) {}
2128 
2129   /// See AbstractAttribute::initialize(...).
2130   void initialize(Attributor &A) override {
2131     AAWillReturn::initialize(A);
2132 
2133     Function *F = getAnchorScope();
2134     if (!F || !A.isFunctionIPOAmendable(*F) || mayContainUnboundedCycle(*F, A))
2135       indicatePessimisticFixpoint();
2136   }
2137 
2138   /// See AbstractAttribute::updateImpl(...).
2139   ChangeStatus updateImpl(Attributor &A) override {
2140     auto CheckForWillReturn = [&](Instruction &I) {
2141       IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I));
2142       const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos);
2143       if (WillReturnAA.isKnownWillReturn())
2144         return true;
2145       if (!WillReturnAA.isAssumedWillReturn())
2146         return false;
2147       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos);
2148       return NoRecurseAA.isAssumedNoRecurse();
2149     };
2150 
2151     if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this))
2152       return indicatePessimisticFixpoint();
2153 
2154     return ChangeStatus::UNCHANGED;
2155   }
2156 
2157   /// See AbstractAttribute::getAsStr()
2158   const std::string getAsStr() const override {
2159     return getAssumed() ? "willreturn" : "may-noreturn";
2160   }
2161 };
2162 
2163 struct AAWillReturnFunction final : AAWillReturnImpl {
2164   AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
2165       : AAWillReturnImpl(IRP, A) {}
2166 
2167   /// See AbstractAttribute::trackStatistics()
2168   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
2169 };
2170 
2171 /// WillReturn attribute deduction for a call sites.
2172 struct AAWillReturnCallSite final : AAWillReturnImpl {
2173   AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
2174       : AAWillReturnImpl(IRP, A) {}
2175 
2176   /// See AbstractAttribute::initialize(...).
2177   void initialize(Attributor &A) override {
2178     AAWillReturnImpl::initialize(A);
2179     Function *F = getAssociatedFunction();
2180     if (!F)
2181       indicatePessimisticFixpoint();
2182   }
2183 
2184   /// See AbstractAttribute::updateImpl(...).
2185   ChangeStatus updateImpl(Attributor &A) override {
2186     // TODO: Once we have call site specific value information we can provide
2187     //       call site specific liveness information and then it makes
2188     //       sense to specialize attributes for call sites arguments instead of
2189     //       redirecting requests to the callee argument.
2190     Function *F = getAssociatedFunction();
2191     const IRPosition &FnPos = IRPosition::function(*F);
2192     auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos);
2193     return clampStateAndIndicateChange(
2194         getState(),
2195         static_cast<const AAWillReturn::StateType &>(FnAA.getState()));
2196   }
2197 
2198   /// See AbstractAttribute::trackStatistics()
2199   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
2200 };
2201 
2202 /// -------------------AAReachability Attribute--------------------------
2203 
2204 struct AAReachabilityImpl : AAReachability {
2205   AAReachabilityImpl(const IRPosition &IRP, Attributor &A)
2206       : AAReachability(IRP, A) {}
2207 
2208   const std::string getAsStr() const override {
2209     // TODO: Return the number of reachable queries.
2210     return "reachable";
2211   }
2212 
2213   /// See AbstractAttribute::initialize(...).
2214   void initialize(Attributor &A) override { indicatePessimisticFixpoint(); }
2215 
2216   /// See AbstractAttribute::updateImpl(...).
2217   ChangeStatus updateImpl(Attributor &A) override {
2218     return indicatePessimisticFixpoint();
2219   }
2220 };
2221 
2222 struct AAReachabilityFunction final : public AAReachabilityImpl {
2223   AAReachabilityFunction(const IRPosition &IRP, Attributor &A)
2224       : AAReachabilityImpl(IRP, A) {}
2225 
2226   /// See AbstractAttribute::trackStatistics()
2227   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); }
2228 };
2229 
2230 /// ------------------------ NoAlias Argument Attribute ------------------------
2231 
2232 struct AANoAliasImpl : AANoAlias {
2233   AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
2234     assert(getAssociatedType()->isPointerTy() &&
2235            "Noalias is a pointer attribute");
2236   }
2237 
2238   const std::string getAsStr() const override {
2239     return getAssumed() ? "noalias" : "may-alias";
2240   }
2241 };
2242 
2243 /// NoAlias attribute for a floating value.
2244 struct AANoAliasFloating final : AANoAliasImpl {
2245   AANoAliasFloating(const IRPosition &IRP, Attributor &A)
2246       : AANoAliasImpl(IRP, A) {}
2247 
2248   /// See AbstractAttribute::initialize(...).
2249   void initialize(Attributor &A) override {
2250     AANoAliasImpl::initialize(A);
2251     Value *Val = &getAssociatedValue();
2252     do {
2253       CastInst *CI = dyn_cast<CastInst>(Val);
2254       if (!CI)
2255         break;
2256       Value *Base = CI->getOperand(0);
2257       if (Base->getNumUses() != 1)
2258         break;
2259       Val = Base;
2260     } while (true);
2261 
2262     if (!Val->getType()->isPointerTy()) {
2263       indicatePessimisticFixpoint();
2264       return;
2265     }
2266 
2267     if (isa<AllocaInst>(Val))
2268       indicateOptimisticFixpoint();
2269     else if (isa<ConstantPointerNull>(Val) &&
2270              !NullPointerIsDefined(getAnchorScope(),
2271                                    Val->getType()->getPointerAddressSpace()))
2272       indicateOptimisticFixpoint();
2273     else if (Val != &getAssociatedValue()) {
2274       const auto &ValNoAliasAA =
2275           A.getAAFor<AANoAlias>(*this, IRPosition::value(*Val));
2276       if (ValNoAliasAA.isKnownNoAlias())
2277         indicateOptimisticFixpoint();
2278     }
2279   }
2280 
2281   /// See AbstractAttribute::updateImpl(...).
2282   ChangeStatus updateImpl(Attributor &A) override {
2283     // TODO: Implement this.
2284     return indicatePessimisticFixpoint();
2285   }
2286 
2287   /// See AbstractAttribute::trackStatistics()
2288   void trackStatistics() const override {
2289     STATS_DECLTRACK_FLOATING_ATTR(noalias)
2290   }
2291 };
2292 
2293 /// NoAlias attribute for an argument.
2294 struct AANoAliasArgument final
2295     : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
2296   using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
2297   AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
2298 
2299   /// See AbstractAttribute::initialize(...).
2300   void initialize(Attributor &A) override {
2301     Base::initialize(A);
2302     // See callsite argument attribute and callee argument attribute.
2303     if (hasAttr({Attribute::ByVal}))
2304       indicateOptimisticFixpoint();
2305   }
2306 
2307   /// See AbstractAttribute::update(...).
2308   ChangeStatus updateImpl(Attributor &A) override {
2309     // We have to make sure no-alias on the argument does not break
2310     // synchronization when this is a callback argument, see also [1] below.
2311     // If synchronization cannot be affected, we delegate to the base updateImpl
2312     // function, otherwise we give up for now.
2313 
2314     // If the function is no-sync, no-alias cannot break synchronization.
2315     const auto &NoSyncAA = A.getAAFor<AANoSync>(
2316         *this, IRPosition::function_scope(getIRPosition()));
2317     if (NoSyncAA.isAssumedNoSync())
2318       return Base::updateImpl(A);
2319 
2320     // If the argument is read-only, no-alias cannot break synchronization.
2321     const auto &MemBehaviorAA =
2322         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
2323     if (MemBehaviorAA.isAssumedReadOnly())
2324       return Base::updateImpl(A);
2325 
2326     // If the argument is never passed through callbacks, no-alias cannot break
2327     // synchronization.
2328     bool AllCallSitesKnown;
2329     if (A.checkForAllCallSites(
2330             [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
2331             true, AllCallSitesKnown))
2332       return Base::updateImpl(A);
2333 
2334     // TODO: add no-alias but make sure it doesn't break synchronization by
2335     // introducing fake uses. See:
2336     // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
2337     //     International Workshop on OpenMP 2018,
2338     //     http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
2339 
2340     return indicatePessimisticFixpoint();
2341   }
2342 
2343   /// See AbstractAttribute::trackStatistics()
2344   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
2345 };
2346 
2347 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
2348   AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
2349       : AANoAliasImpl(IRP, A) {}
2350 
2351   /// See AbstractAttribute::initialize(...).
2352   void initialize(Attributor &A) override {
2353     // See callsite argument attribute and callee argument attribute.
2354     const auto &CB = cast<CallBase>(getAnchorValue());
2355     if (CB.paramHasAttr(getArgNo(), Attribute::NoAlias))
2356       indicateOptimisticFixpoint();
2357     Value &Val = getAssociatedValue();
2358     if (isa<ConstantPointerNull>(Val) &&
2359         !NullPointerIsDefined(getAnchorScope(),
2360                               Val.getType()->getPointerAddressSpace()))
2361       indicateOptimisticFixpoint();
2362   }
2363 
2364   /// Determine if the underlying value may alias with the call site argument
2365   /// \p OtherArgNo of \p ICS (= the underlying call site).
2366   bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
2367                             const AAMemoryBehavior &MemBehaviorAA,
2368                             const CallBase &CB, unsigned OtherArgNo) {
2369     // We do not need to worry about aliasing with the underlying IRP.
2370     if (this->getArgNo() == (int)OtherArgNo)
2371       return false;
2372 
2373     // If it is not a pointer or pointer vector we do not alias.
2374     const Value *ArgOp = CB.getArgOperand(OtherArgNo);
2375     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
2376       return false;
2377 
2378     auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
2379         *this, IRPosition::callsite_argument(CB, OtherArgNo),
2380         /* TrackDependence */ false);
2381 
2382     // If the argument is readnone, there is no read-write aliasing.
2383     if (CBArgMemBehaviorAA.isAssumedReadNone()) {
2384       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
2385       return false;
2386     }
2387 
2388     // If the argument is readonly and the underlying value is readonly, there
2389     // is no read-write aliasing.
2390     bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
2391     if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) {
2392       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2393       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
2394       return false;
2395     }
2396 
2397     // We have to utilize actual alias analysis queries so we need the object.
2398     if (!AAR)
2399       AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope());
2400 
2401     // Try to rule it out at the call site.
2402     bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
2403     LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
2404                          "callsite arguments: "
2405                       << getAssociatedValue() << " " << *ArgOp << " => "
2406                       << (IsAliasing ? "" : "no-") << "alias \n");
2407 
2408     return IsAliasing;
2409   }
2410 
2411   bool
2412   isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR,
2413                                          const AAMemoryBehavior &MemBehaviorAA,
2414                                          const AANoAlias &NoAliasAA) {
2415     // We can deduce "noalias" if the following conditions hold.
2416     // (i)   Associated value is assumed to be noalias in the definition.
2417     // (ii)  Associated value is assumed to be no-capture in all the uses
2418     //       possibly executed before this callsite.
2419     // (iii) There is no other pointer argument which could alias with the
2420     //       value.
2421 
2422     bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias();
2423     if (!AssociatedValueIsNoAliasAtDef) {
2424       LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
2425                         << " is not no-alias at the definition\n");
2426       return false;
2427     }
2428 
2429     A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL);
2430 
2431     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
2432     auto &NoCaptureAA =
2433         A.getAAFor<AANoCapture>(*this, VIRP, /* TrackDependence */ false);
2434     // Check whether the value is captured in the scope using AANoCapture.
2435     //      Look at CFG and check only uses possibly executed before this
2436     //      callsite.
2437     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
2438       Instruction *UserI = cast<Instruction>(U.getUser());
2439 
2440       // If user if curr instr and only use.
2441       if ((UserI == getCtxI()) && (UserI->getNumUses() == 1))
2442         return true;
2443 
2444       const Function *ScopeFn = VIRP.getAnchorScope();
2445       if (ScopeFn) {
2446         const auto &ReachabilityAA =
2447             A.getAAFor<AAReachability>(*this, IRPosition::function(*ScopeFn));
2448 
2449         if (!ReachabilityAA.isAssumedReachable(UserI, getCtxI()))
2450           return true;
2451 
2452         if (auto *CB = dyn_cast<CallBase>(UserI)) {
2453           if (CB->isArgOperand(&U)) {
2454 
2455             unsigned ArgNo = CB->getArgOperandNo(&U);
2456 
2457             const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
2458                 *this, IRPosition::callsite_argument(*CB, ArgNo));
2459 
2460             if (NoCaptureAA.isAssumedNoCapture())
2461               return true;
2462           }
2463         }
2464       }
2465 
2466       // For cases which can potentially have more users
2467       if (isa<GetElementPtrInst>(U) || isa<BitCastInst>(U) || isa<PHINode>(U) ||
2468           isa<SelectInst>(U)) {
2469         Follow = true;
2470         return true;
2471       }
2472 
2473       LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *U << "\n");
2474       return false;
2475     };
2476 
2477     if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
2478       if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
2479         LLVM_DEBUG(
2480             dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
2481                    << " cannot be noalias as it is potentially captured\n");
2482         return false;
2483       }
2484     }
2485     A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL);
2486 
2487     // Check there is no other pointer argument which could alias with the
2488     // value passed at this call site.
2489     // TODO: AbstractCallSite
2490     const auto &CB = cast<CallBase>(getAnchorValue());
2491     for (unsigned OtherArgNo = 0; OtherArgNo < CB.getNumArgOperands();
2492          OtherArgNo++)
2493       if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
2494         return false;
2495 
2496     return true;
2497   }
2498 
2499   /// See AbstractAttribute::updateImpl(...).
2500   ChangeStatus updateImpl(Attributor &A) override {
2501     // If the argument is readnone we are done as there are no accesses via the
2502     // argument.
2503     auto &MemBehaviorAA =
2504         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(),
2505                                      /* TrackDependence */ false);
2506     if (MemBehaviorAA.isAssumedReadNone()) {
2507       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
2508       return ChangeStatus::UNCHANGED;
2509     }
2510 
2511     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
2512     const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, VIRP,
2513                                                   /* TrackDependence */ false);
2514 
2515     AAResults *AAR = nullptr;
2516     if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA,
2517                                                NoAliasAA)) {
2518       LLVM_DEBUG(
2519           dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
2520       return ChangeStatus::UNCHANGED;
2521     }
2522 
2523     return indicatePessimisticFixpoint();
2524   }
2525 
2526   /// See AbstractAttribute::trackStatistics()
2527   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
2528 };
2529 
2530 /// NoAlias attribute for function return value.
2531 struct AANoAliasReturned final : AANoAliasImpl {
2532   AANoAliasReturned(const IRPosition &IRP, Attributor &A)
2533       : AANoAliasImpl(IRP, A) {}
2534 
2535   /// See AbstractAttribute::updateImpl(...).
2536   virtual ChangeStatus updateImpl(Attributor &A) override {
2537 
2538     auto CheckReturnValue = [&](Value &RV) -> bool {
2539       if (Constant *C = dyn_cast<Constant>(&RV))
2540         if (C->isNullValue() || isa<UndefValue>(C))
2541           return true;
2542 
2543       /// For now, we can only deduce noalias if we have call sites.
2544       /// FIXME: add more support.
2545       if (!isa<CallBase>(&RV))
2546         return false;
2547 
2548       const IRPosition &RVPos = IRPosition::value(RV);
2549       const auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, RVPos);
2550       if (!NoAliasAA.isAssumedNoAlias())
2551         return false;
2552 
2553       const auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, RVPos);
2554       return NoCaptureAA.isAssumedNoCaptureMaybeReturned();
2555     };
2556 
2557     if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
2558       return indicatePessimisticFixpoint();
2559 
2560     return ChangeStatus::UNCHANGED;
2561   }
2562 
2563   /// See AbstractAttribute::trackStatistics()
2564   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
2565 };
2566 
2567 /// NoAlias attribute deduction for a call site return value.
2568 struct AANoAliasCallSiteReturned final : AANoAliasImpl {
2569   AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
2570       : AANoAliasImpl(IRP, A) {}
2571 
2572   /// See AbstractAttribute::initialize(...).
2573   void initialize(Attributor &A) override {
2574     AANoAliasImpl::initialize(A);
2575     Function *F = getAssociatedFunction();
2576     if (!F)
2577       indicatePessimisticFixpoint();
2578   }
2579 
2580   /// See AbstractAttribute::updateImpl(...).
2581   ChangeStatus updateImpl(Attributor &A) override {
2582     // TODO: Once we have call site specific value information we can provide
2583     //       call site specific liveness information and then it makes
2584     //       sense to specialize attributes for call sites arguments instead of
2585     //       redirecting requests to the callee argument.
2586     Function *F = getAssociatedFunction();
2587     const IRPosition &FnPos = IRPosition::returned(*F);
2588     auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos);
2589     return clampStateAndIndicateChange(
2590         getState(), static_cast<const AANoAlias::StateType &>(FnAA.getState()));
2591   }
2592 
2593   /// See AbstractAttribute::trackStatistics()
2594   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
2595 };
2596 
2597 /// -------------------AAIsDead Function Attribute-----------------------
2598 
2599 struct AAIsDeadValueImpl : public AAIsDead {
2600   AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
2601 
2602   /// See AAIsDead::isAssumedDead().
2603   bool isAssumedDead() const override { return getAssumed(); }
2604 
2605   /// See AAIsDead::isKnownDead().
2606   bool isKnownDead() const override { return getKnown(); }
2607 
2608   /// See AAIsDead::isAssumedDead(BasicBlock *).
2609   bool isAssumedDead(const BasicBlock *BB) const override { return false; }
2610 
2611   /// See AAIsDead::isKnownDead(BasicBlock *).
2612   bool isKnownDead(const BasicBlock *BB) const override { return false; }
2613 
2614   /// See AAIsDead::isAssumedDead(Instruction *I).
2615   bool isAssumedDead(const Instruction *I) const override {
2616     return I == getCtxI() && isAssumedDead();
2617   }
2618 
2619   /// See AAIsDead::isKnownDead(Instruction *I).
2620   bool isKnownDead(const Instruction *I) const override {
2621     return isAssumedDead(I) && getKnown();
2622   }
2623 
2624   /// See AbstractAttribute::getAsStr().
2625   const std::string getAsStr() const override {
2626     return isAssumedDead() ? "assumed-dead" : "assumed-live";
2627   }
2628 
2629   /// Check if all uses are assumed dead.
2630   bool areAllUsesAssumedDead(Attributor &A, Value &V) {
2631     auto UsePred = [&](const Use &U, bool &Follow) { return false; };
2632     // Explicitly set the dependence class to required because we want a long
2633     // chain of N dependent instructions to be considered live as soon as one is
2634     // without going through N update cycles. This is not required for
2635     // correctness.
2636     return A.checkForAllUses(UsePred, *this, V, DepClassTy::REQUIRED);
2637   }
2638 
2639   /// Determine if \p I is assumed to be side-effect free.
2640   bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
2641     if (!I || wouldInstructionBeTriviallyDead(I))
2642       return true;
2643 
2644     auto *CB = dyn_cast<CallBase>(I);
2645     if (!CB || isa<IntrinsicInst>(CB))
2646       return false;
2647 
2648     const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
2649     const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(*this, CallIRP);
2650     if (!NoUnwindAA.isAssumedNoUnwind())
2651       return false;
2652 
2653     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, CallIRP);
2654     if (!MemBehaviorAA.isAssumedReadOnly())
2655       return false;
2656 
2657     return true;
2658   }
2659 };
2660 
2661 struct AAIsDeadFloating : public AAIsDeadValueImpl {
2662   AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
2663       : AAIsDeadValueImpl(IRP, A) {}
2664 
2665   /// See AbstractAttribute::initialize(...).
2666   void initialize(Attributor &A) override {
2667     if (isa<UndefValue>(getAssociatedValue())) {
2668       indicatePessimisticFixpoint();
2669       return;
2670     }
2671 
2672     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
2673     if (!isAssumedSideEffectFree(A, I))
2674       indicatePessimisticFixpoint();
2675   }
2676 
2677   /// See AbstractAttribute::updateImpl(...).
2678   ChangeStatus updateImpl(Attributor &A) override {
2679     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
2680     if (!isAssumedSideEffectFree(A, I))
2681       return indicatePessimisticFixpoint();
2682 
2683     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
2684       return indicatePessimisticFixpoint();
2685     return ChangeStatus::UNCHANGED;
2686   }
2687 
2688   /// See AbstractAttribute::manifest(...).
2689   ChangeStatus manifest(Attributor &A) override {
2690     Value &V = getAssociatedValue();
2691     if (auto *I = dyn_cast<Instruction>(&V)) {
2692       // If we get here we basically know the users are all dead. We check if
2693       // isAssumedSideEffectFree returns true here again because it might not be
2694       // the case and only the users are dead but the instruction (=call) is
2695       // still needed.
2696       if (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I)) {
2697         A.deleteAfterManifest(*I);
2698         return ChangeStatus::CHANGED;
2699       }
2700     }
2701     if (V.use_empty())
2702       return ChangeStatus::UNCHANGED;
2703 
2704     bool UsedAssumedInformation = false;
2705     Optional<Constant *> C =
2706         A.getAssumedConstant(V, *this, UsedAssumedInformation);
2707     if (C.hasValue() && C.getValue())
2708       return ChangeStatus::UNCHANGED;
2709 
2710     // Replace the value with undef as it is dead but keep droppable uses around
2711     // as they provide information we don't want to give up on just yet.
2712     UndefValue &UV = *UndefValue::get(V.getType());
2713     bool AnyChange =
2714         A.changeValueAfterManifest(V, UV, /* ChangeDropppable */ false);
2715     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
2716   }
2717 
2718   /// See AbstractAttribute::trackStatistics()
2719   void trackStatistics() const override {
2720     STATS_DECLTRACK_FLOATING_ATTR(IsDead)
2721   }
2722 };
2723 
2724 struct AAIsDeadArgument : public AAIsDeadFloating {
2725   AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
2726       : AAIsDeadFloating(IRP, A) {}
2727 
2728   /// See AbstractAttribute::initialize(...).
2729   void initialize(Attributor &A) override {
2730     if (!A.isFunctionIPOAmendable(*getAnchorScope()))
2731       indicatePessimisticFixpoint();
2732   }
2733 
2734   /// See AbstractAttribute::manifest(...).
2735   ChangeStatus manifest(Attributor &A) override {
2736     ChangeStatus Changed = AAIsDeadFloating::manifest(A);
2737     Argument &Arg = *getAssociatedArgument();
2738     if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
2739       if (A.registerFunctionSignatureRewrite(
2740               Arg, /* ReplacementTypes */ {},
2741               Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{},
2742               Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) {
2743         Arg.dropDroppableUses();
2744         return ChangeStatus::CHANGED;
2745       }
2746     return Changed;
2747   }
2748 
2749   /// See AbstractAttribute::trackStatistics()
2750   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
2751 };
2752 
2753 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
2754   AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
2755       : AAIsDeadValueImpl(IRP, A) {}
2756 
2757   /// See AbstractAttribute::initialize(...).
2758   void initialize(Attributor &A) override {
2759     if (isa<UndefValue>(getAssociatedValue()))
2760       indicatePessimisticFixpoint();
2761   }
2762 
2763   /// See AbstractAttribute::updateImpl(...).
2764   ChangeStatus updateImpl(Attributor &A) override {
2765     // TODO: Once we have call site specific value information we can provide
2766     //       call site specific liveness information and then it makes
2767     //       sense to specialize attributes for call sites arguments instead of
2768     //       redirecting requests to the callee argument.
2769     Argument *Arg = getAssociatedArgument();
2770     if (!Arg)
2771       return indicatePessimisticFixpoint();
2772     const IRPosition &ArgPos = IRPosition::argument(*Arg);
2773     auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos);
2774     return clampStateAndIndicateChange(
2775         getState(), static_cast<const AAIsDead::StateType &>(ArgAA.getState()));
2776   }
2777 
2778   /// See AbstractAttribute::manifest(...).
2779   ChangeStatus manifest(Attributor &A) override {
2780     CallBase &CB = cast<CallBase>(getAnchorValue());
2781     Use &U = CB.getArgOperandUse(getArgNo());
2782     assert(!isa<UndefValue>(U.get()) &&
2783            "Expected undef values to be filtered out!");
2784     UndefValue &UV = *UndefValue::get(U->getType());
2785     if (A.changeUseAfterManifest(U, UV))
2786       return ChangeStatus::CHANGED;
2787     return ChangeStatus::UNCHANGED;
2788   }
2789 
2790   /// See AbstractAttribute::trackStatistics()
2791   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
2792 };
2793 
2794 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
2795   AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
2796       : AAIsDeadFloating(IRP, A), IsAssumedSideEffectFree(true) {}
2797 
2798   /// See AAIsDead::isAssumedDead().
2799   bool isAssumedDead() const override {
2800     return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
2801   }
2802 
2803   /// See AbstractAttribute::initialize(...).
2804   void initialize(Attributor &A) override {
2805     if (isa<UndefValue>(getAssociatedValue())) {
2806       indicatePessimisticFixpoint();
2807       return;
2808     }
2809 
2810     // We track this separately as a secondary state.
2811     IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
2812   }
2813 
2814   /// See AbstractAttribute::updateImpl(...).
2815   ChangeStatus updateImpl(Attributor &A) override {
2816     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2817     if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
2818       IsAssumedSideEffectFree = false;
2819       Changed = ChangeStatus::CHANGED;
2820     }
2821 
2822     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
2823       return indicatePessimisticFixpoint();
2824     return Changed;
2825   }
2826 
2827   /// See AbstractAttribute::trackStatistics()
2828   void trackStatistics() const override {
2829     if (IsAssumedSideEffectFree)
2830       STATS_DECLTRACK_CSRET_ATTR(IsDead)
2831     else
2832       STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
2833   }
2834 
2835   /// See AbstractAttribute::getAsStr().
2836   const std::string getAsStr() const override {
2837     return isAssumedDead()
2838                ? "assumed-dead"
2839                : (getAssumed() ? "assumed-dead-users" : "assumed-live");
2840   }
2841 
2842 private:
2843   bool IsAssumedSideEffectFree;
2844 };
2845 
2846 struct AAIsDeadReturned : public AAIsDeadValueImpl {
2847   AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
2848       : AAIsDeadValueImpl(IRP, A) {}
2849 
2850   /// See AbstractAttribute::updateImpl(...).
2851   ChangeStatus updateImpl(Attributor &A) override {
2852 
2853     A.checkForAllInstructions([](Instruction &) { return true; }, *this,
2854                               {Instruction::Ret});
2855 
2856     auto PredForCallSite = [&](AbstractCallSite ACS) {
2857       if (ACS.isCallbackCall() || !ACS.getInstruction())
2858         return false;
2859       return areAllUsesAssumedDead(A, *ACS.getInstruction());
2860     };
2861 
2862     bool AllCallSitesKnown;
2863     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
2864                                 AllCallSitesKnown))
2865       return indicatePessimisticFixpoint();
2866 
2867     return ChangeStatus::UNCHANGED;
2868   }
2869 
2870   /// See AbstractAttribute::manifest(...).
2871   ChangeStatus manifest(Attributor &A) override {
2872     // TODO: Rewrite the signature to return void?
2873     bool AnyChange = false;
2874     UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
2875     auto RetInstPred = [&](Instruction &I) {
2876       ReturnInst &RI = cast<ReturnInst>(I);
2877       if (!isa<UndefValue>(RI.getReturnValue()))
2878         AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
2879       return true;
2880     };
2881     A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret});
2882     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
2883   }
2884 
2885   /// See AbstractAttribute::trackStatistics()
2886   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
2887 };
2888 
2889 struct AAIsDeadFunction : public AAIsDead {
2890   AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
2891 
2892   /// See AbstractAttribute::initialize(...).
2893   void initialize(Attributor &A) override {
2894     const Function *F = getAnchorScope();
2895     if (F && !F->isDeclaration()) {
2896       ToBeExploredFrom.insert(&F->getEntryBlock().front());
2897       assumeLive(A, F->getEntryBlock());
2898     }
2899   }
2900 
2901   /// See AbstractAttribute::getAsStr().
2902   const std::string getAsStr() const override {
2903     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
2904            std::to_string(getAnchorScope()->size()) + "][#TBEP " +
2905            std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
2906            std::to_string(KnownDeadEnds.size()) + "]";
2907   }
2908 
2909   /// See AbstractAttribute::manifest(...).
2910   ChangeStatus manifest(Attributor &A) override {
2911     assert(getState().isValidState() &&
2912            "Attempted to manifest an invalid state!");
2913 
2914     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
2915     Function &F = *getAnchorScope();
2916 
2917     if (AssumedLiveBlocks.empty()) {
2918       A.deleteAfterManifest(F);
2919       return ChangeStatus::CHANGED;
2920     }
2921 
2922     // Flag to determine if we can change an invoke to a call assuming the
2923     // callee is nounwind. This is not possible if the personality of the
2924     // function allows to catch asynchronous exceptions.
2925     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
2926 
2927     KnownDeadEnds.set_union(ToBeExploredFrom);
2928     for (const Instruction *DeadEndI : KnownDeadEnds) {
2929       auto *CB = dyn_cast<CallBase>(DeadEndI);
2930       if (!CB)
2931         continue;
2932       const auto &NoReturnAA =
2933           A.getAAFor<AANoReturn>(*this, IRPosition::callsite_function(*CB));
2934       bool MayReturn = !NoReturnAA.isAssumedNoReturn();
2935       if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
2936         continue;
2937 
2938       if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
2939         A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
2940       else
2941         A.changeToUnreachableAfterManifest(
2942             const_cast<Instruction *>(DeadEndI->getNextNode()));
2943       HasChanged = ChangeStatus::CHANGED;
2944     }
2945 
2946     STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
2947     for (BasicBlock &BB : F)
2948       if (!AssumedLiveBlocks.count(&BB)) {
2949         A.deleteAfterManifest(BB);
2950         ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
2951       }
2952 
2953     return HasChanged;
2954   }
2955 
2956   /// See AbstractAttribute::updateImpl(...).
2957   ChangeStatus updateImpl(Attributor &A) override;
2958 
2959   /// See AbstractAttribute::trackStatistics()
2960   void trackStatistics() const override {}
2961 
2962   /// Returns true if the function is assumed dead.
2963   bool isAssumedDead() const override { return false; }
2964 
2965   /// See AAIsDead::isKnownDead().
2966   bool isKnownDead() const override { return false; }
2967 
2968   /// See AAIsDead::isAssumedDead(BasicBlock *).
2969   bool isAssumedDead(const BasicBlock *BB) const override {
2970     assert(BB->getParent() == getAnchorScope() &&
2971            "BB must be in the same anchor scope function.");
2972 
2973     if (!getAssumed())
2974       return false;
2975     return !AssumedLiveBlocks.count(BB);
2976   }
2977 
2978   /// See AAIsDead::isKnownDead(BasicBlock *).
2979   bool isKnownDead(const BasicBlock *BB) const override {
2980     return getKnown() && isAssumedDead(BB);
2981   }
2982 
2983   /// See AAIsDead::isAssumed(Instruction *I).
2984   bool isAssumedDead(const Instruction *I) const override {
2985     assert(I->getParent()->getParent() == getAnchorScope() &&
2986            "Instruction must be in the same anchor scope function.");
2987 
2988     if (!getAssumed())
2989       return false;
2990 
2991     // If it is not in AssumedLiveBlocks then it for sure dead.
2992     // Otherwise, it can still be after noreturn call in a live block.
2993     if (!AssumedLiveBlocks.count(I->getParent()))
2994       return true;
2995 
2996     // If it is not after a liveness barrier it is live.
2997     const Instruction *PrevI = I->getPrevNode();
2998     while (PrevI) {
2999       if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
3000         return true;
3001       PrevI = PrevI->getPrevNode();
3002     }
3003     return false;
3004   }
3005 
3006   /// See AAIsDead::isKnownDead(Instruction *I).
3007   bool isKnownDead(const Instruction *I) const override {
3008     return getKnown() && isAssumedDead(I);
3009   }
3010 
3011   /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
3012   /// that internal function called from \p BB should now be looked at.
3013   bool assumeLive(Attributor &A, const BasicBlock &BB) {
3014     if (!AssumedLiveBlocks.insert(&BB).second)
3015       return false;
3016 
3017     // We assume that all of BB is (probably) live now and if there are calls to
3018     // internal functions we will assume that those are now live as well. This
3019     // is a performance optimization for blocks with calls to a lot of internal
3020     // functions. It can however cause dead functions to be treated as live.
3021     for (const Instruction &I : BB)
3022       if (const auto *CB = dyn_cast<CallBase>(&I))
3023         if (const Function *F = CB->getCalledFunction())
3024           if (F->hasLocalLinkage())
3025             A.markLiveInternalFunction(*F);
3026     return true;
3027   }
3028 
3029   /// Collection of instructions that need to be explored again, e.g., we
3030   /// did assume they do not transfer control to (one of their) successors.
3031   SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
3032 
3033   /// Collection of instructions that are known to not transfer control.
3034   SmallSetVector<const Instruction *, 8> KnownDeadEnds;
3035 
3036   /// Collection of all assumed live BasicBlocks.
3037   DenseSet<const BasicBlock *> AssumedLiveBlocks;
3038 };
3039 
3040 static bool
3041 identifyAliveSuccessors(Attributor &A, const CallBase &CB,
3042                         AbstractAttribute &AA,
3043                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3044   const IRPosition &IPos = IRPosition::callsite_function(CB);
3045 
3046   const auto &NoReturnAA = A.getAAFor<AANoReturn>(AA, IPos);
3047   if (NoReturnAA.isAssumedNoReturn())
3048     return !NoReturnAA.isKnownNoReturn();
3049   if (CB.isTerminator())
3050     AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
3051   else
3052     AliveSuccessors.push_back(CB.getNextNode());
3053   return false;
3054 }
3055 
3056 static bool
3057 identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
3058                         AbstractAttribute &AA,
3059                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3060   bool UsedAssumedInformation =
3061       identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
3062 
3063   // First, determine if we can change an invoke to a call assuming the
3064   // callee is nounwind. This is not possible if the personality of the
3065   // function allows to catch asynchronous exceptions.
3066   if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
3067     AliveSuccessors.push_back(&II.getUnwindDest()->front());
3068   } else {
3069     const IRPosition &IPos = IRPosition::callsite_function(II);
3070     const auto &AANoUnw = A.getAAFor<AANoUnwind>(AA, IPos);
3071     if (AANoUnw.isAssumedNoUnwind()) {
3072       UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
3073     } else {
3074       AliveSuccessors.push_back(&II.getUnwindDest()->front());
3075     }
3076   }
3077   return UsedAssumedInformation;
3078 }
3079 
3080 static bool
3081 identifyAliveSuccessors(Attributor &A, const BranchInst &BI,
3082                         AbstractAttribute &AA,
3083                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3084   bool UsedAssumedInformation = false;
3085   if (BI.getNumSuccessors() == 1) {
3086     AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3087   } else {
3088     Optional<ConstantInt *> CI = getAssumedConstantInt(
3089         A, *BI.getCondition(), AA, UsedAssumedInformation);
3090     if (!CI.hasValue()) {
3091       // No value yet, assume both edges are dead.
3092     } else if (CI.getValue()) {
3093       const BasicBlock *SuccBB =
3094           BI.getSuccessor(1 - CI.getValue()->getZExtValue());
3095       AliveSuccessors.push_back(&SuccBB->front());
3096     } else {
3097       AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
3098       AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
3099       UsedAssumedInformation = false;
3100     }
3101   }
3102   return UsedAssumedInformation;
3103 }
3104 
3105 static bool
3106 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
3107                         AbstractAttribute &AA,
3108                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3109   bool UsedAssumedInformation = false;
3110   Optional<ConstantInt *> CI =
3111       getAssumedConstantInt(A, *SI.getCondition(), AA, UsedAssumedInformation);
3112   if (!CI.hasValue()) {
3113     // No value yet, assume all edges are dead.
3114   } else if (CI.getValue()) {
3115     for (auto &CaseIt : SI.cases()) {
3116       if (CaseIt.getCaseValue() == CI.getValue()) {
3117         AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
3118         return UsedAssumedInformation;
3119       }
3120     }
3121     AliveSuccessors.push_back(&SI.getDefaultDest()->front());
3122     return UsedAssumedInformation;
3123   } else {
3124     for (const BasicBlock *SuccBB : successors(SI.getParent()))
3125       AliveSuccessors.push_back(&SuccBB->front());
3126   }
3127   return UsedAssumedInformation;
3128 }
3129 
3130 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
3131   ChangeStatus Change = ChangeStatus::UNCHANGED;
3132 
3133   LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
3134                     << getAnchorScope()->size() << "] BBs and "
3135                     << ToBeExploredFrom.size() << " exploration points and "
3136                     << KnownDeadEnds.size() << " known dead ends\n");
3137 
3138   // Copy and clear the list of instructions we need to explore from. It is
3139   // refilled with instructions the next update has to look at.
3140   SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
3141                                                ToBeExploredFrom.end());
3142   decltype(ToBeExploredFrom) NewToBeExploredFrom;
3143 
3144   SmallVector<const Instruction *, 8> AliveSuccessors;
3145   while (!Worklist.empty()) {
3146     const Instruction *I = Worklist.pop_back_val();
3147     LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
3148 
3149     AliveSuccessors.clear();
3150 
3151     bool UsedAssumedInformation = false;
3152     switch (I->getOpcode()) {
3153     // TODO: look for (assumed) UB to backwards propagate "deadness".
3154     default:
3155       if (I->isTerminator()) {
3156         for (const BasicBlock *SuccBB : successors(I->getParent()))
3157           AliveSuccessors.push_back(&SuccBB->front());
3158       } else {
3159         AliveSuccessors.push_back(I->getNextNode());
3160       }
3161       break;
3162     case Instruction::Call:
3163       UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
3164                                                        *this, AliveSuccessors);
3165       break;
3166     case Instruction::Invoke:
3167       UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
3168                                                        *this, AliveSuccessors);
3169       break;
3170     case Instruction::Br:
3171       UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
3172                                                        *this, AliveSuccessors);
3173       break;
3174     case Instruction::Switch:
3175       UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
3176                                                        *this, AliveSuccessors);
3177       break;
3178     }
3179 
3180     if (UsedAssumedInformation) {
3181       NewToBeExploredFrom.insert(I);
3182     } else {
3183       Change = ChangeStatus::CHANGED;
3184       if (AliveSuccessors.empty() ||
3185           (I->isTerminator() && AliveSuccessors.size() < I->getNumSuccessors()))
3186         KnownDeadEnds.insert(I);
3187     }
3188 
3189     LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
3190                       << AliveSuccessors.size() << " UsedAssumedInformation: "
3191                       << UsedAssumedInformation << "\n");
3192 
3193     for (const Instruction *AliveSuccessor : AliveSuccessors) {
3194       if (!I->isTerminator()) {
3195         assert(AliveSuccessors.size() == 1 &&
3196                "Non-terminator expected to have a single successor!");
3197         Worklist.push_back(AliveSuccessor);
3198       } else {
3199         if (assumeLive(A, *AliveSuccessor->getParent()))
3200           Worklist.push_back(AliveSuccessor);
3201       }
3202     }
3203   }
3204 
3205   ToBeExploredFrom = std::move(NewToBeExploredFrom);
3206 
3207   // If we know everything is live there is no need to query for liveness.
3208   // Instead, indicating a pessimistic fixpoint will cause the state to be
3209   // "invalid" and all queries to be answered conservatively without lookups.
3210   // To be in this state we have to (1) finished the exploration and (3) not
3211   // discovered any non-trivial dead end and (2) not ruled unreachable code
3212   // dead.
3213   if (ToBeExploredFrom.empty() &&
3214       getAnchorScope()->size() == AssumedLiveBlocks.size() &&
3215       llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
3216         return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
3217       }))
3218     return indicatePessimisticFixpoint();
3219   return Change;
3220 }
3221 
3222 /// Liveness information for a call sites.
3223 struct AAIsDeadCallSite final : AAIsDeadFunction {
3224   AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
3225       : AAIsDeadFunction(IRP, A) {}
3226 
3227   /// See AbstractAttribute::initialize(...).
3228   void initialize(Attributor &A) override {
3229     // TODO: Once we have call site specific value information we can provide
3230     //       call site specific liveness information and then it makes
3231     //       sense to specialize attributes for call sites instead of
3232     //       redirecting requests to the callee.
3233     llvm_unreachable("Abstract attributes for liveness are not "
3234                      "supported for call sites yet!");
3235   }
3236 
3237   /// See AbstractAttribute::updateImpl(...).
3238   ChangeStatus updateImpl(Attributor &A) override {
3239     return indicatePessimisticFixpoint();
3240   }
3241 
3242   /// See AbstractAttribute::trackStatistics()
3243   void trackStatistics() const override {}
3244 };
3245 
3246 /// -------------------- Dereferenceable Argument Attribute --------------------
3247 
3248 template <>
3249 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
3250                                                      const DerefState &R) {
3251   ChangeStatus CS0 =
3252       clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
3253   ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
3254   return CS0 | CS1;
3255 }
3256 
3257 struct AADereferenceableImpl : AADereferenceable {
3258   AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
3259       : AADereferenceable(IRP, A) {}
3260   using StateType = DerefState;
3261 
3262   void initialize(Attributor &A) override {
3263     SmallVector<Attribute, 4> Attrs;
3264     getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
3265              Attrs, /* IgnoreSubsumingPositions */ false, &A);
3266     for (const Attribute &Attr : Attrs)
3267       takeKnownDerefBytesMaximum(Attr.getValueAsInt());
3268 
3269     NonNullAA = &A.getAAFor<AANonNull>(*this, getIRPosition(),
3270                                        /* TrackDependence */ false);
3271 
3272     const IRPosition &IRP = this->getIRPosition();
3273     bool IsFnInterface = IRP.isFnInterfaceKind();
3274     Function *FnScope = IRP.getAnchorScope();
3275     if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope)))
3276       indicatePessimisticFixpoint();
3277   }
3278 
3279   /// See AbstractAttribute::getState()
3280   /// {
3281   StateType &getState() override { return *this; }
3282   const StateType &getState() const override { return *this; }
3283   /// }
3284 
3285   /// Helper function for collecting accessed bytes in must-be-executed-context
3286   void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
3287                               DerefState &State) {
3288     const Value *UseV = U->get();
3289     if (!UseV->getType()->isPointerTy())
3290       return;
3291 
3292     Type *PtrTy = UseV->getType();
3293     const DataLayout &DL = A.getDataLayout();
3294     int64_t Offset;
3295     if (const Value *Base = getBasePointerOfAccessPointerOperand(
3296             I, Offset, DL, /*AllowNonInbounds*/ true)) {
3297       if (Base == &getAssociatedValue() &&
3298           getPointerOperand(I, /* AllowVolatile */ false) == UseV) {
3299         uint64_t Size = DL.getTypeStoreSize(PtrTy->getPointerElementType());
3300         State.addAccessedBytes(Offset, Size);
3301       }
3302     }
3303     return;
3304   }
3305 
3306   /// See AAFromMustBeExecutedContext
3307   bool followUse(Attributor &A, const Use *U, const Instruction *I,
3308                  AADereferenceable::StateType &State) {
3309     bool IsNonNull = false;
3310     bool TrackUse = false;
3311     int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
3312         A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
3313 
3314     addAccessedBytesForUse(A, U, I, State);
3315     State.takeKnownDerefBytesMaximum(DerefBytes);
3316     return TrackUse;
3317   }
3318 
3319   /// See AbstractAttribute::manifest(...).
3320   ChangeStatus manifest(Attributor &A) override {
3321     ChangeStatus Change = AADereferenceable::manifest(A);
3322     if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) {
3323       removeAttrs({Attribute::DereferenceableOrNull});
3324       return ChangeStatus::CHANGED;
3325     }
3326     return Change;
3327   }
3328 
3329   void getDeducedAttributes(LLVMContext &Ctx,
3330                             SmallVectorImpl<Attribute> &Attrs) const override {
3331     // TODO: Add *_globally support
3332     if (isAssumedNonNull())
3333       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
3334           Ctx, getAssumedDereferenceableBytes()));
3335     else
3336       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
3337           Ctx, getAssumedDereferenceableBytes()));
3338   }
3339 
3340   /// See AbstractAttribute::getAsStr().
3341   const std::string getAsStr() const override {
3342     if (!getAssumedDereferenceableBytes())
3343       return "unknown-dereferenceable";
3344     return std::string("dereferenceable") +
3345            (isAssumedNonNull() ? "" : "_or_null") +
3346            (isAssumedGlobal() ? "_globally" : "") + "<" +
3347            std::to_string(getKnownDereferenceableBytes()) + "-" +
3348            std::to_string(getAssumedDereferenceableBytes()) + ">";
3349   }
3350 };
3351 
3352 /// Dereferenceable attribute for a floating value.
3353 struct AADereferenceableFloating
3354     : AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl> {
3355   using Base =
3356       AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl>;
3357   AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
3358       : Base(IRP, A) {}
3359 
3360   /// See AbstractAttribute::updateImpl(...).
3361   ChangeStatus updateImpl(Attributor &A) override {
3362     ChangeStatus Change = Base::updateImpl(A);
3363 
3364     const DataLayout &DL = A.getDataLayout();
3365 
3366     auto VisitValueCB = [&](Value &V, const Instruction *, DerefState &T,
3367                             bool Stripped) -> bool {
3368       unsigned IdxWidth =
3369           DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
3370       APInt Offset(IdxWidth, 0);
3371       const Value *Base =
3372           V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
3373 
3374       const auto &AA =
3375           A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base));
3376       int64_t DerefBytes = 0;
3377       if (!Stripped && this == &AA) {
3378         // Use IR information if we did not strip anything.
3379         // TODO: track globally.
3380         bool CanBeNull;
3381         DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull);
3382         T.GlobalState.indicatePessimisticFixpoint();
3383       } else {
3384         const DerefState &DS = static_cast<const DerefState &>(AA.getState());
3385         DerefBytes = DS.DerefBytesState.getAssumed();
3386         T.GlobalState &= DS.GlobalState;
3387       }
3388 
3389       // TODO: Use `AAConstantRange` to infer dereferenceable bytes.
3390 
3391       // For now we do not try to "increase" dereferenceability due to negative
3392       // indices as we first have to come up with code to deal with loops and
3393       // for overflows of the dereferenceable bytes.
3394       int64_t OffsetSExt = Offset.getSExtValue();
3395       if (OffsetSExt < 0)
3396         OffsetSExt = 0;
3397 
3398       T.takeAssumedDerefBytesMinimum(
3399           std::max(int64_t(0), DerefBytes - OffsetSExt));
3400 
3401       if (this == &AA) {
3402         if (!Stripped) {
3403           // If nothing was stripped IR information is all we got.
3404           T.takeKnownDerefBytesMaximum(
3405               std::max(int64_t(0), DerefBytes - OffsetSExt));
3406           T.indicatePessimisticFixpoint();
3407         } else if (OffsetSExt > 0) {
3408           // If something was stripped but there is circular reasoning we look
3409           // for the offset. If it is positive we basically decrease the
3410           // dereferenceable bytes in a circluar loop now, which will simply
3411           // drive them down to the known value in a very slow way which we
3412           // can accelerate.
3413           T.indicatePessimisticFixpoint();
3414         }
3415       }
3416 
3417       return T.isValidState();
3418     };
3419 
3420     DerefState T;
3421     if (!genericValueTraversal<AADereferenceable, DerefState>(
3422             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
3423       return indicatePessimisticFixpoint();
3424 
3425     return Change | clampStateAndIndicateChange(getState(), T);
3426   }
3427 
3428   /// See AbstractAttribute::trackStatistics()
3429   void trackStatistics() const override {
3430     STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
3431   }
3432 };
3433 
3434 /// Dereferenceable attribute for a return value.
3435 struct AADereferenceableReturned final
3436     : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
3437   AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
3438       : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>(
3439             IRP, A) {}
3440 
3441   /// See AbstractAttribute::trackStatistics()
3442   void trackStatistics() const override {
3443     STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
3444   }
3445 };
3446 
3447 /// Dereferenceable attribute for an argument
3448 struct AADereferenceableArgument final
3449     : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
3450           AADereferenceable, AADereferenceableImpl> {
3451   using Base = AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
3452       AADereferenceable, AADereferenceableImpl>;
3453   AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
3454       : Base(IRP, A) {}
3455 
3456   /// See AbstractAttribute::trackStatistics()
3457   void trackStatistics() const override {
3458     STATS_DECLTRACK_ARG_ATTR(dereferenceable)
3459   }
3460 };
3461 
3462 /// Dereferenceable attribute for a call site argument.
3463 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
3464   AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
3465       : AADereferenceableFloating(IRP, A) {}
3466 
3467   /// See AbstractAttribute::trackStatistics()
3468   void trackStatistics() const override {
3469     STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
3470   }
3471 };
3472 
3473 /// Dereferenceable attribute deduction for a call site return value.
3474 struct AADereferenceableCallSiteReturned final
3475     : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
3476           AADereferenceable, AADereferenceableImpl> {
3477   using Base = AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
3478       AADereferenceable, AADereferenceableImpl>;
3479   AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
3480       : Base(IRP, A) {}
3481 
3482   /// See AbstractAttribute::trackStatistics()
3483   void trackStatistics() const override {
3484     STATS_DECLTRACK_CS_ATTR(dereferenceable);
3485   }
3486 };
3487 
3488 // ------------------------ Align Argument Attribute ------------------------
3489 
3490 /// \p Ptr is accessed so we can get alignment information if the ABI requires
3491 /// the element type to be aligned.
3492 static MaybeAlign getKnownAlignmentFromAccessedPtr(const Value *Ptr,
3493                                                    const DataLayout &DL) {
3494   MaybeAlign KnownAlignment = Ptr->getPointerAlignment(DL);
3495   Type *ElementTy = Ptr->getType()->getPointerElementType();
3496   if (ElementTy->isSized())
3497     KnownAlignment = max(KnownAlignment, DL.getABITypeAlign(ElementTy));
3498   return KnownAlignment;
3499 }
3500 
3501 static unsigned getKnownAlignForUse(Attributor &A,
3502                                     AbstractAttribute &QueryingAA,
3503                                     Value &AssociatedValue, const Use *U,
3504                                     const Instruction *I, bool &TrackUse) {
3505   // We need to follow common pointer manipulation uses to the accesses they
3506   // feed into.
3507   if (isa<CastInst>(I)) {
3508     // Follow all but ptr2int casts.
3509     TrackUse = !isa<PtrToIntInst>(I);
3510     return 0;
3511   }
3512   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3513     if (GEP->hasAllConstantIndices()) {
3514       TrackUse = true;
3515       return 0;
3516     }
3517   }
3518 
3519   MaybeAlign MA;
3520   if (const auto *CB = dyn_cast<CallBase>(I)) {
3521     if (CB->isBundleOperand(U) || CB->isCallee(U))
3522       return 0;
3523 
3524     unsigned ArgNo = CB->getArgOperandNo(U);
3525     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
3526     // As long as we only use known information there is no need to track
3527     // dependences here.
3528     auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP,
3529                                         /* TrackDependence */ false);
3530     MA = MaybeAlign(AlignAA.getKnownAlign());
3531   }
3532 
3533   const DataLayout &DL = A.getDataLayout();
3534   const Value *UseV = U->get();
3535   if (auto *SI = dyn_cast<StoreInst>(I)) {
3536     if (SI->getPointerOperand() == UseV) {
3537       if (unsigned SIAlign = SI->getAlignment())
3538         MA = MaybeAlign(SIAlign);
3539       else
3540         MA = getKnownAlignmentFromAccessedPtr(UseV, DL);
3541     }
3542   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
3543     if (LI->getPointerOperand() == UseV) {
3544       if (unsigned LIAlign = LI->getAlignment())
3545         MA = MaybeAlign(LIAlign);
3546       else
3547         MA = getKnownAlignmentFromAccessedPtr(UseV, DL);
3548     }
3549   }
3550 
3551   if (!MA.hasValue() || MA <= 1)
3552     return 0;
3553 
3554   unsigned Alignment = MA->value();
3555   int64_t Offset;
3556 
3557   if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
3558     if (Base == &AssociatedValue) {
3559       // BasePointerAddr + Offset = Alignment * Q for some integer Q.
3560       // So we can say that the maximum power of two which is a divisor of
3561       // gcd(Offset, Alignment) is an alignment.
3562 
3563       uint32_t gcd =
3564           greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment);
3565       Alignment = llvm::PowerOf2Floor(gcd);
3566     }
3567   }
3568 
3569   return Alignment;
3570 }
3571 
3572 struct AAAlignImpl : AAAlign {
3573   AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
3574 
3575   /// See AbstractAttribute::initialize(...).
3576   void initialize(Attributor &A) override {
3577     SmallVector<Attribute, 4> Attrs;
3578     getAttrs({Attribute::Alignment}, Attrs);
3579     for (const Attribute &Attr : Attrs)
3580       takeKnownMaximum(Attr.getValueAsInt());
3581 
3582     if (getIRPosition().isFnInterfaceKind() &&
3583         (!getAnchorScope() ||
3584          !A.isFunctionIPOAmendable(*getAssociatedFunction())))
3585       indicatePessimisticFixpoint();
3586   }
3587 
3588   /// See AbstractAttribute::manifest(...).
3589   ChangeStatus manifest(Attributor &A) override {
3590     ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED;
3591 
3592     // Check for users that allow alignment annotations.
3593     Value &AssociatedValue = getAssociatedValue();
3594     for (const Use &U : AssociatedValue.uses()) {
3595       if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
3596         if (SI->getPointerOperand() == &AssociatedValue)
3597           if (SI->getAlignment() < getAssumedAlign()) {
3598             STATS_DECLTRACK(AAAlign, Store,
3599                             "Number of times alignment added to a store");
3600             SI->setAlignment(Align(getAssumedAlign()));
3601             LoadStoreChanged = ChangeStatus::CHANGED;
3602           }
3603       } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
3604         if (LI->getPointerOperand() == &AssociatedValue)
3605           if (LI->getAlignment() < getAssumedAlign()) {
3606             LI->setAlignment(Align(getAssumedAlign()));
3607             STATS_DECLTRACK(AAAlign, Load,
3608                             "Number of times alignment added to a load");
3609             LoadStoreChanged = ChangeStatus::CHANGED;
3610           }
3611       }
3612     }
3613 
3614     ChangeStatus Changed = AAAlign::manifest(A);
3615 
3616     MaybeAlign InheritAlign =
3617         getAssociatedValue().getPointerAlignment(A.getDataLayout());
3618     if (InheritAlign.valueOrOne() >= getAssumedAlign())
3619       return LoadStoreChanged;
3620     return Changed | LoadStoreChanged;
3621   }
3622 
3623   // TODO: Provide a helper to determine the implied ABI alignment and check in
3624   //       the existing manifest method and a new one for AAAlignImpl that value
3625   //       to avoid making the alignment explicit if it did not improve.
3626 
3627   /// See AbstractAttribute::getDeducedAttributes
3628   virtual void
3629   getDeducedAttributes(LLVMContext &Ctx,
3630                        SmallVectorImpl<Attribute> &Attrs) const override {
3631     if (getAssumedAlign() > 1)
3632       Attrs.emplace_back(
3633           Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
3634   }
3635   /// See AAFromMustBeExecutedContext
3636   bool followUse(Attributor &A, const Use *U, const Instruction *I,
3637                  AAAlign::StateType &State) {
3638     bool TrackUse = false;
3639 
3640     unsigned int KnownAlign =
3641         getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
3642     State.takeKnownMaximum(KnownAlign);
3643 
3644     return TrackUse;
3645   }
3646 
3647   /// See AbstractAttribute::getAsStr().
3648   const std::string getAsStr() const override {
3649     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
3650                                 "-" + std::to_string(getAssumedAlign()) + ">")
3651                              : "unknown-align";
3652   }
3653 };
3654 
3655 /// Align attribute for a floating value.
3656 struct AAAlignFloating : AAFromMustBeExecutedContext<AAAlign, AAAlignImpl> {
3657   using Base = AAFromMustBeExecutedContext<AAAlign, AAAlignImpl>;
3658   AAAlignFloating(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3659 
3660   /// See AbstractAttribute::updateImpl(...).
3661   ChangeStatus updateImpl(Attributor &A) override {
3662     Base::updateImpl(A);
3663 
3664     const DataLayout &DL = A.getDataLayout();
3665 
3666     auto VisitValueCB = [&](Value &V, const Instruction *,
3667                             AAAlign::StateType &T, bool Stripped) -> bool {
3668       const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V));
3669       if (!Stripped && this == &AA) {
3670         // Use only IR information if we did not strip anything.
3671         const MaybeAlign PA = V.getPointerAlignment(DL);
3672         T.takeKnownMaximum(PA ? PA->value() : 0);
3673         T.indicatePessimisticFixpoint();
3674       } else {
3675         // Use abstract attribute information.
3676         const AAAlign::StateType &DS =
3677             static_cast<const AAAlign::StateType &>(AA.getState());
3678         T ^= DS;
3679       }
3680       return T.isValidState();
3681     };
3682 
3683     StateType T;
3684     if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T,
3685                                                    VisitValueCB, getCtxI()))
3686       return indicatePessimisticFixpoint();
3687 
3688     // TODO: If we know we visited all incoming values, thus no are assumed
3689     // dead, we can take the known information from the state T.
3690     return clampStateAndIndicateChange(getState(), T);
3691   }
3692 
3693   /// See AbstractAttribute::trackStatistics()
3694   void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
3695 };
3696 
3697 /// Align attribute for function return value.
3698 struct AAAlignReturned final
3699     : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
3700   AAAlignReturned(const IRPosition &IRP, Attributor &A)
3701       : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP, A) {}
3702 
3703   /// See AbstractAttribute::trackStatistics()
3704   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
3705 };
3706 
3707 /// Align attribute for function argument.
3708 struct AAAlignArgument final
3709     : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AAAlign,
3710                                                               AAAlignImpl> {
3711   using Base =
3712       AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AAAlign,
3713                                                               AAAlignImpl>;
3714   AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3715 
3716   /// See AbstractAttribute::manifest(...).
3717   ChangeStatus manifest(Attributor &A) override {
3718     // If the associated argument is involved in a must-tail call we give up
3719     // because we would need to keep the argument alignments of caller and
3720     // callee in-sync. Just does not seem worth the trouble right now.
3721     if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
3722       return ChangeStatus::UNCHANGED;
3723     return Base::manifest(A);
3724   }
3725 
3726   /// See AbstractAttribute::trackStatistics()
3727   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
3728 };
3729 
3730 struct AAAlignCallSiteArgument final : AAAlignFloating {
3731   AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
3732       : AAAlignFloating(IRP, A) {}
3733 
3734   /// See AbstractAttribute::manifest(...).
3735   ChangeStatus manifest(Attributor &A) override {
3736     // If the associated argument is involved in a must-tail call we give up
3737     // because we would need to keep the argument alignments of caller and
3738     // callee in-sync. Just does not seem worth the trouble right now.
3739     if (Argument *Arg = getAssociatedArgument())
3740       if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
3741         return ChangeStatus::UNCHANGED;
3742     ChangeStatus Changed = AAAlignImpl::manifest(A);
3743     MaybeAlign InheritAlign =
3744         getAssociatedValue().getPointerAlignment(A.getDataLayout());
3745     if (InheritAlign.valueOrOne() >= getAssumedAlign())
3746       Changed = ChangeStatus::UNCHANGED;
3747     return Changed;
3748   }
3749 
3750   /// See AbstractAttribute::updateImpl(Attributor &A).
3751   ChangeStatus updateImpl(Attributor &A) override {
3752     ChangeStatus Changed = AAAlignFloating::updateImpl(A);
3753     if (Argument *Arg = getAssociatedArgument()) {
3754       // We only take known information from the argument
3755       // so we do not need to track a dependence.
3756       const auto &ArgAlignAA = A.getAAFor<AAAlign>(
3757           *this, IRPosition::argument(*Arg), /* TrackDependence */ false);
3758       takeKnownMaximum(ArgAlignAA.getKnownAlign());
3759     }
3760     return Changed;
3761   }
3762 
3763   /// See AbstractAttribute::trackStatistics()
3764   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
3765 };
3766 
3767 /// Align attribute deduction for a call site return value.
3768 struct AAAlignCallSiteReturned final
3769     : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AAAlign,
3770                                                              AAAlignImpl> {
3771   using Base =
3772       AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AAAlign,
3773                                                              AAAlignImpl>;
3774   AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
3775       : Base(IRP, A) {}
3776 
3777   /// See AbstractAttribute::initialize(...).
3778   void initialize(Attributor &A) override {
3779     Base::initialize(A);
3780     Function *F = getAssociatedFunction();
3781     if (!F)
3782       indicatePessimisticFixpoint();
3783   }
3784 
3785   /// See AbstractAttribute::trackStatistics()
3786   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
3787 };
3788 
3789 /// ------------------ Function No-Return Attribute ----------------------------
3790 struct AANoReturnImpl : public AANoReturn {
3791   AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
3792 
3793   /// See AbstractAttribute::initialize(...).
3794   void initialize(Attributor &A) override {
3795     AANoReturn::initialize(A);
3796     Function *F = getAssociatedFunction();
3797     if (!F)
3798       indicatePessimisticFixpoint();
3799   }
3800 
3801   /// See AbstractAttribute::getAsStr().
3802   const std::string getAsStr() const override {
3803     return getAssumed() ? "noreturn" : "may-return";
3804   }
3805 
3806   /// See AbstractAttribute::updateImpl(Attributor &A).
3807   virtual ChangeStatus updateImpl(Attributor &A) override {
3808     auto CheckForNoReturn = [](Instruction &) { return false; };
3809     if (!A.checkForAllInstructions(CheckForNoReturn, *this,
3810                                    {(unsigned)Instruction::Ret}))
3811       return indicatePessimisticFixpoint();
3812     return ChangeStatus::UNCHANGED;
3813   }
3814 };
3815 
3816 struct AANoReturnFunction final : AANoReturnImpl {
3817   AANoReturnFunction(const IRPosition &IRP, Attributor &A)
3818       : AANoReturnImpl(IRP, A) {}
3819 
3820   /// See AbstractAttribute::trackStatistics()
3821   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
3822 };
3823 
3824 /// NoReturn attribute deduction for a call sites.
3825 struct AANoReturnCallSite final : AANoReturnImpl {
3826   AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
3827       : AANoReturnImpl(IRP, A) {}
3828 
3829   /// See AbstractAttribute::updateImpl(...).
3830   ChangeStatus updateImpl(Attributor &A) override {
3831     // TODO: Once we have call site specific value information we can provide
3832     //       call site specific liveness information and then it makes
3833     //       sense to specialize attributes for call sites arguments instead of
3834     //       redirecting requests to the callee argument.
3835     Function *F = getAssociatedFunction();
3836     const IRPosition &FnPos = IRPosition::function(*F);
3837     auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos);
3838     return clampStateAndIndicateChange(
3839         getState(),
3840         static_cast<const AANoReturn::StateType &>(FnAA.getState()));
3841   }
3842 
3843   /// See AbstractAttribute::trackStatistics()
3844   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
3845 };
3846 
3847 /// ----------------------- Variable Capturing ---------------------------------
3848 
3849 /// A class to hold the state of for no-capture attributes.
3850 struct AANoCaptureImpl : public AANoCapture {
3851   AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
3852 
3853   /// See AbstractAttribute::initialize(...).
3854   void initialize(Attributor &A) override {
3855     if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) {
3856       indicateOptimisticFixpoint();
3857       return;
3858     }
3859     Function *AnchorScope = getAnchorScope();
3860     if (isFnInterfaceKind() &&
3861         (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) {
3862       indicatePessimisticFixpoint();
3863       return;
3864     }
3865 
3866     // You cannot "capture" null in the default address space.
3867     if (isa<ConstantPointerNull>(getAssociatedValue()) &&
3868         getAssociatedValue().getType()->getPointerAddressSpace() == 0) {
3869       indicateOptimisticFixpoint();
3870       return;
3871     }
3872 
3873     const Function *F = getArgNo() >= 0 ? getAssociatedFunction() : AnchorScope;
3874 
3875     // Check what state the associated function can actually capture.
3876     if (F)
3877       determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
3878     else
3879       indicatePessimisticFixpoint();
3880   }
3881 
3882   /// See AbstractAttribute::updateImpl(...).
3883   ChangeStatus updateImpl(Attributor &A) override;
3884 
3885   /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...).
3886   virtual void
3887   getDeducedAttributes(LLVMContext &Ctx,
3888                        SmallVectorImpl<Attribute> &Attrs) const override {
3889     if (!isAssumedNoCaptureMaybeReturned())
3890       return;
3891 
3892     if (getArgNo() >= 0) {
3893       if (isAssumedNoCapture())
3894         Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture));
3895       else if (ManifestInternal)
3896         Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
3897     }
3898   }
3899 
3900   /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
3901   /// depending on the ability of the function associated with \p IRP to capture
3902   /// state in memory and through "returning/throwing", respectively.
3903   static void determineFunctionCaptureCapabilities(const IRPosition &IRP,
3904                                                    const Function &F,
3905                                                    BitIntegerState &State) {
3906     // TODO: Once we have memory behavior attributes we should use them here.
3907 
3908     // If we know we cannot communicate or write to memory, we do not care about
3909     // ptr2int anymore.
3910     if (F.onlyReadsMemory() && F.doesNotThrow() &&
3911         F.getReturnType()->isVoidTy()) {
3912       State.addKnownBits(NO_CAPTURE);
3913       return;
3914     }
3915 
3916     // A function cannot capture state in memory if it only reads memory, it can
3917     // however return/throw state and the state might be influenced by the
3918     // pointer value, e.g., loading from a returned pointer might reveal a bit.
3919     if (F.onlyReadsMemory())
3920       State.addKnownBits(NOT_CAPTURED_IN_MEM);
3921 
3922     // A function cannot communicate state back if it does not through
3923     // exceptions and doesn not return values.
3924     if (F.doesNotThrow() && F.getReturnType()->isVoidTy())
3925       State.addKnownBits(NOT_CAPTURED_IN_RET);
3926 
3927     // Check existing "returned" attributes.
3928     int ArgNo = IRP.getArgNo();
3929     if (F.doesNotThrow() && ArgNo >= 0) {
3930       for (unsigned u = 0, e = F.arg_size(); u < e; ++u)
3931         if (F.hasParamAttribute(u, Attribute::Returned)) {
3932           if (u == unsigned(ArgNo))
3933             State.removeAssumedBits(NOT_CAPTURED_IN_RET);
3934           else if (F.onlyReadsMemory())
3935             State.addKnownBits(NO_CAPTURE);
3936           else
3937             State.addKnownBits(NOT_CAPTURED_IN_RET);
3938           break;
3939         }
3940     }
3941   }
3942 
3943   /// See AbstractState::getAsStr().
3944   const std::string getAsStr() const override {
3945     if (isKnownNoCapture())
3946       return "known not-captured";
3947     if (isAssumedNoCapture())
3948       return "assumed not-captured";
3949     if (isKnownNoCaptureMaybeReturned())
3950       return "known not-captured-maybe-returned";
3951     if (isAssumedNoCaptureMaybeReturned())
3952       return "assumed not-captured-maybe-returned";
3953     return "assumed-captured";
3954   }
3955 };
3956 
3957 /// Attributor-aware capture tracker.
3958 struct AACaptureUseTracker final : public CaptureTracker {
3959 
3960   /// Create a capture tracker that can lookup in-flight abstract attributes
3961   /// through the Attributor \p A.
3962   ///
3963   /// If a use leads to a potential capture, \p CapturedInMemory is set and the
3964   /// search is stopped. If a use leads to a return instruction,
3965   /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed.
3966   /// If a use leads to a ptr2int which may capture the value,
3967   /// \p CapturedInInteger is set. If a use is found that is currently assumed
3968   /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies
3969   /// set. All values in \p PotentialCopies are later tracked as well. For every
3970   /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0,
3971   /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger
3972   /// conservatively set to true.
3973   AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA,
3974                       const AAIsDead &IsDeadAA, AANoCapture::StateType &State,
3975                       SmallVectorImpl<const Value *> &PotentialCopies,
3976                       unsigned &RemainingUsesToExplore)
3977       : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State),
3978         PotentialCopies(PotentialCopies),
3979         RemainingUsesToExplore(RemainingUsesToExplore) {}
3980 
3981   /// Determine if \p V maybe captured. *Also updates the state!*
3982   bool valueMayBeCaptured(const Value *V) {
3983     if (V->getType()->isPointerTy()) {
3984       PointerMayBeCaptured(V, this);
3985     } else {
3986       State.indicatePessimisticFixpoint();
3987     }
3988     return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
3989   }
3990 
3991   /// See CaptureTracker::tooManyUses().
3992   void tooManyUses() override {
3993     State.removeAssumedBits(AANoCapture::NO_CAPTURE);
3994   }
3995 
3996   bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override {
3997     if (CaptureTracker::isDereferenceableOrNull(O, DL))
3998       return true;
3999     const auto &DerefAA = A.getAAFor<AADereferenceable>(
4000         NoCaptureAA, IRPosition::value(*O), /* TrackDependence */ true,
4001         DepClassTy::OPTIONAL);
4002     return DerefAA.getAssumedDereferenceableBytes();
4003   }
4004 
4005   /// See CaptureTracker::captured(...).
4006   bool captured(const Use *U) override {
4007     Instruction *UInst = cast<Instruction>(U->getUser());
4008     LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst
4009                       << "\n");
4010 
4011     // Because we may reuse the tracker multiple times we keep track of the
4012     // number of explored uses ourselves as well.
4013     if (RemainingUsesToExplore-- == 0) {
4014       LLVM_DEBUG(dbgs() << " - too many uses to explore!\n");
4015       return isCapturedIn(/* Memory */ true, /* Integer */ true,
4016                           /* Return */ true);
4017     }
4018 
4019     // Deal with ptr2int by following uses.
4020     if (isa<PtrToIntInst>(UInst)) {
4021       LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
4022       return valueMayBeCaptured(UInst);
4023     }
4024 
4025     // Explicitly catch return instructions.
4026     if (isa<ReturnInst>(UInst))
4027       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4028                           /* Return */ true);
4029 
4030     // For now we only use special logic for call sites. However, the tracker
4031     // itself knows about a lot of other non-capturing cases already.
4032     auto *CB = dyn_cast<CallBase>(UInst);
4033     if (!CB || !CB->isArgOperand(U))
4034       return isCapturedIn(/* Memory */ true, /* Integer */ true,
4035                           /* Return */ true);
4036 
4037     unsigned ArgNo = CB->getArgOperandNo(U);
4038     const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
4039     // If we have a abstract no-capture attribute for the argument we can use
4040     // it to justify a non-capture attribute here. This allows recursion!
4041     auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos);
4042     if (ArgNoCaptureAA.isAssumedNoCapture())
4043       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4044                           /* Return */ false);
4045     if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
4046       addPotentialCopy(*CB);
4047       return isCapturedIn(/* Memory */ false, /* Integer */ false,
4048                           /* Return */ false);
4049     }
4050 
4051     // Lastly, we could not find a reason no-capture can be assumed so we don't.
4052     return isCapturedIn(/* Memory */ true, /* Integer */ true,
4053                         /* Return */ true);
4054   }
4055 
4056   /// Register \p CS as potential copy of the value we are checking.
4057   void addPotentialCopy(CallBase &CB) { PotentialCopies.push_back(&CB); }
4058 
4059   /// See CaptureTracker::shouldExplore(...).
4060   bool shouldExplore(const Use *U) override {
4061     // Check liveness and ignore droppable users.
4062     return !U->getUser()->isDroppable() &&
4063            !A.isAssumedDead(*U, &NoCaptureAA, &IsDeadAA);
4064   }
4065 
4066   /// Update the state according to \p CapturedInMem, \p CapturedInInt, and
4067   /// \p CapturedInRet, then return the appropriate value for use in the
4068   /// CaptureTracker::captured() interface.
4069   bool isCapturedIn(bool CapturedInMem, bool CapturedInInt,
4070                     bool CapturedInRet) {
4071     LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
4072                       << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
4073     if (CapturedInMem)
4074       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
4075     if (CapturedInInt)
4076       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
4077     if (CapturedInRet)
4078       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
4079     return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
4080   }
4081 
4082 private:
4083   /// The attributor providing in-flight abstract attributes.
4084   Attributor &A;
4085 
4086   /// The abstract attribute currently updated.
4087   AANoCapture &NoCaptureAA;
4088 
4089   /// The abstract liveness state.
4090   const AAIsDead &IsDeadAA;
4091 
4092   /// The state currently updated.
4093   AANoCapture::StateType &State;
4094 
4095   /// Set of potential copies of the tracked value.
4096   SmallVectorImpl<const Value *> &PotentialCopies;
4097 
4098   /// Global counter to limit the number of explored uses.
4099   unsigned &RemainingUsesToExplore;
4100 };
4101 
4102 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
4103   const IRPosition &IRP = getIRPosition();
4104   const Value *V =
4105       getArgNo() >= 0 ? IRP.getAssociatedArgument() : &IRP.getAssociatedValue();
4106   if (!V)
4107     return indicatePessimisticFixpoint();
4108 
4109   const Function *F =
4110       getArgNo() >= 0 ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
4111   assert(F && "Expected a function!");
4112   const IRPosition &FnPos = IRPosition::function(*F);
4113   const auto &IsDeadAA =
4114       A.getAAFor<AAIsDead>(*this, FnPos, /* TrackDependence */ false);
4115 
4116   AANoCapture::StateType T;
4117 
4118   // Readonly means we cannot capture through memory.
4119   const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(
4120       *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
4121   if (FnMemAA.isAssumedReadOnly()) {
4122     T.addKnownBits(NOT_CAPTURED_IN_MEM);
4123     if (FnMemAA.isKnownReadOnly())
4124       addKnownBits(NOT_CAPTURED_IN_MEM);
4125   }
4126 
4127   // Make sure all returned values are different than the underlying value.
4128   // TODO: we could do this in a more sophisticated way inside
4129   //       AAReturnedValues, e.g., track all values that escape through returns
4130   //       directly somehow.
4131   auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) {
4132     bool SeenConstant = false;
4133     for (auto &It : RVAA.returned_values()) {
4134       if (isa<Constant>(It.first)) {
4135         if (SeenConstant)
4136           return false;
4137         SeenConstant = true;
4138       } else if (!isa<Argument>(It.first) ||
4139                  It.first == getAssociatedArgument())
4140         return false;
4141     }
4142     return true;
4143   };
4144 
4145   const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(
4146       *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
4147   if (NoUnwindAA.isAssumedNoUnwind()) {
4148     bool IsVoidTy = F->getReturnType()->isVoidTy();
4149     const AAReturnedValues *RVAA =
4150         IsVoidTy ? nullptr
4151                  : &A.getAAFor<AAReturnedValues>(*this, FnPos,
4152                                                  /* TrackDependence */ true,
4153                                                  DepClassTy::OPTIONAL);
4154     if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
4155       T.addKnownBits(NOT_CAPTURED_IN_RET);
4156       if (T.isKnown(NOT_CAPTURED_IN_MEM))
4157         return ChangeStatus::UNCHANGED;
4158       if (NoUnwindAA.isKnownNoUnwind() &&
4159           (IsVoidTy || RVAA->getState().isAtFixpoint())) {
4160         addKnownBits(NOT_CAPTURED_IN_RET);
4161         if (isKnown(NOT_CAPTURED_IN_MEM))
4162           return indicateOptimisticFixpoint();
4163       }
4164     }
4165   }
4166 
4167   // Use the CaptureTracker interface and logic with the specialized tracker,
4168   // defined in AACaptureUseTracker, that can look at in-flight abstract
4169   // attributes and directly updates the assumed state.
4170   SmallVector<const Value *, 4> PotentialCopies;
4171   unsigned RemainingUsesToExplore = DefaultMaxUsesToExplore;
4172   AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies,
4173                               RemainingUsesToExplore);
4174 
4175   // Check all potential copies of the associated value until we can assume
4176   // none will be captured or we have to assume at least one might be.
4177   unsigned Idx = 0;
4178   PotentialCopies.push_back(V);
4179   while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size())
4180     Tracker.valueMayBeCaptured(PotentialCopies[Idx++]);
4181 
4182   AANoCapture::StateType &S = getState();
4183   auto Assumed = S.getAssumed();
4184   S.intersectAssumedBits(T.getAssumed());
4185   if (!isAssumedNoCaptureMaybeReturned())
4186     return indicatePessimisticFixpoint();
4187   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
4188                                    : ChangeStatus::CHANGED;
4189 }
4190 
4191 /// NoCapture attribute for function arguments.
4192 struct AANoCaptureArgument final : AANoCaptureImpl {
4193   AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
4194       : AANoCaptureImpl(IRP, A) {}
4195 
4196   /// See AbstractAttribute::trackStatistics()
4197   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
4198 };
4199 
4200 /// NoCapture attribute for call site arguments.
4201 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
4202   AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
4203       : AANoCaptureImpl(IRP, A) {}
4204 
4205   /// See AbstractAttribute::initialize(...).
4206   void initialize(Attributor &A) override {
4207     if (Argument *Arg = getAssociatedArgument())
4208       if (Arg->hasByValAttr())
4209         indicateOptimisticFixpoint();
4210     AANoCaptureImpl::initialize(A);
4211   }
4212 
4213   /// See AbstractAttribute::updateImpl(...).
4214   ChangeStatus updateImpl(Attributor &A) override {
4215     // TODO: Once we have call site specific value information we can provide
4216     //       call site specific liveness information and then it makes
4217     //       sense to specialize attributes for call sites arguments instead of
4218     //       redirecting requests to the callee argument.
4219     Argument *Arg = getAssociatedArgument();
4220     if (!Arg)
4221       return indicatePessimisticFixpoint();
4222     const IRPosition &ArgPos = IRPosition::argument(*Arg);
4223     auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos);
4224     return clampStateAndIndicateChange(
4225         getState(),
4226         static_cast<const AANoCapture::StateType &>(ArgAA.getState()));
4227   }
4228 
4229   /// See AbstractAttribute::trackStatistics()
4230   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)};
4231 };
4232 
4233 /// NoCapture attribute for floating values.
4234 struct AANoCaptureFloating final : AANoCaptureImpl {
4235   AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
4236       : AANoCaptureImpl(IRP, A) {}
4237 
4238   /// See AbstractAttribute::trackStatistics()
4239   void trackStatistics() const override {
4240     STATS_DECLTRACK_FLOATING_ATTR(nocapture)
4241   }
4242 };
4243 
4244 /// NoCapture attribute for function return value.
4245 struct AANoCaptureReturned final : AANoCaptureImpl {
4246   AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
4247       : AANoCaptureImpl(IRP, A) {
4248     llvm_unreachable("NoCapture is not applicable to function returns!");
4249   }
4250 
4251   /// See AbstractAttribute::initialize(...).
4252   void initialize(Attributor &A) override {
4253     llvm_unreachable("NoCapture is not applicable to function returns!");
4254   }
4255 
4256   /// See AbstractAttribute::updateImpl(...).
4257   ChangeStatus updateImpl(Attributor &A) override {
4258     llvm_unreachable("NoCapture is not applicable to function returns!");
4259   }
4260 
4261   /// See AbstractAttribute::trackStatistics()
4262   void trackStatistics() const override {}
4263 };
4264 
4265 /// NoCapture attribute deduction for a call site return value.
4266 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
4267   AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
4268       : AANoCaptureImpl(IRP, A) {}
4269 
4270   /// See AbstractAttribute::trackStatistics()
4271   void trackStatistics() const override {
4272     STATS_DECLTRACK_CSRET_ATTR(nocapture)
4273   }
4274 };
4275 
4276 /// ------------------ Value Simplify Attribute ----------------------------
4277 struct AAValueSimplifyImpl : AAValueSimplify {
4278   AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
4279       : AAValueSimplify(IRP, A) {}
4280 
4281   /// See AbstractAttribute::initialize(...).
4282   void initialize(Attributor &A) override {
4283     if (getAssociatedValue().getType()->isVoidTy())
4284       indicatePessimisticFixpoint();
4285   }
4286 
4287   /// See AbstractAttribute::getAsStr().
4288   const std::string getAsStr() const override {
4289     return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple")
4290                         : "not-simple";
4291   }
4292 
4293   /// See AbstractAttribute::trackStatistics()
4294   void trackStatistics() const override {}
4295 
4296   /// See AAValueSimplify::getAssumedSimplifiedValue()
4297   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
4298     if (!getAssumed())
4299       return const_cast<Value *>(&getAssociatedValue());
4300     return SimplifiedAssociatedValue;
4301   }
4302 
4303   /// Helper function for querying AAValueSimplify and updating candicate.
4304   /// \param QueryingValue Value trying to unify with SimplifiedValue
4305   /// \param AccumulatedSimplifiedValue Current simplification result.
4306   static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
4307                              Value &QueryingValue,
4308                              Optional<Value *> &AccumulatedSimplifiedValue) {
4309     // FIXME: Add a typecast support.
4310 
4311     auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>(
4312         QueryingAA, IRPosition::value(QueryingValue));
4313 
4314     Optional<Value *> QueryingValueSimplified =
4315         ValueSimplifyAA.getAssumedSimplifiedValue(A);
4316 
4317     if (!QueryingValueSimplified.hasValue())
4318       return true;
4319 
4320     if (!QueryingValueSimplified.getValue())
4321       return false;
4322 
4323     Value &QueryingValueSimplifiedUnwrapped =
4324         *QueryingValueSimplified.getValue();
4325 
4326     if (AccumulatedSimplifiedValue.hasValue() &&
4327         !isa<UndefValue>(AccumulatedSimplifiedValue.getValue()) &&
4328         !isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4329       return AccumulatedSimplifiedValue == QueryingValueSimplified;
4330     if (AccumulatedSimplifiedValue.hasValue() &&
4331         isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4332       return true;
4333 
4334     LLVM_DEBUG(dbgs() << "[ValueSimplify] " << QueryingValue
4335                       << " is assumed to be "
4336                       << QueryingValueSimplifiedUnwrapped << "\n");
4337 
4338     AccumulatedSimplifiedValue = QueryingValueSimplified;
4339     return true;
4340   }
4341 
4342   bool askSimplifiedValueForAAValueConstantRange(Attributor &A) {
4343     if (!getAssociatedValue().getType()->isIntegerTy())
4344       return false;
4345 
4346     const auto &ValueConstantRangeAA =
4347         A.getAAFor<AAValueConstantRange>(*this, getIRPosition());
4348 
4349     Optional<ConstantInt *> COpt =
4350         ValueConstantRangeAA.getAssumedConstantInt(A);
4351     if (COpt.hasValue()) {
4352       if (auto *C = COpt.getValue())
4353         SimplifiedAssociatedValue = C;
4354       else
4355         return false;
4356     } else {
4357       SimplifiedAssociatedValue = llvm::None;
4358     }
4359     return true;
4360   }
4361 
4362   /// See AbstractAttribute::manifest(...).
4363   ChangeStatus manifest(Attributor &A) override {
4364     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4365 
4366     if (SimplifiedAssociatedValue.hasValue() &&
4367         !SimplifiedAssociatedValue.getValue())
4368       return Changed;
4369 
4370     Value &V = getAssociatedValue();
4371     auto *C = SimplifiedAssociatedValue.hasValue()
4372                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4373                   : UndefValue::get(V.getType());
4374     if (C) {
4375       // We can replace the AssociatedValue with the constant.
4376       if (!V.user_empty() && &V != C && V.getType() == C->getType()) {
4377         LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *C
4378                           << " :: " << *this << "\n");
4379         if (A.changeValueAfterManifest(V, *C))
4380           Changed = ChangeStatus::CHANGED;
4381       }
4382     }
4383 
4384     return Changed | AAValueSimplify::manifest(A);
4385   }
4386 
4387   /// See AbstractState::indicatePessimisticFixpoint(...).
4388   ChangeStatus indicatePessimisticFixpoint() override {
4389     // NOTE: Associated value will be returned in a pessimistic fixpoint and is
4390     // regarded as known. That's why`indicateOptimisticFixpoint` is called.
4391     SimplifiedAssociatedValue = &getAssociatedValue();
4392     indicateOptimisticFixpoint();
4393     return ChangeStatus::CHANGED;
4394   }
4395 
4396 protected:
4397   // An assumed simplified value. Initially, it is set to Optional::None, which
4398   // means that the value is not clear under current assumption. If in the
4399   // pessimistic state, getAssumedSimplifiedValue doesn't return this value but
4400   // returns orignal associated value.
4401   Optional<Value *> SimplifiedAssociatedValue;
4402 };
4403 
4404 struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
4405   AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
4406       : AAValueSimplifyImpl(IRP, A) {}
4407 
4408   void initialize(Attributor &A) override {
4409     AAValueSimplifyImpl::initialize(A);
4410     if (!getAnchorScope() || getAnchorScope()->isDeclaration())
4411       indicatePessimisticFixpoint();
4412     if (hasAttr({Attribute::InAlloca, Attribute::StructRet, Attribute::Nest},
4413                 /* IgnoreSubsumingPositions */ true))
4414       indicatePessimisticFixpoint();
4415 
4416     // FIXME: This is a hack to prevent us from propagating function poiner in
4417     // the new pass manager CGSCC pass as it creates call edges the
4418     // CallGraphUpdater cannot handle yet.
4419     Value &V = getAssociatedValue();
4420     if (V.getType()->isPointerTy() &&
4421         V.getType()->getPointerElementType()->isFunctionTy() &&
4422         !A.isModulePass())
4423       indicatePessimisticFixpoint();
4424   }
4425 
4426   /// See AbstractAttribute::updateImpl(...).
4427   ChangeStatus updateImpl(Attributor &A) override {
4428     // Byval is only replacable if it is readonly otherwise we would write into
4429     // the replaced value and not the copy that byval creates implicitly.
4430     Argument *Arg = getAssociatedArgument();
4431     if (Arg->hasByValAttr()) {
4432       // TODO: We probably need to verify synchronization is not an issue, e.g.,
4433       //       there is no race by not copying a constant byval.
4434       const auto &MemAA = A.getAAFor<AAMemoryBehavior>(*this, getIRPosition());
4435       if (!MemAA.isAssumedReadOnly())
4436         return indicatePessimisticFixpoint();
4437     }
4438 
4439     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4440 
4441     auto PredForCallSite = [&](AbstractCallSite ACS) {
4442       const IRPosition &ACSArgPos =
4443           IRPosition::callsite_argument(ACS, getArgNo());
4444       // Check if a coresponding argument was found or if it is on not
4445       // associated (which can happen for callback calls).
4446       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
4447         return false;
4448 
4449       // We can only propagate thread independent values through callbacks.
4450       // This is different to direct/indirect call sites because for them we
4451       // know the thread executing the caller and callee is the same. For
4452       // callbacks this is not guaranteed, thus a thread dependent value could
4453       // be different for the caller and callee, making it invalid to propagate.
4454       Value &ArgOp = ACSArgPos.getAssociatedValue();
4455       if (ACS.isCallbackCall())
4456         if (auto *C = dyn_cast<Constant>(&ArgOp))
4457           if (C->isThreadDependent())
4458             return false;
4459       return checkAndUpdate(A, *this, ArgOp, SimplifiedAssociatedValue);
4460     };
4461 
4462     bool AllCallSitesKnown;
4463     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
4464                                 AllCallSitesKnown))
4465       if (!askSimplifiedValueForAAValueConstantRange(A))
4466         return indicatePessimisticFixpoint();
4467 
4468     // If a candicate was found in this update, return CHANGED.
4469     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4470                ? ChangeStatus::UNCHANGED
4471                : ChangeStatus ::CHANGED;
4472   }
4473 
4474   /// See AbstractAttribute::trackStatistics()
4475   void trackStatistics() const override {
4476     STATS_DECLTRACK_ARG_ATTR(value_simplify)
4477   }
4478 };
4479 
4480 struct AAValueSimplifyReturned : AAValueSimplifyImpl {
4481   AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
4482       : AAValueSimplifyImpl(IRP, A) {}
4483 
4484   /// See AbstractAttribute::updateImpl(...).
4485   ChangeStatus updateImpl(Attributor &A) override {
4486     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4487 
4488     auto PredForReturned = [&](Value &V) {
4489       return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
4490     };
4491 
4492     if (!A.checkForAllReturnedValues(PredForReturned, *this))
4493       if (!askSimplifiedValueForAAValueConstantRange(A))
4494         return indicatePessimisticFixpoint();
4495 
4496     // If a candicate was found in this update, return CHANGED.
4497     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4498                ? ChangeStatus::UNCHANGED
4499                : ChangeStatus ::CHANGED;
4500   }
4501 
4502   ChangeStatus manifest(Attributor &A) override {
4503     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4504 
4505     if (SimplifiedAssociatedValue.hasValue() &&
4506         !SimplifiedAssociatedValue.getValue())
4507       return Changed;
4508 
4509     Value &V = getAssociatedValue();
4510     auto *C = SimplifiedAssociatedValue.hasValue()
4511                   ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())
4512                   : UndefValue::get(V.getType());
4513     if (C) {
4514       auto PredForReturned =
4515           [&](Value &V, const SmallSetVector<ReturnInst *, 4> &RetInsts) {
4516             // We can replace the AssociatedValue with the constant.
4517             if (&V == C || V.getType() != C->getType() || isa<UndefValue>(V))
4518               return true;
4519 
4520             for (ReturnInst *RI : RetInsts) {
4521               if (RI->getFunction() != getAnchorScope())
4522                 continue;
4523               LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *C
4524                                 << " in " << *RI << " :: " << *this << "\n");
4525               if (A.changeUseAfterManifest(RI->getOperandUse(0), *C))
4526                 Changed = ChangeStatus::CHANGED;
4527             }
4528             return true;
4529           };
4530       A.checkForAllReturnedValuesAndReturnInsts(PredForReturned, *this);
4531     }
4532 
4533     return Changed | AAValueSimplify::manifest(A);
4534   }
4535 
4536   /// See AbstractAttribute::trackStatistics()
4537   void trackStatistics() const override {
4538     STATS_DECLTRACK_FNRET_ATTR(value_simplify)
4539   }
4540 };
4541 
4542 struct AAValueSimplifyFloating : AAValueSimplifyImpl {
4543   AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
4544       : AAValueSimplifyImpl(IRP, A) {}
4545 
4546   /// See AbstractAttribute::initialize(...).
4547   void initialize(Attributor &A) override {
4548     // FIXME: This might have exposed a SCC iterator update bug in the old PM.
4549     //        Needs investigation.
4550     // AAValueSimplifyImpl::initialize(A);
4551     Value &V = getAnchorValue();
4552 
4553     // TODO: add other stuffs
4554     if (isa<Constant>(V))
4555       indicatePessimisticFixpoint();
4556   }
4557 
4558   /// See AbstractAttribute::updateImpl(...).
4559   ChangeStatus updateImpl(Attributor &A) override {
4560     bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4561 
4562     auto VisitValueCB = [&](Value &V, const Instruction *CtxI, bool &,
4563                             bool Stripped) -> bool {
4564       auto &AA = A.getAAFor<AAValueSimplify>(*this, IRPosition::value(V));
4565       if (!Stripped && this == &AA) {
4566         // TODO: Look the instruction and check recursively.
4567 
4568         LLVM_DEBUG(dbgs() << "[ValueSimplify] Can't be stripped more : " << V
4569                           << "\n");
4570         return false;
4571       }
4572       return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue);
4573     };
4574 
4575     bool Dummy = false;
4576     if (!genericValueTraversal<AAValueSimplify, bool>(
4577             A, getIRPosition(), *this, Dummy, VisitValueCB, getCtxI()))
4578       if (!askSimplifiedValueForAAValueConstantRange(A))
4579         return indicatePessimisticFixpoint();
4580 
4581     // If a candicate was found in this update, return CHANGED.
4582 
4583     return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4584                ? ChangeStatus::UNCHANGED
4585                : ChangeStatus ::CHANGED;
4586   }
4587 
4588   /// See AbstractAttribute::trackStatistics()
4589   void trackStatistics() const override {
4590     STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
4591   }
4592 };
4593 
4594 struct AAValueSimplifyFunction : AAValueSimplifyImpl {
4595   AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
4596       : AAValueSimplifyImpl(IRP, A) {}
4597 
4598   /// See AbstractAttribute::initialize(...).
4599   void initialize(Attributor &A) override {
4600     SimplifiedAssociatedValue = &getAnchorValue();
4601     indicateOptimisticFixpoint();
4602   }
4603   /// See AbstractAttribute::initialize(...).
4604   ChangeStatus updateImpl(Attributor &A) override {
4605     llvm_unreachable(
4606         "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
4607   }
4608   /// See AbstractAttribute::trackStatistics()
4609   void trackStatistics() const override {
4610     STATS_DECLTRACK_FN_ATTR(value_simplify)
4611   }
4612 };
4613 
4614 struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
4615   AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
4616       : AAValueSimplifyFunction(IRP, A) {}
4617   /// See AbstractAttribute::trackStatistics()
4618   void trackStatistics() const override {
4619     STATS_DECLTRACK_CS_ATTR(value_simplify)
4620   }
4621 };
4622 
4623 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned {
4624   AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
4625       : AAValueSimplifyReturned(IRP, A) {}
4626 
4627   /// See AbstractAttribute::manifest(...).
4628   ChangeStatus manifest(Attributor &A) override {
4629     return AAValueSimplifyImpl::manifest(A);
4630   }
4631 
4632   void trackStatistics() const override {
4633     STATS_DECLTRACK_CSRET_ATTR(value_simplify)
4634   }
4635 };
4636 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
4637   AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
4638       : AAValueSimplifyFloating(IRP, A) {}
4639 
4640   void trackStatistics() const override {
4641     STATS_DECLTRACK_CSARG_ATTR(value_simplify)
4642   }
4643 };
4644 
4645 /// ----------------------- Heap-To-Stack Conversion ---------------------------
4646 struct AAHeapToStackImpl : public AAHeapToStack {
4647   AAHeapToStackImpl(const IRPosition &IRP, Attributor &A)
4648       : AAHeapToStack(IRP, A) {}
4649 
4650   const std::string getAsStr() const override {
4651     return "[H2S] Mallocs: " + std::to_string(MallocCalls.size());
4652   }
4653 
4654   ChangeStatus manifest(Attributor &A) override {
4655     assert(getState().isValidState() &&
4656            "Attempted to manifest an invalid state!");
4657 
4658     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
4659     Function *F = getAnchorScope();
4660     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
4661 
4662     for (Instruction *MallocCall : MallocCalls) {
4663       // This malloc cannot be replaced.
4664       if (BadMallocCalls.count(MallocCall))
4665         continue;
4666 
4667       for (Instruction *FreeCall : FreesForMalloc[MallocCall]) {
4668         LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
4669         A.deleteAfterManifest(*FreeCall);
4670         HasChanged = ChangeStatus::CHANGED;
4671       }
4672 
4673       LLVM_DEBUG(dbgs() << "H2S: Removing malloc call: " << *MallocCall
4674                         << "\n");
4675 
4676       MaybeAlign Alignment;
4677       Constant *Size;
4678       if (isCallocLikeFn(MallocCall, TLI)) {
4679         auto *Num = cast<ConstantInt>(MallocCall->getOperand(0));
4680         auto *SizeT = cast<ConstantInt>(MallocCall->getOperand(1));
4681         APInt TotalSize = SizeT->getValue() * Num->getValue();
4682         Size =
4683             ConstantInt::get(MallocCall->getOperand(0)->getType(), TotalSize);
4684       } else if (isAlignedAllocLikeFn(MallocCall, TLI)) {
4685         Size = cast<ConstantInt>(MallocCall->getOperand(1));
4686         Alignment = MaybeAlign(cast<ConstantInt>(MallocCall->getOperand(0))
4687                                    ->getValue()
4688                                    .getZExtValue());
4689       } else {
4690         Size = cast<ConstantInt>(MallocCall->getOperand(0));
4691       }
4692 
4693       unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace();
4694       Instruction *AI =
4695           new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment,
4696                          "", MallocCall->getNextNode());
4697 
4698       if (AI->getType() != MallocCall->getType())
4699         AI = new BitCastInst(AI, MallocCall->getType(), "malloc_bc",
4700                              AI->getNextNode());
4701 
4702       A.changeValueAfterManifest(*MallocCall, *AI);
4703 
4704       if (auto *II = dyn_cast<InvokeInst>(MallocCall)) {
4705         auto *NBB = II->getNormalDest();
4706         BranchInst::Create(NBB, MallocCall->getParent());
4707         A.deleteAfterManifest(*MallocCall);
4708       } else {
4709         A.deleteAfterManifest(*MallocCall);
4710       }
4711 
4712       // Zero out the allocated memory if it was a calloc.
4713       if (isCallocLikeFn(MallocCall, TLI)) {
4714         auto *BI = new BitCastInst(AI, MallocCall->getType(), "calloc_bc",
4715                                    AI->getNextNode());
4716         Value *Ops[] = {
4717             BI, ConstantInt::get(F->getContext(), APInt(8, 0, false)), Size,
4718             ConstantInt::get(Type::getInt1Ty(F->getContext()), false)};
4719 
4720         Type *Tys[] = {BI->getType(), MallocCall->getOperand(0)->getType()};
4721         Module *M = F->getParent();
4722         Function *Fn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
4723         CallInst::Create(Fn, Ops, "", BI->getNextNode());
4724       }
4725       HasChanged = ChangeStatus::CHANGED;
4726     }
4727 
4728     return HasChanged;
4729   }
4730 
4731   /// Collection of all malloc calls in a function.
4732   SmallSetVector<Instruction *, 4> MallocCalls;
4733 
4734   /// Collection of malloc calls that cannot be converted.
4735   DenseSet<const Instruction *> BadMallocCalls;
4736 
4737   /// A map for each malloc call to the set of associated free calls.
4738   DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>> FreesForMalloc;
4739 
4740   ChangeStatus updateImpl(Attributor &A) override;
4741 };
4742 
4743 ChangeStatus AAHeapToStackImpl::updateImpl(Attributor &A) {
4744   const Function *F = getAnchorScope();
4745   const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
4746 
4747   MustBeExecutedContextExplorer &Explorer =
4748       A.getInfoCache().getMustBeExecutedContextExplorer();
4749 
4750   auto FreeCheck = [&](Instruction &I) {
4751     const auto &Frees = FreesForMalloc.lookup(&I);
4752     if (Frees.size() != 1)
4753       return false;
4754     Instruction *UniqueFree = *Frees.begin();
4755     return Explorer.findInContextOf(UniqueFree, I.getNextNode());
4756   };
4757 
4758   auto UsesCheck = [&](Instruction &I) {
4759     bool ValidUsesOnly = true;
4760     bool MustUse = true;
4761     auto Pred = [&](const Use &U, bool &Follow) -> bool {
4762       Instruction *UserI = cast<Instruction>(U.getUser());
4763       if (isa<LoadInst>(UserI))
4764         return true;
4765       if (auto *SI = dyn_cast<StoreInst>(UserI)) {
4766         if (SI->getValueOperand() == U.get()) {
4767           LLVM_DEBUG(dbgs()
4768                      << "[H2S] escaping store to memory: " << *UserI << "\n");
4769           ValidUsesOnly = false;
4770         } else {
4771           // A store into the malloc'ed memory is fine.
4772         }
4773         return true;
4774       }
4775       if (auto *CB = dyn_cast<CallBase>(UserI)) {
4776         if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
4777           return true;
4778         // Record malloc.
4779         if (isFreeCall(UserI, TLI)) {
4780           if (MustUse) {
4781             FreesForMalloc[&I].insert(UserI);
4782           } else {
4783             LLVM_DEBUG(dbgs() << "[H2S] free potentially on different mallocs: "
4784                               << *UserI << "\n");
4785             ValidUsesOnly = false;
4786           }
4787           return true;
4788         }
4789 
4790         unsigned ArgNo = CB->getArgOperandNo(&U);
4791 
4792         const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
4793             *this, IRPosition::callsite_argument(*CB, ArgNo));
4794 
4795         // If a callsite argument use is nofree, we are fine.
4796         const auto &ArgNoFreeAA = A.getAAFor<AANoFree>(
4797             *this, IRPosition::callsite_argument(*CB, ArgNo));
4798 
4799         if (!NoCaptureAA.isAssumedNoCapture() ||
4800             !ArgNoFreeAA.isAssumedNoFree()) {
4801           LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
4802           ValidUsesOnly = false;
4803         }
4804         return true;
4805       }
4806 
4807       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
4808           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
4809         MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI));
4810         Follow = true;
4811         return true;
4812       }
4813       // Unknown user for which we can not track uses further (in a way that
4814       // makes sense).
4815       LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
4816       ValidUsesOnly = false;
4817       return true;
4818     };
4819     A.checkForAllUses(Pred, *this, I);
4820     return ValidUsesOnly;
4821   };
4822 
4823   auto MallocCallocCheck = [&](Instruction &I) {
4824     if (BadMallocCalls.count(&I))
4825       return true;
4826 
4827     bool IsMalloc = isMallocLikeFn(&I, TLI);
4828     bool IsAlignedAllocLike = isAlignedAllocLikeFn(&I, TLI);
4829     bool IsCalloc = !IsMalloc && isCallocLikeFn(&I, TLI);
4830     if (!IsMalloc && !IsAlignedAllocLike && !IsCalloc) {
4831       BadMallocCalls.insert(&I);
4832       return true;
4833     }
4834 
4835     if (IsMalloc) {
4836       if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(0)))
4837         if (Size->getValue().ule(MaxHeapToStackSize))
4838           if (UsesCheck(I) || FreeCheck(I)) {
4839             MallocCalls.insert(&I);
4840             return true;
4841           }
4842     } else if (IsAlignedAllocLike && isa<ConstantInt>(I.getOperand(0))) {
4843       // Only if the alignment and sizes are constant.
4844       if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
4845         if (Size->getValue().ule(MaxHeapToStackSize))
4846           if (UsesCheck(I) || FreeCheck(I)) {
4847             MallocCalls.insert(&I);
4848             return true;
4849           }
4850     } else if (IsCalloc) {
4851       bool Overflow = false;
4852       if (auto *Num = dyn_cast<ConstantInt>(I.getOperand(0)))
4853         if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1)))
4854           if ((Size->getValue().umul_ov(Num->getValue(), Overflow))
4855                   .ule(MaxHeapToStackSize))
4856             if (!Overflow && (UsesCheck(I) || FreeCheck(I))) {
4857               MallocCalls.insert(&I);
4858               return true;
4859             }
4860     }
4861 
4862     BadMallocCalls.insert(&I);
4863     return true;
4864   };
4865 
4866   size_t NumBadMallocs = BadMallocCalls.size();
4867 
4868   A.checkForAllCallLikeInstructions(MallocCallocCheck, *this);
4869 
4870   if (NumBadMallocs != BadMallocCalls.size())
4871     return ChangeStatus::CHANGED;
4872 
4873   return ChangeStatus::UNCHANGED;
4874 }
4875 
4876 struct AAHeapToStackFunction final : public AAHeapToStackImpl {
4877   AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
4878       : AAHeapToStackImpl(IRP, A) {}
4879 
4880   /// See AbstractAttribute::trackStatistics().
4881   void trackStatistics() const override {
4882     STATS_DECL(
4883         MallocCalls, Function,
4884         "Number of malloc/calloc/aligned_alloc calls converted to allocas");
4885     for (auto *C : MallocCalls)
4886       if (!BadMallocCalls.count(C))
4887         ++BUILD_STAT_NAME(MallocCalls, Function);
4888   }
4889 };
4890 
4891 /// ----------------------- Privatizable Pointers ------------------------------
4892 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
4893   AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
4894       : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {}
4895 
4896   ChangeStatus indicatePessimisticFixpoint() override {
4897     AAPrivatizablePtr::indicatePessimisticFixpoint();
4898     PrivatizableType = nullptr;
4899     return ChangeStatus::CHANGED;
4900   }
4901 
4902   /// Identify the type we can chose for a private copy of the underlying
4903   /// argument. None means it is not clear yet, nullptr means there is none.
4904   virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
4905 
4906   /// Return a privatizable type that encloses both T0 and T1.
4907   /// TODO: This is merely a stub for now as we should manage a mapping as well.
4908   Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
4909     if (!T0.hasValue())
4910       return T1;
4911     if (!T1.hasValue())
4912       return T0;
4913     if (T0 == T1)
4914       return T0;
4915     return nullptr;
4916   }
4917 
4918   Optional<Type *> getPrivatizableType() const override {
4919     return PrivatizableType;
4920   }
4921 
4922   const std::string getAsStr() const override {
4923     return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
4924   }
4925 
4926 protected:
4927   Optional<Type *> PrivatizableType;
4928 };
4929 
4930 // TODO: Do this for call site arguments (probably also other values) as well.
4931 
4932 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
4933   AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
4934       : AAPrivatizablePtrImpl(IRP, A) {}
4935 
4936   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
4937   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
4938     // If this is a byval argument and we know all the call sites (so we can
4939     // rewrite them), there is no need to check them explicitly.
4940     bool AllCallSitesKnown;
4941     if (getIRPosition().hasAttr(Attribute::ByVal) &&
4942         A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
4943                                true, AllCallSitesKnown))
4944       return getAssociatedValue().getType()->getPointerElementType();
4945 
4946     Optional<Type *> Ty;
4947     unsigned ArgNo = getIRPosition().getArgNo();
4948 
4949     // Make sure the associated call site argument has the same type at all call
4950     // sites and it is an allocation we know is safe to privatize, for now that
4951     // means we only allow alloca instructions.
4952     // TODO: We can additionally analyze the accesses in the callee to  create
4953     //       the type from that information instead. That is a little more
4954     //       involved and will be done in a follow up patch.
4955     auto CallSiteCheck = [&](AbstractCallSite ACS) {
4956       IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
4957       // Check if a coresponding argument was found or if it is one not
4958       // associated (which can happen for callback calls).
4959       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
4960         return false;
4961 
4962       // Check that all call sites agree on a type.
4963       auto &PrivCSArgAA = A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos);
4964       Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType();
4965 
4966       LLVM_DEBUG({
4967         dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
4968         if (CSTy.hasValue() && CSTy.getValue())
4969           CSTy.getValue()->print(dbgs());
4970         else if (CSTy.hasValue())
4971           dbgs() << "<nullptr>";
4972         else
4973           dbgs() << "<none>";
4974       });
4975 
4976       Ty = combineTypes(Ty, CSTy);
4977 
4978       LLVM_DEBUG({
4979         dbgs() << " : New Type: ";
4980         if (Ty.hasValue() && Ty.getValue())
4981           Ty.getValue()->print(dbgs());
4982         else if (Ty.hasValue())
4983           dbgs() << "<nullptr>";
4984         else
4985           dbgs() << "<none>";
4986         dbgs() << "\n";
4987       });
4988 
4989       return !Ty.hasValue() || Ty.getValue();
4990     };
4991 
4992     if (!A.checkForAllCallSites(CallSiteCheck, *this, true, AllCallSitesKnown))
4993       return nullptr;
4994     return Ty;
4995   }
4996 
4997   /// See AbstractAttribute::updateImpl(...).
4998   ChangeStatus updateImpl(Attributor &A) override {
4999     PrivatizableType = identifyPrivatizableType(A);
5000     if (!PrivatizableType.hasValue())
5001       return ChangeStatus::UNCHANGED;
5002     if (!PrivatizableType.getValue())
5003       return indicatePessimisticFixpoint();
5004 
5005     // Avoid arguments with padding for now.
5006     if (!getIRPosition().hasAttr(Attribute::ByVal) &&
5007         !ArgumentPromotionPass::isDenselyPacked(PrivatizableType.getValue(),
5008                                                 A.getInfoCache().getDL())) {
5009       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
5010       return indicatePessimisticFixpoint();
5011     }
5012 
5013     // Verify callee and caller agree on how the promoted argument would be
5014     // passed.
5015     // TODO: The use of the ArgumentPromotion interface here is ugly, we need a
5016     // specialized form of TargetTransformInfo::areFunctionArgsABICompatible
5017     // which doesn't require the arguments ArgumentPromotion wanted to pass.
5018     Function &Fn = *getIRPosition().getAnchorScope();
5019     SmallPtrSet<Argument *, 1> ArgsToPromote, Dummy;
5020     ArgsToPromote.insert(getAssociatedArgument());
5021     const auto *TTI =
5022         A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
5023     if (!TTI ||
5024         !ArgumentPromotionPass::areFunctionArgsABICompatible(
5025             Fn, *TTI, ArgsToPromote, Dummy) ||
5026         ArgsToPromote.empty()) {
5027       LLVM_DEBUG(
5028           dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
5029                  << Fn.getName() << "\n");
5030       return indicatePessimisticFixpoint();
5031     }
5032 
5033     // Collect the types that will replace the privatizable type in the function
5034     // signature.
5035     SmallVector<Type *, 16> ReplacementTypes;
5036     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
5037 
5038     // Register a rewrite of the argument.
5039     Argument *Arg = getAssociatedArgument();
5040     if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
5041       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
5042       return indicatePessimisticFixpoint();
5043     }
5044 
5045     unsigned ArgNo = Arg->getArgNo();
5046 
5047     // Helper to check if for the given call site the associated argument is
5048     // passed to a callback where the privatization would be different.
5049     auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
5050       SmallVector<const Use *, 4> CallbackUses;
5051       AbstractCallSite::getCallbackUses(CB, CallbackUses);
5052       for (const Use *U : CallbackUses) {
5053         AbstractCallSite CBACS(U);
5054         assert(CBACS && CBACS.isCallbackCall());
5055         for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
5056           int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
5057 
5058           LLVM_DEBUG({
5059             dbgs()
5060                 << "[AAPrivatizablePtr] Argument " << *Arg
5061                 << "check if can be privatized in the context of its parent ("
5062                 << Arg->getParent()->getName()
5063                 << ")\n[AAPrivatizablePtr] because it is an argument in a "
5064                    "callback ("
5065                 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
5066                 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
5067                 << CBACS.getCallArgOperand(CBArg) << " vs "
5068                 << CB.getArgOperand(ArgNo) << "\n"
5069                 << "[AAPrivatizablePtr] " << CBArg << " : "
5070                 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
5071           });
5072 
5073           if (CBArgNo != int(ArgNo))
5074             continue;
5075           const auto &CBArgPrivAA =
5076               A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(CBArg));
5077           if (CBArgPrivAA.isValidState()) {
5078             auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
5079             if (!CBArgPrivTy.hasValue())
5080               continue;
5081             if (CBArgPrivTy.getValue() == PrivatizableType)
5082               continue;
5083           }
5084 
5085           LLVM_DEBUG({
5086             dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5087                    << " cannot be privatized in the context of its parent ("
5088                    << Arg->getParent()->getName()
5089                    << ")\n[AAPrivatizablePtr] because it is an argument in a "
5090                       "callback ("
5091                    << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
5092                    << ").\n[AAPrivatizablePtr] for which the argument "
5093                       "privatization is not compatible.\n";
5094           });
5095           return false;
5096         }
5097       }
5098       return true;
5099     };
5100 
5101     // Helper to check if for the given call site the associated argument is
5102     // passed to a direct call where the privatization would be different.
5103     auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
5104       CallBase *DC = cast<CallBase>(ACS.getInstruction());
5105       int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
5106       assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->getNumArgOperands() &&
5107              "Expected a direct call operand for callback call operand");
5108 
5109       LLVM_DEBUG({
5110         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5111                << " check if be privatized in the context of its parent ("
5112                << Arg->getParent()->getName()
5113                << ")\n[AAPrivatizablePtr] because it is an argument in a "
5114                   "direct call of ("
5115                << DCArgNo << "@" << DC->getCalledFunction()->getName()
5116                << ").\n";
5117       });
5118 
5119       Function *DCCallee = DC->getCalledFunction();
5120       if (unsigned(DCArgNo) < DCCallee->arg_size()) {
5121         const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
5122             *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)));
5123         if (DCArgPrivAA.isValidState()) {
5124           auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
5125           if (!DCArgPrivTy.hasValue())
5126             return true;
5127           if (DCArgPrivTy.getValue() == PrivatizableType)
5128             return true;
5129         }
5130       }
5131 
5132       LLVM_DEBUG({
5133         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
5134                << " cannot be privatized in the context of its parent ("
5135                << Arg->getParent()->getName()
5136                << ")\n[AAPrivatizablePtr] because it is an argument in a "
5137                   "direct call of ("
5138                << ACS.getInstruction()->getCalledFunction()->getName()
5139                << ").\n[AAPrivatizablePtr] for which the argument "
5140                   "privatization is not compatible.\n";
5141       });
5142       return false;
5143     };
5144 
5145     // Helper to check if the associated argument is used at the given abstract
5146     // call site in a way that is incompatible with the privatization assumed
5147     // here.
5148     auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
5149       if (ACS.isDirectCall())
5150         return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
5151       if (ACS.isCallbackCall())
5152         return IsCompatiblePrivArgOfDirectCS(ACS);
5153       return false;
5154     };
5155 
5156     bool AllCallSitesKnown;
5157     if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
5158                                 AllCallSitesKnown))
5159       return indicatePessimisticFixpoint();
5160 
5161     return ChangeStatus::UNCHANGED;
5162   }
5163 
5164   /// Given a type to private \p PrivType, collect the constituates (which are
5165   /// used) in \p ReplacementTypes.
5166   static void
5167   identifyReplacementTypes(Type *PrivType,
5168                            SmallVectorImpl<Type *> &ReplacementTypes) {
5169     // TODO: For now we expand the privatization type to the fullest which can
5170     //       lead to dead arguments that need to be removed later.
5171     assert(PrivType && "Expected privatizable type!");
5172 
5173     // Traverse the type, extract constituate types on the outermost level.
5174     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5175       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
5176         ReplacementTypes.push_back(PrivStructType->getElementType(u));
5177     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5178       ReplacementTypes.append(PrivArrayType->getNumElements(),
5179                               PrivArrayType->getElementType());
5180     } else {
5181       ReplacementTypes.push_back(PrivType);
5182     }
5183   }
5184 
5185   /// Initialize \p Base according to the type \p PrivType at position \p IP.
5186   /// The values needed are taken from the arguments of \p F starting at
5187   /// position \p ArgNo.
5188   static void createInitialization(Type *PrivType, Value &Base, Function &F,
5189                                    unsigned ArgNo, Instruction &IP) {
5190     assert(PrivType && "Expected privatizable type!");
5191 
5192     IRBuilder<NoFolder> IRB(&IP);
5193     const DataLayout &DL = F.getParent()->getDataLayout();
5194 
5195     // Traverse the type, build GEPs and stores.
5196     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5197       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
5198       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
5199         Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo();
5200         Value *Ptr = constructPointer(
5201             PointeeTy, &Base, PrivStructLayout->getElementOffset(u), IRB, DL);
5202         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
5203       }
5204     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5205       Type *PointeePtrTy = PrivArrayType->getElementType()->getPointerTo();
5206       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeePtrTy);
5207       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
5208         Value *Ptr =
5209             constructPointer(PointeePtrTy, &Base, u * PointeeTySize, IRB, DL);
5210         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
5211       }
5212     } else {
5213       new StoreInst(F.getArg(ArgNo), &Base, &IP);
5214     }
5215   }
5216 
5217   /// Extract values from \p Base according to the type \p PrivType at the
5218   /// call position \p ACS. The values are appended to \p ReplacementValues.
5219   void createReplacementValues(Type *PrivType, AbstractCallSite ACS,
5220                                Value *Base,
5221                                SmallVectorImpl<Value *> &ReplacementValues) {
5222     assert(Base && "Expected base value!");
5223     assert(PrivType && "Expected privatizable type!");
5224     Instruction *IP = ACS.getInstruction();
5225 
5226     IRBuilder<NoFolder> IRB(IP);
5227     const DataLayout &DL = IP->getModule()->getDataLayout();
5228 
5229     if (Base->getType()->getPointerElementType() != PrivType)
5230       Base = BitCastInst::CreateBitOrPointerCast(Base, PrivType->getPointerTo(),
5231                                                  "", ACS.getInstruction());
5232 
5233     // TODO: Improve the alignment of the loads.
5234     // Traverse the type, build GEPs and loads.
5235     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
5236       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
5237       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
5238         Type *PointeeTy = PrivStructType->getElementType(u);
5239         Value *Ptr =
5240             constructPointer(PointeeTy->getPointerTo(), Base,
5241                              PrivStructLayout->getElementOffset(u), IRB, DL);
5242         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
5243         L->setAlignment(Align(1));
5244         ReplacementValues.push_back(L);
5245       }
5246     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
5247       Type *PointeeTy = PrivArrayType->getElementType();
5248       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
5249       Type *PointeePtrTy = PointeeTy->getPointerTo();
5250       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
5251         Value *Ptr =
5252             constructPointer(PointeePtrTy, Base, u * PointeeTySize, IRB, DL);
5253         LoadInst *L = new LoadInst(PointeePtrTy, Ptr, "", IP);
5254         L->setAlignment(Align(1));
5255         ReplacementValues.push_back(L);
5256       }
5257     } else {
5258       LoadInst *L = new LoadInst(PrivType, Base, "", IP);
5259       L->setAlignment(Align(1));
5260       ReplacementValues.push_back(L);
5261     }
5262   }
5263 
5264   /// See AbstractAttribute::manifest(...)
5265   ChangeStatus manifest(Attributor &A) override {
5266     if (!PrivatizableType.hasValue())
5267       return ChangeStatus::UNCHANGED;
5268     assert(PrivatizableType.getValue() && "Expected privatizable type!");
5269 
5270     // Collect all tail calls in the function as we cannot allow new allocas to
5271     // escape into tail recursion.
5272     // TODO: Be smarter about new allocas escaping into tail calls.
5273     SmallVector<CallInst *, 16> TailCalls;
5274     if (!A.checkForAllInstructions(
5275             [&](Instruction &I) {
5276               CallInst &CI = cast<CallInst>(I);
5277               if (CI.isTailCall())
5278                 TailCalls.push_back(&CI);
5279               return true;
5280             },
5281             *this, {Instruction::Call}))
5282       return ChangeStatus::UNCHANGED;
5283 
5284     Argument *Arg = getAssociatedArgument();
5285 
5286     // Callback to repair the associated function. A new alloca is placed at the
5287     // beginning and initialized with the values passed through arguments. The
5288     // new alloca replaces the use of the old pointer argument.
5289     Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB =
5290         [=](const Attributor::ArgumentReplacementInfo &ARI,
5291             Function &ReplacementFn, Function::arg_iterator ArgIt) {
5292           BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
5293           Instruction *IP = &*EntryBB.getFirstInsertionPt();
5294           auto *AI = new AllocaInst(PrivatizableType.getValue(), 0,
5295                                     Arg->getName() + ".priv", IP);
5296           createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn,
5297                                ArgIt->getArgNo(), *IP);
5298           Arg->replaceAllUsesWith(AI);
5299 
5300           for (CallInst *CI : TailCalls)
5301             CI->setTailCall(false);
5302         };
5303 
5304     // Callback to repair a call site of the associated function. The elements
5305     // of the privatizable type are loaded prior to the call and passed to the
5306     // new function version.
5307     Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB =
5308         [=](const Attributor::ArgumentReplacementInfo &ARI,
5309             AbstractCallSite ACS, SmallVectorImpl<Value *> &NewArgOperands) {
5310           createReplacementValues(
5311               PrivatizableType.getValue(), ACS,
5312               ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
5313               NewArgOperands);
5314         };
5315 
5316     // Collect the types that will replace the privatizable type in the function
5317     // signature.
5318     SmallVector<Type *, 16> ReplacementTypes;
5319     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
5320 
5321     // Register a rewrite of the argument.
5322     if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
5323                                            std::move(FnRepairCB),
5324                                            std::move(ACSRepairCB)))
5325       return ChangeStatus::CHANGED;
5326     return ChangeStatus::UNCHANGED;
5327   }
5328 
5329   /// See AbstractAttribute::trackStatistics()
5330   void trackStatistics() const override {
5331     STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
5332   }
5333 };
5334 
5335 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
5336   AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
5337       : AAPrivatizablePtrImpl(IRP, A) {}
5338 
5339   /// See AbstractAttribute::initialize(...).
5340   virtual void initialize(Attributor &A) override {
5341     // TODO: We can privatize more than arguments.
5342     indicatePessimisticFixpoint();
5343   }
5344 
5345   ChangeStatus updateImpl(Attributor &A) override {
5346     llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
5347                      "updateImpl will not be called");
5348   }
5349 
5350   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
5351   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
5352     Value *Obj =
5353         GetUnderlyingObject(&getAssociatedValue(), A.getInfoCache().getDL());
5354     if (!Obj) {
5355       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
5356       return nullptr;
5357     }
5358 
5359     if (auto *AI = dyn_cast<AllocaInst>(Obj))
5360       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
5361         if (CI->isOne())
5362           return Obj->getType()->getPointerElementType();
5363     if (auto *Arg = dyn_cast<Argument>(Obj)) {
5364       auto &PrivArgAA =
5365           A.getAAFor<AAPrivatizablePtr>(*this, IRPosition::argument(*Arg));
5366       if (PrivArgAA.isAssumedPrivatizablePtr())
5367         return Obj->getType()->getPointerElementType();
5368     }
5369 
5370     LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
5371                          "alloca nor privatizable argument: "
5372                       << *Obj << "!\n");
5373     return nullptr;
5374   }
5375 
5376   /// See AbstractAttribute::trackStatistics()
5377   void trackStatistics() const override {
5378     STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
5379   }
5380 };
5381 
5382 struct AAPrivatizablePtrCallSiteArgument final
5383     : public AAPrivatizablePtrFloating {
5384   AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
5385       : AAPrivatizablePtrFloating(IRP, A) {}
5386 
5387   /// See AbstractAttribute::initialize(...).
5388   void initialize(Attributor &A) override {
5389     if (getIRPosition().hasAttr(Attribute::ByVal))
5390       indicateOptimisticFixpoint();
5391   }
5392 
5393   /// See AbstractAttribute::updateImpl(...).
5394   ChangeStatus updateImpl(Attributor &A) override {
5395     PrivatizableType = identifyPrivatizableType(A);
5396     if (!PrivatizableType.hasValue())
5397       return ChangeStatus::UNCHANGED;
5398     if (!PrivatizableType.getValue())
5399       return indicatePessimisticFixpoint();
5400 
5401     const IRPosition &IRP = getIRPosition();
5402     auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, IRP);
5403     if (!NoCaptureAA.isAssumedNoCapture()) {
5404       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
5405       return indicatePessimisticFixpoint();
5406     }
5407 
5408     auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP);
5409     if (!NoAliasAA.isAssumedNoAlias()) {
5410       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
5411       return indicatePessimisticFixpoint();
5412     }
5413 
5414     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(*this, IRP);
5415     if (!MemBehaviorAA.isAssumedReadOnly()) {
5416       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
5417       return indicatePessimisticFixpoint();
5418     }
5419 
5420     return ChangeStatus::UNCHANGED;
5421   }
5422 
5423   /// See AbstractAttribute::trackStatistics()
5424   void trackStatistics() const override {
5425     STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
5426   }
5427 };
5428 
5429 struct AAPrivatizablePtrCallSiteReturned final
5430     : public AAPrivatizablePtrFloating {
5431   AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
5432       : AAPrivatizablePtrFloating(IRP, A) {}
5433 
5434   /// See AbstractAttribute::initialize(...).
5435   void initialize(Attributor &A) override {
5436     // TODO: We can privatize more than arguments.
5437     indicatePessimisticFixpoint();
5438   }
5439 
5440   /// See AbstractAttribute::trackStatistics()
5441   void trackStatistics() const override {
5442     STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
5443   }
5444 };
5445 
5446 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
5447   AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
5448       : AAPrivatizablePtrFloating(IRP, A) {}
5449 
5450   /// See AbstractAttribute::initialize(...).
5451   void initialize(Attributor &A) override {
5452     // TODO: We can privatize more than arguments.
5453     indicatePessimisticFixpoint();
5454   }
5455 
5456   /// See AbstractAttribute::trackStatistics()
5457   void trackStatistics() const override {
5458     STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
5459   }
5460 };
5461 
5462 /// -------------------- Memory Behavior Attributes ----------------------------
5463 /// Includes read-none, read-only, and write-only.
5464 /// ----------------------------------------------------------------------------
5465 struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
5466   AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
5467       : AAMemoryBehavior(IRP, A) {}
5468 
5469   /// See AbstractAttribute::initialize(...).
5470   void initialize(Attributor &A) override {
5471     intersectAssumedBits(BEST_STATE);
5472     getKnownStateFromValue(getIRPosition(), getState());
5473     IRAttribute::initialize(A);
5474   }
5475 
5476   /// Return the memory behavior information encoded in the IR for \p IRP.
5477   static void getKnownStateFromValue(const IRPosition &IRP,
5478                                      BitIntegerState &State,
5479                                      bool IgnoreSubsumingPositions = false) {
5480     SmallVector<Attribute, 2> Attrs;
5481     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
5482     for (const Attribute &Attr : Attrs) {
5483       switch (Attr.getKindAsEnum()) {
5484       case Attribute::ReadNone:
5485         State.addKnownBits(NO_ACCESSES);
5486         break;
5487       case Attribute::ReadOnly:
5488         State.addKnownBits(NO_WRITES);
5489         break;
5490       case Attribute::WriteOnly:
5491         State.addKnownBits(NO_READS);
5492         break;
5493       default:
5494         llvm_unreachable("Unexpected attribute!");
5495       }
5496     }
5497 
5498     if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) {
5499       if (!I->mayReadFromMemory())
5500         State.addKnownBits(NO_READS);
5501       if (!I->mayWriteToMemory())
5502         State.addKnownBits(NO_WRITES);
5503     }
5504   }
5505 
5506   /// See AbstractAttribute::getDeducedAttributes(...).
5507   void getDeducedAttributes(LLVMContext &Ctx,
5508                             SmallVectorImpl<Attribute> &Attrs) const override {
5509     assert(Attrs.size() == 0);
5510     if (isAssumedReadNone())
5511       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
5512     else if (isAssumedReadOnly())
5513       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
5514     else if (isAssumedWriteOnly())
5515       Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
5516     assert(Attrs.size() <= 1);
5517   }
5518 
5519   /// See AbstractAttribute::manifest(...).
5520   ChangeStatus manifest(Attributor &A) override {
5521     if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true))
5522       return ChangeStatus::UNCHANGED;
5523 
5524     const IRPosition &IRP = getIRPosition();
5525 
5526     // Check if we would improve the existing attributes first.
5527     SmallVector<Attribute, 4> DeducedAttrs;
5528     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
5529     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
5530           return IRP.hasAttr(Attr.getKindAsEnum(),
5531                              /* IgnoreSubsumingPositions */ true);
5532         }))
5533       return ChangeStatus::UNCHANGED;
5534 
5535     // Clear existing attributes.
5536     IRP.removeAttrs(AttrKinds);
5537 
5538     // Use the generic manifest method.
5539     return IRAttribute::manifest(A);
5540   }
5541 
5542   /// See AbstractState::getAsStr().
5543   const std::string getAsStr() const override {
5544     if (isAssumedReadNone())
5545       return "readnone";
5546     if (isAssumedReadOnly())
5547       return "readonly";
5548     if (isAssumedWriteOnly())
5549       return "writeonly";
5550     return "may-read/write";
5551   }
5552 
5553   /// The set of IR attributes AAMemoryBehavior deals with.
5554   static const Attribute::AttrKind AttrKinds[3];
5555 };
5556 
5557 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
5558     Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
5559 
5560 /// Memory behavior attribute for a floating value.
5561 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
5562   AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
5563       : AAMemoryBehaviorImpl(IRP, A) {}
5564 
5565   /// See AbstractAttribute::initialize(...).
5566   void initialize(Attributor &A) override {
5567     AAMemoryBehaviorImpl::initialize(A);
5568     // Initialize the use vector with all direct uses of the associated value.
5569     for (const Use &U : getAssociatedValue().uses())
5570       Uses.insert(&U);
5571   }
5572 
5573   /// See AbstractAttribute::updateImpl(...).
5574   ChangeStatus updateImpl(Attributor &A) override;
5575 
5576   /// See AbstractAttribute::trackStatistics()
5577   void trackStatistics() const override {
5578     if (isAssumedReadNone())
5579       STATS_DECLTRACK_FLOATING_ATTR(readnone)
5580     else if (isAssumedReadOnly())
5581       STATS_DECLTRACK_FLOATING_ATTR(readonly)
5582     else if (isAssumedWriteOnly())
5583       STATS_DECLTRACK_FLOATING_ATTR(writeonly)
5584   }
5585 
5586 private:
5587   /// Return true if users of \p UserI might access the underlying
5588   /// variable/location described by \p U and should therefore be analyzed.
5589   bool followUsersOfUseIn(Attributor &A, const Use *U,
5590                           const Instruction *UserI);
5591 
5592   /// Update the state according to the effect of use \p U in \p UserI.
5593   void analyzeUseIn(Attributor &A, const Use *U, const Instruction *UserI);
5594 
5595 protected:
5596   /// Container for (transitive) uses of the associated argument.
5597   SetVector<const Use *> Uses;
5598 };
5599 
5600 /// Memory behavior attribute for function argument.
5601 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
5602   AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
5603       : AAMemoryBehaviorFloating(IRP, A) {}
5604 
5605   /// See AbstractAttribute::initialize(...).
5606   void initialize(Attributor &A) override {
5607     intersectAssumedBits(BEST_STATE);
5608     const IRPosition &IRP = getIRPosition();
5609     // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
5610     // can query it when we use has/getAttr. That would allow us to reuse the
5611     // initialize of the base class here.
5612     bool HasByVal =
5613         IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true);
5614     getKnownStateFromValue(IRP, getState(),
5615                            /* IgnoreSubsumingPositions */ HasByVal);
5616 
5617     // Initialize the use vector with all direct uses of the associated value.
5618     Argument *Arg = getAssociatedArgument();
5619     if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent()))) {
5620       indicatePessimisticFixpoint();
5621     } else {
5622       // Initialize the use vector with all direct uses of the associated value.
5623       for (const Use &U : Arg->uses())
5624         Uses.insert(&U);
5625     }
5626   }
5627 
5628   ChangeStatus manifest(Attributor &A) override {
5629     // TODO: Pointer arguments are not supported on vectors of pointers yet.
5630     if (!getAssociatedValue().getType()->isPointerTy())
5631       return ChangeStatus::UNCHANGED;
5632 
5633     // TODO: From readattrs.ll: "inalloca parameters are always
5634     //                           considered written"
5635     if (hasAttr({Attribute::InAlloca})) {
5636       removeKnownBits(NO_WRITES);
5637       removeAssumedBits(NO_WRITES);
5638     }
5639     return AAMemoryBehaviorFloating::manifest(A);
5640   }
5641 
5642   /// See AbstractAttribute::trackStatistics()
5643   void trackStatistics() const override {
5644     if (isAssumedReadNone())
5645       STATS_DECLTRACK_ARG_ATTR(readnone)
5646     else if (isAssumedReadOnly())
5647       STATS_DECLTRACK_ARG_ATTR(readonly)
5648     else if (isAssumedWriteOnly())
5649       STATS_DECLTRACK_ARG_ATTR(writeonly)
5650   }
5651 };
5652 
5653 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
5654   AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
5655       : AAMemoryBehaviorArgument(IRP, A) {}
5656 
5657   /// See AbstractAttribute::initialize(...).
5658   void initialize(Attributor &A) override {
5659     if (Argument *Arg = getAssociatedArgument()) {
5660       if (Arg->hasByValAttr()) {
5661         addKnownBits(NO_WRITES);
5662         removeKnownBits(NO_READS);
5663         removeAssumedBits(NO_READS);
5664       }
5665     } else {
5666     }
5667     AAMemoryBehaviorArgument::initialize(A);
5668   }
5669 
5670   /// See AbstractAttribute::updateImpl(...).
5671   ChangeStatus updateImpl(Attributor &A) override {
5672     // TODO: Once we have call site specific value information we can provide
5673     //       call site specific liveness liveness information and then it makes
5674     //       sense to specialize attributes for call sites arguments instead of
5675     //       redirecting requests to the callee argument.
5676     Argument *Arg = getAssociatedArgument();
5677     const IRPosition &ArgPos = IRPosition::argument(*Arg);
5678     auto &ArgAA = A.getAAFor<AAMemoryBehavior>(*this, ArgPos);
5679     return clampStateAndIndicateChange(
5680         getState(),
5681         static_cast<const AAMemoryBehavior::StateType &>(ArgAA.getState()));
5682   }
5683 
5684   /// See AbstractAttribute::trackStatistics()
5685   void trackStatistics() const override {
5686     if (isAssumedReadNone())
5687       STATS_DECLTRACK_CSARG_ATTR(readnone)
5688     else if (isAssumedReadOnly())
5689       STATS_DECLTRACK_CSARG_ATTR(readonly)
5690     else if (isAssumedWriteOnly())
5691       STATS_DECLTRACK_CSARG_ATTR(writeonly)
5692   }
5693 };
5694 
5695 /// Memory behavior attribute for a call site return position.
5696 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
5697   AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
5698       : AAMemoryBehaviorFloating(IRP, A) {}
5699 
5700   /// See AbstractAttribute::manifest(...).
5701   ChangeStatus manifest(Attributor &A) override {
5702     // We do not annotate returned values.
5703     return ChangeStatus::UNCHANGED;
5704   }
5705 
5706   /// See AbstractAttribute::trackStatistics()
5707   void trackStatistics() const override {}
5708 };
5709 
5710 /// An AA to represent the memory behavior function attributes.
5711 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
5712   AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
5713       : AAMemoryBehaviorImpl(IRP, A) {}
5714 
5715   /// See AbstractAttribute::updateImpl(Attributor &A).
5716   virtual ChangeStatus updateImpl(Attributor &A) override;
5717 
5718   /// See AbstractAttribute::manifest(...).
5719   ChangeStatus manifest(Attributor &A) override {
5720     Function &F = cast<Function>(getAnchorValue());
5721     if (isAssumedReadNone()) {
5722       F.removeFnAttr(Attribute::ArgMemOnly);
5723       F.removeFnAttr(Attribute::InaccessibleMemOnly);
5724       F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
5725     }
5726     return AAMemoryBehaviorImpl::manifest(A);
5727   }
5728 
5729   /// See AbstractAttribute::trackStatistics()
5730   void trackStatistics() const override {
5731     if (isAssumedReadNone())
5732       STATS_DECLTRACK_FN_ATTR(readnone)
5733     else if (isAssumedReadOnly())
5734       STATS_DECLTRACK_FN_ATTR(readonly)
5735     else if (isAssumedWriteOnly())
5736       STATS_DECLTRACK_FN_ATTR(writeonly)
5737   }
5738 };
5739 
5740 /// AAMemoryBehavior attribute for call sites.
5741 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
5742   AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
5743       : AAMemoryBehaviorImpl(IRP, A) {}
5744 
5745   /// See AbstractAttribute::initialize(...).
5746   void initialize(Attributor &A) override {
5747     AAMemoryBehaviorImpl::initialize(A);
5748     Function *F = getAssociatedFunction();
5749     if (!F || !A.isFunctionIPOAmendable(*F))
5750       indicatePessimisticFixpoint();
5751   }
5752 
5753   /// See AbstractAttribute::updateImpl(...).
5754   ChangeStatus updateImpl(Attributor &A) override {
5755     // TODO: Once we have call site specific value information we can provide
5756     //       call site specific liveness liveness information and then it makes
5757     //       sense to specialize attributes for call sites arguments instead of
5758     //       redirecting requests to the callee argument.
5759     Function *F = getAssociatedFunction();
5760     const IRPosition &FnPos = IRPosition::function(*F);
5761     auto &FnAA = A.getAAFor<AAMemoryBehavior>(*this, FnPos);
5762     return clampStateAndIndicateChange(
5763         getState(),
5764         static_cast<const AAMemoryBehavior::StateType &>(FnAA.getState()));
5765   }
5766 
5767   /// See AbstractAttribute::trackStatistics()
5768   void trackStatistics() const override {
5769     if (isAssumedReadNone())
5770       STATS_DECLTRACK_CS_ATTR(readnone)
5771     else if (isAssumedReadOnly())
5772       STATS_DECLTRACK_CS_ATTR(readonly)
5773     else if (isAssumedWriteOnly())
5774       STATS_DECLTRACK_CS_ATTR(writeonly)
5775   }
5776 };
5777 
5778 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
5779 
5780   // The current assumed state used to determine a change.
5781   auto AssumedState = getAssumed();
5782 
5783   auto CheckRWInst = [&](Instruction &I) {
5784     // If the instruction has an own memory behavior state, use it to restrict
5785     // the local state. No further analysis is required as the other memory
5786     // state is as optimistic as it gets.
5787     if (const auto *CB = dyn_cast<CallBase>(&I)) {
5788       const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
5789           *this, IRPosition::callsite_function(*CB));
5790       intersectAssumedBits(MemBehaviorAA.getAssumed());
5791       return !isAtFixpoint();
5792     }
5793 
5794     // Remove access kind modifiers if necessary.
5795     if (I.mayReadFromMemory())
5796       removeAssumedBits(NO_READS);
5797     if (I.mayWriteToMemory())
5798       removeAssumedBits(NO_WRITES);
5799     return !isAtFixpoint();
5800   };
5801 
5802   if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
5803     return indicatePessimisticFixpoint();
5804 
5805   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
5806                                         : ChangeStatus::UNCHANGED;
5807 }
5808 
5809 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
5810 
5811   const IRPosition &IRP = getIRPosition();
5812   const IRPosition &FnPos = IRPosition::function_scope(IRP);
5813   AAMemoryBehavior::StateType &S = getState();
5814 
5815   // First, check the function scope. We take the known information and we avoid
5816   // work if the assumed information implies the current assumed information for
5817   // this attribute. This is a valid for all but byval arguments.
5818   Argument *Arg = IRP.getAssociatedArgument();
5819   AAMemoryBehavior::base_t FnMemAssumedState =
5820       AAMemoryBehavior::StateType::getWorstState();
5821   if (!Arg || !Arg->hasByValAttr()) {
5822     const auto &FnMemAA = A.getAAFor<AAMemoryBehavior>(
5823         *this, FnPos, /* TrackDependence */ true, DepClassTy::OPTIONAL);
5824     FnMemAssumedState = FnMemAA.getAssumed();
5825     S.addKnownBits(FnMemAA.getKnown());
5826     if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
5827       return ChangeStatus::UNCHANGED;
5828   }
5829 
5830   // Make sure the value is not captured (except through "return"), if
5831   // it is, any information derived would be irrelevant anyway as we cannot
5832   // check the potential aliases introduced by the capture. However, no need
5833   // to fall back to anythign less optimistic than the function state.
5834   const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
5835       *this, IRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
5836   if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
5837     S.intersectAssumedBits(FnMemAssumedState);
5838     return ChangeStatus::CHANGED;
5839   }
5840 
5841   // The current assumed state used to determine a change.
5842   auto AssumedState = S.getAssumed();
5843 
5844   // Liveness information to exclude dead users.
5845   // TODO: Take the FnPos once we have call site specific liveness information.
5846   const auto &LivenessAA = A.getAAFor<AAIsDead>(
5847       *this, IRPosition::function(*IRP.getAssociatedFunction()),
5848       /* TrackDependence */ false);
5849 
5850   // Visit and expand uses until all are analyzed or a fixpoint is reached.
5851   for (unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) {
5852     const Use *U = Uses[i];
5853     Instruction *UserI = cast<Instruction>(U->getUser());
5854     LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << **U << " in " << *UserI
5855                       << " [Dead: " << (A.isAssumedDead(*U, this, &LivenessAA))
5856                       << "]\n");
5857     if (A.isAssumedDead(*U, this, &LivenessAA))
5858       continue;
5859 
5860     // Droppable users, e.g., llvm::assume does not actually perform any action.
5861     if (UserI->isDroppable())
5862       continue;
5863 
5864     // Check if the users of UserI should also be visited.
5865     if (followUsersOfUseIn(A, U, UserI))
5866       for (const Use &UserIUse : UserI->uses())
5867         Uses.insert(&UserIUse);
5868 
5869     // If UserI might touch memory we analyze the use in detail.
5870     if (UserI->mayReadOrWriteMemory())
5871       analyzeUseIn(A, U, UserI);
5872   }
5873 
5874   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
5875                                         : ChangeStatus::UNCHANGED;
5876 }
5877 
5878 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use *U,
5879                                                   const Instruction *UserI) {
5880   // The loaded value is unrelated to the pointer argument, no need to
5881   // follow the users of the load.
5882   if (isa<LoadInst>(UserI))
5883     return false;
5884 
5885   // By default we follow all uses assuming UserI might leak information on U,
5886   // we have special handling for call sites operands though.
5887   const auto *CB = dyn_cast<CallBase>(UserI);
5888   if (!CB || !CB->isArgOperand(U))
5889     return true;
5890 
5891   // If the use is a call argument known not to be captured, the users of
5892   // the call do not need to be visited because they have to be unrelated to
5893   // the input. Note that this check is not trivial even though we disallow
5894   // general capturing of the underlying argument. The reason is that the
5895   // call might the argument "through return", which we allow and for which we
5896   // need to check call users.
5897   if (U->get()->getType()->isPointerTy()) {
5898     unsigned ArgNo = CB->getArgOperandNo(U);
5899     const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
5900         *this, IRPosition::callsite_argument(*CB, ArgNo),
5901         /* TrackDependence */ true, DepClassTy::OPTIONAL);
5902     return !ArgNoCaptureAA.isAssumedNoCapture();
5903   }
5904 
5905   return true;
5906 }
5907 
5908 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use *U,
5909                                             const Instruction *UserI) {
5910   assert(UserI->mayReadOrWriteMemory());
5911 
5912   switch (UserI->getOpcode()) {
5913   default:
5914     // TODO: Handle all atomics and other side-effect operations we know of.
5915     break;
5916   case Instruction::Load:
5917     // Loads cause the NO_READS property to disappear.
5918     removeAssumedBits(NO_READS);
5919     return;
5920 
5921   case Instruction::Store:
5922     // Stores cause the NO_WRITES property to disappear if the use is the
5923     // pointer operand. Note that we do assume that capturing was taken care of
5924     // somewhere else.
5925     if (cast<StoreInst>(UserI)->getPointerOperand() == U->get())
5926       removeAssumedBits(NO_WRITES);
5927     return;
5928 
5929   case Instruction::Call:
5930   case Instruction::CallBr:
5931   case Instruction::Invoke: {
5932     // For call sites we look at the argument memory behavior attribute (this
5933     // could be recursive!) in order to restrict our own state.
5934     const auto *CB = cast<CallBase>(UserI);
5935 
5936     // Give up on operand bundles.
5937     if (CB->isBundleOperand(U)) {
5938       indicatePessimisticFixpoint();
5939       return;
5940     }
5941 
5942     // Calling a function does read the function pointer, maybe write it if the
5943     // function is self-modifying.
5944     if (CB->isCallee(U)) {
5945       removeAssumedBits(NO_READS);
5946       break;
5947     }
5948 
5949     // Adjust the possible access behavior based on the information on the
5950     // argument.
5951     IRPosition Pos;
5952     if (U->get()->getType()->isPointerTy())
5953       Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(U));
5954     else
5955       Pos = IRPosition::callsite_function(*CB);
5956     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
5957         *this, Pos,
5958         /* TrackDependence */ true, DepClassTy::OPTIONAL);
5959     // "assumed" has at most the same bits as the MemBehaviorAA assumed
5960     // and at least "known".
5961     intersectAssumedBits(MemBehaviorAA.getAssumed());
5962     return;
5963   }
5964   };
5965 
5966   // Generally, look at the "may-properties" and adjust the assumed state if we
5967   // did not trigger special handling before.
5968   if (UserI->mayReadFromMemory())
5969     removeAssumedBits(NO_READS);
5970   if (UserI->mayWriteToMemory())
5971     removeAssumedBits(NO_WRITES);
5972 }
5973 
5974 } // namespace
5975 
5976 /// -------------------- Memory Locations Attributes ---------------------------
5977 /// Includes read-none, argmemonly, inaccessiblememonly,
5978 /// inaccessiblememorargmemonly
5979 /// ----------------------------------------------------------------------------
5980 
5981 std::string AAMemoryLocation::getMemoryLocationsAsStr(
5982     AAMemoryLocation::MemoryLocationsKind MLK) {
5983   if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
5984     return "all memory";
5985   if (MLK == AAMemoryLocation::NO_LOCATIONS)
5986     return "no memory";
5987   std::string S = "memory:";
5988   if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
5989     S += "stack,";
5990   if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
5991     S += "constant,";
5992   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM))
5993     S += "internal global,";
5994   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM))
5995     S += "external global,";
5996   if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
5997     S += "argument,";
5998   if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM))
5999     S += "inaccessible,";
6000   if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
6001     S += "malloced,";
6002   if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
6003     S += "unknown,";
6004   S.pop_back();
6005   return S;
6006 }
6007 
6008 struct AAMemoryLocationImpl : public AAMemoryLocation {
6009 
6010   AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
6011       : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {}
6012 
6013   ~AAMemoryLocationImpl() {
6014     // The AccessSets are allocated via a BumpPtrAllocator, we call
6015     // the destructor manually.
6016     for (auto &It : AccessKind2Accesses)
6017       It.getSecond()->~AccessSet();
6018   }
6019 
6020   /// See AbstractAttribute::initialize(...).
6021   void initialize(Attributor &A) override {
6022     intersectAssumedBits(BEST_STATE);
6023     getKnownStateFromValue(getIRPosition(), getState());
6024     IRAttribute::initialize(A);
6025   }
6026 
6027   /// Return the memory behavior information encoded in the IR for \p IRP.
6028   static void getKnownStateFromValue(const IRPosition &IRP,
6029                                      BitIntegerState &State,
6030                                      bool IgnoreSubsumingPositions = false) {
6031     SmallVector<Attribute, 2> Attrs;
6032     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
6033     for (const Attribute &Attr : Attrs) {
6034       switch (Attr.getKindAsEnum()) {
6035       case Attribute::ReadNone:
6036         State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
6037         break;
6038       case Attribute::InaccessibleMemOnly:
6039         State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
6040         break;
6041       case Attribute::ArgMemOnly:
6042         State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
6043         break;
6044       case Attribute::InaccessibleMemOrArgMemOnly:
6045         State.addKnownBits(
6046             inverseLocation(NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
6047         break;
6048       default:
6049         llvm_unreachable("Unexpected attribute!");
6050       }
6051     }
6052   }
6053 
6054   /// See AbstractAttribute::getDeducedAttributes(...).
6055   void getDeducedAttributes(LLVMContext &Ctx,
6056                             SmallVectorImpl<Attribute> &Attrs) const override {
6057     assert(Attrs.size() == 0);
6058     if (isAssumedReadNone()) {
6059       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
6060     } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
6061       if (isAssumedInaccessibleMemOnly())
6062         Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly));
6063       else if (isAssumedArgMemOnly())
6064         Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly));
6065       else if (isAssumedInaccessibleOrArgMemOnly())
6066         Attrs.push_back(
6067             Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly));
6068     }
6069     assert(Attrs.size() <= 1);
6070   }
6071 
6072   /// See AbstractAttribute::manifest(...).
6073   ChangeStatus manifest(Attributor &A) override {
6074     const IRPosition &IRP = getIRPosition();
6075 
6076     // Check if we would improve the existing attributes first.
6077     SmallVector<Attribute, 4> DeducedAttrs;
6078     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
6079     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
6080           return IRP.hasAttr(Attr.getKindAsEnum(),
6081                              /* IgnoreSubsumingPositions */ true);
6082         }))
6083       return ChangeStatus::UNCHANGED;
6084 
6085     // Clear existing attributes.
6086     IRP.removeAttrs(AttrKinds);
6087     if (isAssumedReadNone())
6088       IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds);
6089 
6090     // Use the generic manifest method.
6091     return IRAttribute::manifest(A);
6092   }
6093 
6094   /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...).
6095   bool checkForAllAccessesToMemoryKind(
6096       function_ref<bool(const Instruction *, const Value *, AccessKind,
6097                         MemoryLocationsKind)>
6098           Pred,
6099       MemoryLocationsKind RequestedMLK) const override {
6100     if (!isValidState())
6101       return false;
6102 
6103     MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
6104     if (AssumedMLK == NO_LOCATIONS)
6105       return true;
6106 
6107     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
6108       if (CurMLK & RequestedMLK)
6109         continue;
6110 
6111       if (const AccessSet *Accesses = AccessKind2Accesses.lookup(CurMLK))
6112         for (const AccessInfo &AI : *Accesses)
6113           if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
6114             return false;
6115     }
6116 
6117     return true;
6118   }
6119 
6120   ChangeStatus indicatePessimisticFixpoint() override {
6121     // If we give up and indicate a pessimistic fixpoint this instruction will
6122     // become an access for all potential access kinds:
6123     // TODO: Add pointers for argmemonly and globals to improve the results of
6124     //       checkForAllAccessesToMemoryKind.
6125     bool Changed = false;
6126     MemoryLocationsKind KnownMLK = getKnown();
6127     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
6128     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
6129       if (!(CurMLK & KnownMLK))
6130         updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed);
6131     return AAMemoryLocation::indicatePessimisticFixpoint();
6132   }
6133 
6134 protected:
6135   /// Helper struct to tie together an instruction that has a read or write
6136   /// effect with the pointer it accesses (if any).
6137   struct AccessInfo {
6138 
6139     /// The instruction that caused the access.
6140     const Instruction *I;
6141 
6142     /// The base pointer that is accessed, or null if unknown.
6143     const Value *Ptr;
6144 
6145     /// The kind of access (read/write/read+write).
6146     AccessKind Kind;
6147 
6148     bool operator==(const AccessInfo &RHS) const {
6149       return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
6150     }
6151     bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
6152       if (LHS.I != RHS.I)
6153         return LHS.I < RHS.I;
6154       if (LHS.Ptr != RHS.Ptr)
6155         return LHS.Ptr < RHS.Ptr;
6156       if (LHS.Kind != RHS.Kind)
6157         return LHS.Kind < RHS.Kind;
6158       return false;
6159     }
6160   };
6161 
6162   /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
6163   /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
6164   using AccessSet = SmallSet<AccessInfo, 8, AccessInfo>;
6165   using AccessKind2AccessSetTy = DenseMap<unsigned, AccessSet *>;
6166   AccessKind2AccessSetTy AccessKind2Accesses;
6167 
6168   /// Return the kind(s) of location that may be accessed by \p V.
6169   AAMemoryLocation::MemoryLocationsKind
6170   categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
6171 
6172   /// Update the state \p State and the AccessKind2Accesses given that \p I is
6173   /// an access to a \p MLK memory location with the access pointer \p Ptr.
6174   void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
6175                                  MemoryLocationsKind MLK, const Instruction *I,
6176                                  const Value *Ptr, bool &Changed) {
6177     // TODO: The kind should be determined at the call sites based on the
6178     // information we have there.
6179     AccessKind Kind = READ_WRITE;
6180     if (I) {
6181       Kind = I->mayReadFromMemory() ? READ : NONE;
6182       Kind = AccessKind(Kind | (I->mayWriteToMemory() ? WRITE : NONE));
6183     }
6184 
6185     assert(isPowerOf2_32(MLK) && "Expected a single location set!");
6186     auto *&Accesses = AccessKind2Accesses[MLK];
6187     if (!Accesses)
6188       Accesses = new (Allocator) AccessSet();
6189     Changed |= Accesses->insert(AccessInfo{I, Ptr, Kind}).second;
6190     State.removeAssumedBits(MLK);
6191   }
6192 
6193   /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
6194   /// arguments, and update the state and access map accordingly.
6195   void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
6196                           AAMemoryLocation::StateType &State, bool &Changed);
6197 
6198   /// Used to allocate access sets.
6199   BumpPtrAllocator &Allocator;
6200 
6201   /// The set of IR attributes AAMemoryLocation deals with.
6202   static const Attribute::AttrKind AttrKinds[4];
6203 };
6204 
6205 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = {
6206     Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly,
6207     Attribute::InaccessibleMemOrArgMemOnly};
6208 
6209 void AAMemoryLocationImpl::categorizePtrValue(
6210     Attributor &A, const Instruction &I, const Value &Ptr,
6211     AAMemoryLocation::StateType &State, bool &Changed) {
6212   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
6213                     << Ptr << " ["
6214                     << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
6215 
6216   auto StripGEPCB = [](Value *V) -> Value * {
6217     auto *GEP = dyn_cast<GEPOperator>(V);
6218     while (GEP) {
6219       V = GEP->getPointerOperand();
6220       GEP = dyn_cast<GEPOperator>(V);
6221     }
6222     return V;
6223   };
6224 
6225   auto VisitValueCB = [&](Value &V, const Instruction *,
6226                           AAMemoryLocation::StateType &T,
6227                           bool Stripped) -> bool {
6228     assert(!isa<GEPOperator>(V) && "GEPs should have been stripped.");
6229     if (isa<UndefValue>(V))
6230       return true;
6231     if (auto *Arg = dyn_cast<Argument>(&V)) {
6232       if (Arg->hasByValAttr())
6233         updateStateAndAccessesMap(T, NO_LOCAL_MEM, &I, &V, Changed);
6234       else
6235         updateStateAndAccessesMap(T, NO_ARGUMENT_MEM, &I, &V, Changed);
6236       return true;
6237     }
6238     if (auto *GV = dyn_cast<GlobalValue>(&V)) {
6239       if (GV->hasLocalLinkage())
6240         updateStateAndAccessesMap(T, NO_GLOBAL_INTERNAL_MEM, &I, &V, Changed);
6241       else
6242         updateStateAndAccessesMap(T, NO_GLOBAL_EXTERNAL_MEM, &I, &V, Changed);
6243       return true;
6244     }
6245     if (isa<AllocaInst>(V)) {
6246       updateStateAndAccessesMap(T, NO_LOCAL_MEM, &I, &V, Changed);
6247       return true;
6248     }
6249     if (const auto *CB = dyn_cast<CallBase>(&V)) {
6250       const auto &NoAliasAA =
6251           A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(*CB));
6252       if (NoAliasAA.isAssumedNoAlias()) {
6253         updateStateAndAccessesMap(T, NO_MALLOCED_MEM, &I, &V, Changed);
6254         return true;
6255       }
6256     }
6257 
6258     updateStateAndAccessesMap(T, NO_UNKOWN_MEM, &I, &V, Changed);
6259     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value cannot be categorized: "
6260                       << V << " -> " << getMemoryLocationsAsStr(T.getAssumed())
6261                       << "\n");
6262     return true;
6263   };
6264 
6265   if (!genericValueTraversal<AAMemoryLocation, AAMemoryLocation::StateType>(
6266           A, IRPosition::value(Ptr), *this, State, VisitValueCB, getCtxI(),
6267           /* MaxValues */ 32, StripGEPCB)) {
6268     LLVM_DEBUG(
6269         dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
6270     updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed);
6271   } else {
6272     LLVM_DEBUG(
6273         dbgs()
6274         << "[AAMemoryLocation] Accessed locations with pointer locations: "
6275         << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
6276   }
6277 }
6278 
6279 AAMemoryLocation::MemoryLocationsKind
6280 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
6281                                                   bool &Changed) {
6282   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
6283                     << I << "\n");
6284 
6285   AAMemoryLocation::StateType AccessedLocs;
6286   AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
6287 
6288   if (auto *CB = dyn_cast<CallBase>(&I)) {
6289 
6290     // First check if we assume any memory is access is visible.
6291     const auto &CBMemLocationAA =
6292         A.getAAFor<AAMemoryLocation>(*this, IRPosition::callsite_function(*CB));
6293     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
6294                       << " [" << CBMemLocationAA << "]\n");
6295 
6296     if (CBMemLocationAA.isAssumedReadNone())
6297       return NO_LOCATIONS;
6298 
6299     if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) {
6300       updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
6301                                 Changed);
6302       return AccessedLocs.getAssumed();
6303     }
6304 
6305     uint32_t CBAssumedNotAccessedLocs =
6306         CBMemLocationAA.getAssumedNotAccessedLocation();
6307 
6308     // Set the argmemonly and global bit as we handle them separately below.
6309     uint32_t CBAssumedNotAccessedLocsNoArgMem =
6310         CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
6311 
6312     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
6313       if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
6314         continue;
6315       updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed);
6316     }
6317 
6318     // Now handle global memory if it might be accessed. This is slightly tricky
6319     // as NO_GLOBAL_MEM has multiple bits set.
6320     bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
6321     if (HasGlobalAccesses) {
6322       auto AccessPred = [&](const Instruction *, const Value *Ptr,
6323                             AccessKind Kind, MemoryLocationsKind MLK) {
6324         updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed);
6325         return true;
6326       };
6327       if (!CBMemLocationAA.checkForAllAccessesToMemoryKind(
6328               AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
6329         return AccessedLocs.getWorstState();
6330     }
6331 
6332     LLVM_DEBUG(
6333         dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
6334                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
6335 
6336     // Now handle argument memory if it might be accessed.
6337     bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
6338     if (HasArgAccesses) {
6339       for (unsigned ArgNo = 0, E = CB->getNumArgOperands(); ArgNo < E;
6340            ++ArgNo) {
6341 
6342         // Skip non-pointer arguments.
6343         const Value *ArgOp = CB->getArgOperand(ArgNo);
6344         if (!ArgOp->getType()->isPtrOrPtrVectorTy())
6345           continue;
6346 
6347         // Skip readnone arguments.
6348         const IRPosition &ArgOpIRP = IRPosition::callsite_argument(*CB, ArgNo);
6349         const auto &ArgOpMemLocationAA = A.getAAFor<AAMemoryBehavior>(
6350             *this, ArgOpIRP, /* TrackDependence */ true, DepClassTy::OPTIONAL);
6351 
6352         if (ArgOpMemLocationAA.isAssumedReadNone())
6353           continue;
6354 
6355         // Categorize potentially accessed pointer arguments as if there was an
6356         // access instruction with them as pointer.
6357         categorizePtrValue(A, I, *ArgOp, AccessedLocs, Changed);
6358       }
6359     }
6360 
6361     LLVM_DEBUG(
6362         dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
6363                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
6364 
6365     return AccessedLocs.getAssumed();
6366   }
6367 
6368   if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
6369     LLVM_DEBUG(
6370         dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
6371                << I << " [" << *Ptr << "]\n");
6372     categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed);
6373     return AccessedLocs.getAssumed();
6374   }
6375 
6376   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
6377                     << I << "\n");
6378   updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed);
6379   return AccessedLocs.getAssumed();
6380 }
6381 
6382 /// An AA to represent the memory behavior function attributes.
6383 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
6384   AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
6385       : AAMemoryLocationImpl(IRP, A) {}
6386 
6387   /// See AbstractAttribute::updateImpl(Attributor &A).
6388   virtual ChangeStatus updateImpl(Attributor &A) override {
6389 
6390     const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
6391         *this, getIRPosition(), /* TrackDependence */ false);
6392     if (MemBehaviorAA.isAssumedReadNone()) {
6393       if (MemBehaviorAA.isKnownReadNone())
6394         return indicateOptimisticFixpoint();
6395       assert(isAssumedReadNone() &&
6396              "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
6397       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
6398       return ChangeStatus::UNCHANGED;
6399     }
6400 
6401     // The current assumed state used to determine a change.
6402     auto AssumedState = getAssumed();
6403     bool Changed = false;
6404 
6405     auto CheckRWInst = [&](Instruction &I) {
6406       MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
6407       LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
6408                         << ": " << getMemoryLocationsAsStr(MLK) << "\n");
6409       removeAssumedBits(inverseLocation(MLK, false, false));
6410       return true;
6411     };
6412 
6413     if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this))
6414       return indicatePessimisticFixpoint();
6415 
6416     Changed |= AssumedState != getAssumed();
6417     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
6418   }
6419 
6420   /// See AbstractAttribute::trackStatistics()
6421   void trackStatistics() const override {
6422     if (isAssumedReadNone())
6423       STATS_DECLTRACK_FN_ATTR(readnone)
6424     else if (isAssumedArgMemOnly())
6425       STATS_DECLTRACK_FN_ATTR(argmemonly)
6426     else if (isAssumedInaccessibleMemOnly())
6427       STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
6428     else if (isAssumedInaccessibleOrArgMemOnly())
6429       STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
6430   }
6431 };
6432 
6433 /// AAMemoryLocation attribute for call sites.
6434 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
6435   AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
6436       : AAMemoryLocationImpl(IRP, A) {}
6437 
6438   /// See AbstractAttribute::initialize(...).
6439   void initialize(Attributor &A) override {
6440     AAMemoryLocationImpl::initialize(A);
6441     Function *F = getAssociatedFunction();
6442     if (!F || !A.isFunctionIPOAmendable(*F))
6443       indicatePessimisticFixpoint();
6444   }
6445 
6446   /// See AbstractAttribute::updateImpl(...).
6447   ChangeStatus updateImpl(Attributor &A) override {
6448     // TODO: Once we have call site specific value information we can provide
6449     //       call site specific liveness liveness information and then it makes
6450     //       sense to specialize attributes for call sites arguments instead of
6451     //       redirecting requests to the callee argument.
6452     Function *F = getAssociatedFunction();
6453     const IRPosition &FnPos = IRPosition::function(*F);
6454     auto &FnAA = A.getAAFor<AAMemoryLocation>(*this, FnPos);
6455     bool Changed = false;
6456     auto AccessPred = [&](const Instruction *I, const Value *Ptr,
6457                           AccessKind Kind, MemoryLocationsKind MLK) {
6458       updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed);
6459       return true;
6460     };
6461     if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
6462       return indicatePessimisticFixpoint();
6463     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
6464   }
6465 
6466   /// See AbstractAttribute::trackStatistics()
6467   void trackStatistics() const override {
6468     if (isAssumedReadNone())
6469       STATS_DECLTRACK_CS_ATTR(readnone)
6470   }
6471 };
6472 
6473 /// ------------------ Value Constant Range Attribute -------------------------
6474 
6475 struct AAValueConstantRangeImpl : AAValueConstantRange {
6476   using StateType = IntegerRangeState;
6477   AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
6478       : AAValueConstantRange(IRP, A) {}
6479 
6480   /// See AbstractAttribute::getAsStr().
6481   const std::string getAsStr() const override {
6482     std::string Str;
6483     llvm::raw_string_ostream OS(Str);
6484     OS << "range(" << getBitWidth() << ")<";
6485     getKnown().print(OS);
6486     OS << " / ";
6487     getAssumed().print(OS);
6488     OS << ">";
6489     return OS.str();
6490   }
6491 
6492   /// Helper function to get a SCEV expr for the associated value at program
6493   /// point \p I.
6494   const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
6495     if (!getAnchorScope())
6496       return nullptr;
6497 
6498     ScalarEvolution *SE =
6499         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
6500             *getAnchorScope());
6501 
6502     LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
6503         *getAnchorScope());
6504 
6505     if (!SE || !LI)
6506       return nullptr;
6507 
6508     const SCEV *S = SE->getSCEV(&getAssociatedValue());
6509     if (!I)
6510       return S;
6511 
6512     return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
6513   }
6514 
6515   /// Helper function to get a range from SCEV for the associated value at
6516   /// program point \p I.
6517   ConstantRange getConstantRangeFromSCEV(Attributor &A,
6518                                          const Instruction *I = nullptr) const {
6519     if (!getAnchorScope())
6520       return getWorstState(getBitWidth());
6521 
6522     ScalarEvolution *SE =
6523         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
6524             *getAnchorScope());
6525 
6526     const SCEV *S = getSCEV(A, I);
6527     if (!SE || !S)
6528       return getWorstState(getBitWidth());
6529 
6530     return SE->getUnsignedRange(S);
6531   }
6532 
6533   /// Helper function to get a range from LVI for the associated value at
6534   /// program point \p I.
6535   ConstantRange
6536   getConstantRangeFromLVI(Attributor &A,
6537                           const Instruction *CtxI = nullptr) const {
6538     if (!getAnchorScope())
6539       return getWorstState(getBitWidth());
6540 
6541     LazyValueInfo *LVI =
6542         A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
6543             *getAnchorScope());
6544 
6545     if (!LVI || !CtxI)
6546       return getWorstState(getBitWidth());
6547     return LVI->getConstantRange(&getAssociatedValue(),
6548                                  const_cast<BasicBlock *>(CtxI->getParent()),
6549                                  const_cast<Instruction *>(CtxI));
6550   }
6551 
6552   /// See AAValueConstantRange::getKnownConstantRange(..).
6553   ConstantRange
6554   getKnownConstantRange(Attributor &A,
6555                         const Instruction *CtxI = nullptr) const override {
6556     if (!CtxI || CtxI == getCtxI())
6557       return getKnown();
6558 
6559     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
6560     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
6561     return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
6562   }
6563 
6564   /// See AAValueConstantRange::getAssumedConstantRange(..).
6565   ConstantRange
6566   getAssumedConstantRange(Attributor &A,
6567                           const Instruction *CtxI = nullptr) const override {
6568     // TODO: Make SCEV use Attributor assumption.
6569     //       We may be able to bound a variable range via assumptions in
6570     //       Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
6571     //       evolve to x^2 + x, then we can say that y is in [2, 12].
6572 
6573     if (!CtxI || CtxI == getCtxI())
6574       return getAssumed();
6575 
6576     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
6577     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
6578     return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
6579   }
6580 
6581   /// See AbstractAttribute::initialize(..).
6582   void initialize(Attributor &A) override {
6583     // Intersect a range given by SCEV.
6584     intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
6585 
6586     // Intersect a range given by LVI.
6587     intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
6588   }
6589 
6590   /// Helper function to create MDNode for range metadata.
6591   static MDNode *
6592   getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
6593                             const ConstantRange &AssumedConstantRange) {
6594     Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
6595                                   Ty, AssumedConstantRange.getLower())),
6596                               ConstantAsMetadata::get(ConstantInt::get(
6597                                   Ty, AssumedConstantRange.getUpper()))};
6598     return MDNode::get(Ctx, LowAndHigh);
6599   }
6600 
6601   /// Return true if \p Assumed is included in \p KnownRanges.
6602   static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) {
6603 
6604     if (Assumed.isFullSet())
6605       return false;
6606 
6607     if (!KnownRanges)
6608       return true;
6609 
6610     // If multiple ranges are annotated in IR, we give up to annotate assumed
6611     // range for now.
6612 
6613     // TODO:  If there exists a known range which containts assumed range, we
6614     // can say assumed range is better.
6615     if (KnownRanges->getNumOperands() > 2)
6616       return false;
6617 
6618     ConstantInt *Lower =
6619         mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
6620     ConstantInt *Upper =
6621         mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
6622 
6623     ConstantRange Known(Lower->getValue(), Upper->getValue());
6624     return Known.contains(Assumed) && Known != Assumed;
6625   }
6626 
6627   /// Helper function to set range metadata.
6628   static bool
6629   setRangeMetadataIfisBetterRange(Instruction *I,
6630                                   const ConstantRange &AssumedConstantRange) {
6631     auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range);
6632     if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
6633       if (!AssumedConstantRange.isEmptySet()) {
6634         I->setMetadata(LLVMContext::MD_range,
6635                        getMDNodeForConstantRange(I->getType(), I->getContext(),
6636                                                  AssumedConstantRange));
6637         return true;
6638       }
6639     }
6640     return false;
6641   }
6642 
6643   /// See AbstractAttribute::manifest()
6644   ChangeStatus manifest(Attributor &A) override {
6645     ChangeStatus Changed = ChangeStatus::UNCHANGED;
6646     ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
6647     assert(!AssumedConstantRange.isFullSet() && "Invalid state");
6648 
6649     auto &V = getAssociatedValue();
6650     if (!AssumedConstantRange.isEmptySet() &&
6651         !AssumedConstantRange.isSingleElement()) {
6652       if (Instruction *I = dyn_cast<Instruction>(&V))
6653         if (isa<CallInst>(I) || isa<LoadInst>(I))
6654           if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
6655             Changed = ChangeStatus::CHANGED;
6656     }
6657 
6658     return Changed;
6659   }
6660 };
6661 
6662 struct AAValueConstantRangeArgument final
6663     : AAArgumentFromCallSiteArguments<
6664           AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState> {
6665   using Base = AAArgumentFromCallSiteArguments<
6666       AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState>;
6667   AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
6668       : Base(IRP, A) {}
6669 
6670   /// See AbstractAttribute::initialize(..).
6671   void initialize(Attributor &A) override {
6672     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
6673       indicatePessimisticFixpoint();
6674     } else {
6675       Base::initialize(A);
6676     }
6677   }
6678 
6679   /// See AbstractAttribute::trackStatistics()
6680   void trackStatistics() const override {
6681     STATS_DECLTRACK_ARG_ATTR(value_range)
6682   }
6683 };
6684 
6685 struct AAValueConstantRangeReturned
6686     : AAReturnedFromReturnedValues<AAValueConstantRange,
6687                                    AAValueConstantRangeImpl> {
6688   using Base = AAReturnedFromReturnedValues<AAValueConstantRange,
6689                                             AAValueConstantRangeImpl>;
6690   AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
6691       : Base(IRP, A) {}
6692 
6693   /// See AbstractAttribute::initialize(...).
6694   void initialize(Attributor &A) override {}
6695 
6696   /// See AbstractAttribute::trackStatistics()
6697   void trackStatistics() const override {
6698     STATS_DECLTRACK_FNRET_ATTR(value_range)
6699   }
6700 };
6701 
6702 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
6703   AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
6704       : AAValueConstantRangeImpl(IRP, A) {}
6705 
6706   /// See AbstractAttribute::initialize(...).
6707   void initialize(Attributor &A) override {
6708     AAValueConstantRangeImpl::initialize(A);
6709     Value &V = getAssociatedValue();
6710 
6711     if (auto *C = dyn_cast<ConstantInt>(&V)) {
6712       unionAssumed(ConstantRange(C->getValue()));
6713       indicateOptimisticFixpoint();
6714       return;
6715     }
6716 
6717     if (isa<UndefValue>(&V)) {
6718       // Collapse the undef state to 0.
6719       unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
6720       indicateOptimisticFixpoint();
6721       return;
6722     }
6723 
6724     if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V))
6725       return;
6726     // If it is a load instruction with range metadata, use it.
6727     if (LoadInst *LI = dyn_cast<LoadInst>(&V))
6728       if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
6729         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
6730         return;
6731       }
6732 
6733     // We can work with PHI and select instruction as we traverse their operands
6734     // during update.
6735     if (isa<SelectInst>(V) || isa<PHINode>(V))
6736       return;
6737 
6738     // Otherwise we give up.
6739     indicatePessimisticFixpoint();
6740 
6741     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
6742                       << getAssociatedValue() << "\n");
6743   }
6744 
6745   bool calculateBinaryOperator(
6746       Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
6747       const Instruction *CtxI,
6748       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
6749     Value *LHS = BinOp->getOperand(0);
6750     Value *RHS = BinOp->getOperand(1);
6751     // TODO: Allow non integers as well.
6752     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
6753       return false;
6754 
6755     auto &LHSAA =
6756         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
6757     QuerriedAAs.push_back(&LHSAA);
6758     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
6759 
6760     auto &RHSAA =
6761         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
6762     QuerriedAAs.push_back(&RHSAA);
6763     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
6764 
6765     auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
6766 
6767     T.unionAssumed(AssumedRange);
6768 
6769     // TODO: Track a known state too.
6770 
6771     return T.isValidState();
6772   }
6773 
6774   bool calculateCastInst(
6775       Attributor &A, CastInst *CastI, IntegerRangeState &T,
6776       const Instruction *CtxI,
6777       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
6778     assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
6779     // TODO: Allow non integers as well.
6780     Value &OpV = *CastI->getOperand(0);
6781     if (!OpV.getType()->isIntegerTy())
6782       return false;
6783 
6784     auto &OpAA =
6785         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(OpV));
6786     QuerriedAAs.push_back(&OpAA);
6787     T.unionAssumed(
6788         OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth()));
6789     return T.isValidState();
6790   }
6791 
6792   bool
6793   calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
6794                    const Instruction *CtxI,
6795                    SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
6796     Value *LHS = CmpI->getOperand(0);
6797     Value *RHS = CmpI->getOperand(1);
6798     // TODO: Allow non integers as well.
6799     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
6800       return false;
6801 
6802     auto &LHSAA =
6803         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*LHS));
6804     QuerriedAAs.push_back(&LHSAA);
6805     auto &RHSAA =
6806         A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(*RHS));
6807     QuerriedAAs.push_back(&RHSAA);
6808 
6809     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
6810     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
6811 
6812     // If one of them is empty set, we can't decide.
6813     if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
6814       return true;
6815 
6816     bool MustTrue = false, MustFalse = false;
6817 
6818     auto AllowedRegion =
6819         ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange);
6820 
6821     auto SatisfyingRegion = ConstantRange::makeSatisfyingICmpRegion(
6822         CmpI->getPredicate(), RHSAARange);
6823 
6824     if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
6825       MustFalse = true;
6826 
6827     if (SatisfyingRegion.contains(LHSAARange))
6828       MustTrue = true;
6829 
6830     assert((!MustTrue || !MustFalse) &&
6831            "Either MustTrue or MustFalse should be false!");
6832 
6833     if (MustTrue)
6834       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
6835     else if (MustFalse)
6836       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
6837     else
6838       T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
6839 
6840     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA
6841                       << " " << RHSAA << "\n");
6842 
6843     // TODO: Track a known state too.
6844     return T.isValidState();
6845   }
6846 
6847   /// See AbstractAttribute::updateImpl(...).
6848   ChangeStatus updateImpl(Attributor &A) override {
6849     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
6850                             IntegerRangeState &T, bool Stripped) -> bool {
6851       Instruction *I = dyn_cast<Instruction>(&V);
6852       if (!I || isa<CallBase>(I)) {
6853 
6854         // If the value is not instruction, we query AA to Attributor.
6855         const auto &AA =
6856             A.getAAFor<AAValueConstantRange>(*this, IRPosition::value(V));
6857 
6858         // Clamp operator is not used to utilize a program point CtxI.
6859         T.unionAssumed(AA.getAssumedConstantRange(A, CtxI));
6860 
6861         return T.isValidState();
6862       }
6863 
6864       SmallVector<const AAValueConstantRange *, 4> QuerriedAAs;
6865       if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
6866         if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
6867           return false;
6868       } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
6869         if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
6870           return false;
6871       } else if (auto *CastI = dyn_cast<CastInst>(I)) {
6872         if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
6873           return false;
6874       } else {
6875         // Give up with other instructions.
6876         // TODO: Add other instructions
6877 
6878         T.indicatePessimisticFixpoint();
6879         return false;
6880       }
6881 
6882       // Catch circular reasoning in a pessimistic way for now.
6883       // TODO: Check how the range evolves and if we stripped anything, see also
6884       //       AADereferenceable or AAAlign for similar situations.
6885       for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
6886         if (QueriedAA != this)
6887           continue;
6888         // If we are in a stady state we do not need to worry.
6889         if (T.getAssumed() == getState().getAssumed())
6890           continue;
6891         T.indicatePessimisticFixpoint();
6892       }
6893 
6894       return T.isValidState();
6895     };
6896 
6897     IntegerRangeState T(getBitWidth());
6898 
6899     if (!genericValueTraversal<AAValueConstantRange, IntegerRangeState>(
6900             A, getIRPosition(), *this, T, VisitValueCB, getCtxI()))
6901       return indicatePessimisticFixpoint();
6902 
6903     return clampStateAndIndicateChange(getState(), T);
6904   }
6905 
6906   /// See AbstractAttribute::trackStatistics()
6907   void trackStatistics() const override {
6908     STATS_DECLTRACK_FLOATING_ATTR(value_range)
6909   }
6910 };
6911 
6912 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
6913   AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
6914       : AAValueConstantRangeImpl(IRP, A) {}
6915 
6916   /// See AbstractAttribute::initialize(...).
6917   ChangeStatus updateImpl(Attributor &A) override {
6918     llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
6919                      "not be called");
6920   }
6921 
6922   /// See AbstractAttribute::trackStatistics()
6923   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
6924 };
6925 
6926 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
6927   AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
6928       : AAValueConstantRangeFunction(IRP, A) {}
6929 
6930   /// See AbstractAttribute::trackStatistics()
6931   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
6932 };
6933 
6934 struct AAValueConstantRangeCallSiteReturned
6935     : AACallSiteReturnedFromReturned<AAValueConstantRange,
6936                                      AAValueConstantRangeImpl> {
6937   AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
6938       : AACallSiteReturnedFromReturned<AAValueConstantRange,
6939                                        AAValueConstantRangeImpl>(IRP, A) {}
6940 
6941   /// See AbstractAttribute::initialize(...).
6942   void initialize(Attributor &A) override {
6943     // If it is a load instruction with range metadata, use the metadata.
6944     if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue()))
6945       if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
6946         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
6947 
6948     AAValueConstantRangeImpl::initialize(A);
6949   }
6950 
6951   /// See AbstractAttribute::trackStatistics()
6952   void trackStatistics() const override {
6953     STATS_DECLTRACK_CSRET_ATTR(value_range)
6954   }
6955 };
6956 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
6957   AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
6958       : AAValueConstantRangeFloating(IRP, A) {}
6959 
6960   /// See AbstractAttribute::trackStatistics()
6961   void trackStatistics() const override {
6962     STATS_DECLTRACK_CSARG_ATTR(value_range)
6963   }
6964 };
6965 
6966 const char AAReturnedValues::ID = 0;
6967 const char AANoUnwind::ID = 0;
6968 const char AANoSync::ID = 0;
6969 const char AANoFree::ID = 0;
6970 const char AANonNull::ID = 0;
6971 const char AANoRecurse::ID = 0;
6972 const char AAWillReturn::ID = 0;
6973 const char AAUndefinedBehavior::ID = 0;
6974 const char AANoAlias::ID = 0;
6975 const char AAReachability::ID = 0;
6976 const char AANoReturn::ID = 0;
6977 const char AAIsDead::ID = 0;
6978 const char AADereferenceable::ID = 0;
6979 const char AAAlign::ID = 0;
6980 const char AANoCapture::ID = 0;
6981 const char AAValueSimplify::ID = 0;
6982 const char AAHeapToStack::ID = 0;
6983 const char AAPrivatizablePtr::ID = 0;
6984 const char AAMemoryBehavior::ID = 0;
6985 const char AAMemoryLocation::ID = 0;
6986 const char AAValueConstantRange::ID = 0;
6987 
6988 // Macro magic to create the static generator function for attributes that
6989 // follow the naming scheme.
6990 
6991 #define SWITCH_PK_INV(CLASS, PK, POS_NAME)                                     \
6992   case IRPosition::PK:                                                         \
6993     llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
6994 
6995 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX)                               \
6996   case IRPosition::PK:                                                         \
6997     AA = new (A.Allocator) CLASS##SUFFIX(IRP, A);                              \
6998     break;
6999 
7000 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                 \
7001   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7002     CLASS *AA = nullptr;                                                       \
7003     switch (IRP.getPositionKind()) {                                           \
7004       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7005       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
7006       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
7007       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7008       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
7009       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
7010       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7011       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7012     }                                                                          \
7013     return *AA;                                                                \
7014   }
7015 
7016 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                    \
7017   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7018     CLASS *AA = nullptr;                                                       \
7019     switch (IRP.getPositionKind()) {                                           \
7020       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7021       SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function")                           \
7022       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
7023       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7024       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7025       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
7026       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7027       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7028     }                                                                          \
7029     return *AA;                                                                \
7030   }
7031 
7032 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                      \
7033   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7034     CLASS *AA = nullptr;                                                       \
7035     switch (IRP.getPositionKind()) {                                           \
7036       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7037       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7038       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7039       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7040       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7041       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
7042       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7043       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7044     }                                                                          \
7045     return *AA;                                                                \
7046   }
7047 
7048 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)            \
7049   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7050     CLASS *AA = nullptr;                                                       \
7051     switch (IRP.getPositionKind()) {                                           \
7052       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7053       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
7054       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
7055       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7056       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
7057       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
7058       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
7059       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7060     }                                                                          \
7061     return *AA;                                                                \
7062   }
7063 
7064 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                  \
7065   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
7066     CLASS *AA = nullptr;                                                       \
7067     switch (IRP.getPositionKind()) {                                           \
7068       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
7069       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
7070       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
7071       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
7072       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
7073       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
7074       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
7075       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
7076     }                                                                          \
7077     return *AA;                                                                \
7078   }
7079 
7080 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
7081 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
7082 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
7083 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
7084 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
7085 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
7086 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation)
7087 
7088 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
7089 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
7090 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr)
7091 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
7092 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
7093 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture)
7094 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange)
7095 
7096 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify)
7097 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
7098 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
7099 
7100 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack)
7101 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability)
7102 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior)
7103 
7104 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior)
7105 
7106 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
7107 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
7108 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
7109 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
7110 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
7111 #undef SWITCH_PK_CREATE
7112 #undef SWITCH_PK_INV
7113