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