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