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/APInt.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetOperations.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/AssumeBundleQueries.h"
26 #include "llvm/Analysis/AssumptionCache.h"
27 #include "llvm/Analysis/CaptureTracking.h"
28 #include "llvm/Analysis/InstructionSimplify.h"
29 #include "llvm/Analysis/LazyValueInfo.h"
30 #include "llvm/Analysis/MemoryBuiltins.h"
31 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
32 #include "llvm/Analysis/ScalarEvolution.h"
33 #include "llvm/Analysis/TargetTransformInfo.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Assumptions.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/NoFolder.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/IR/ValueHandle.h"
47 #include "llvm/Support/Alignment.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/GraphWriter.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Transforms/Utils/ValueMapper.h"
57 #include <cassert>
58 
59 using namespace llvm;
60 
61 #define DEBUG_TYPE "attributor"
62 
63 static cl::opt<bool> ManifestInternal(
64     "attributor-manifest-internal", cl::Hidden,
65     cl::desc("Manifest Attributor internal string attributes."),
66     cl::init(false));
67 
68 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128),
69                                        cl::Hidden);
70 
71 template <>
72 unsigned llvm::PotentialConstantIntValuesState::MaxPotentialValues = 0;
73 
74 static cl::opt<unsigned, true> MaxPotentialValues(
75     "attributor-max-potential-values", cl::Hidden,
76     cl::desc("Maximum number of potential values to be "
77              "tracked for each position."),
78     cl::location(llvm::PotentialConstantIntValuesState::MaxPotentialValues),
79     cl::init(7));
80 
81 static cl::opt<unsigned> MaxInterferingAccesses(
82     "attributor-max-interfering-accesses", cl::Hidden,
83     cl::desc("Maximum number of interfering accesses to "
84              "check before assuming all might interfere."),
85     cl::init(6));
86 
87 STATISTIC(NumAAs, "Number of abstract attributes created");
88 
89 // Some helper macros to deal with statistics tracking.
90 //
91 // Usage:
92 // For simple IR attribute tracking overload trackStatistics in the abstract
93 // attribute and choose the right STATS_DECLTRACK_********* macro,
94 // e.g.,:
95 //  void trackStatistics() const override {
96 //    STATS_DECLTRACK_ARG_ATTR(returned)
97 //  }
98 // If there is a single "increment" side one can use the macro
99 // STATS_DECLTRACK with a custom message. If there are multiple increment
100 // sides, STATS_DECL and STATS_TRACK can also be used separately.
101 //
102 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME)                                     \
103   ("Number of " #TYPE " marked '" #NAME "'")
104 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
105 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
106 #define STATS_DECL(NAME, TYPE, MSG)                                            \
107   STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
108 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
109 #define STATS_DECLTRACK(NAME, TYPE, MSG)                                       \
110   {                                                                            \
111     STATS_DECL(NAME, TYPE, MSG)                                                \
112     STATS_TRACK(NAME, TYPE)                                                    \
113   }
114 #define STATS_DECLTRACK_ARG_ATTR(NAME)                                         \
115   STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
116 #define STATS_DECLTRACK_CSARG_ATTR(NAME)                                       \
117   STATS_DECLTRACK(NAME, CSArguments,                                           \
118                   BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
119 #define STATS_DECLTRACK_FN_ATTR(NAME)                                          \
120   STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
121 #define STATS_DECLTRACK_CS_ATTR(NAME)                                          \
122   STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
123 #define STATS_DECLTRACK_FNRET_ATTR(NAME)                                       \
124   STATS_DECLTRACK(NAME, FunctionReturn,                                        \
125                   BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
126 #define STATS_DECLTRACK_CSRET_ATTR(NAME)                                       \
127   STATS_DECLTRACK(NAME, CSReturn,                                              \
128                   BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
129 #define STATS_DECLTRACK_FLOATING_ATTR(NAME)                                    \
130   STATS_DECLTRACK(NAME, Floating,                                              \
131                   ("Number of floating values known to be '" #NAME "'"))
132 
133 // Specialization of the operator<< for abstract attributes subclasses. This
134 // disambiguates situations where multiple operators are applicable.
135 namespace llvm {
136 #define PIPE_OPERATOR(CLASS)                                                   \
137   raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) {                  \
138     return OS << static_cast<const AbstractAttribute &>(AA);                   \
139   }
140 
141 PIPE_OPERATOR(AAIsDead)
142 PIPE_OPERATOR(AANoUnwind)
143 PIPE_OPERATOR(AANoSync)
144 PIPE_OPERATOR(AANoRecurse)
145 PIPE_OPERATOR(AAWillReturn)
146 PIPE_OPERATOR(AANoReturn)
147 PIPE_OPERATOR(AAReturnedValues)
148 PIPE_OPERATOR(AANonNull)
149 PIPE_OPERATOR(AANoAlias)
150 PIPE_OPERATOR(AADereferenceable)
151 PIPE_OPERATOR(AAAlign)
152 PIPE_OPERATOR(AAInstanceInfo)
153 PIPE_OPERATOR(AANoCapture)
154 PIPE_OPERATOR(AAValueSimplify)
155 PIPE_OPERATOR(AANoFree)
156 PIPE_OPERATOR(AAHeapToStack)
157 PIPE_OPERATOR(AAReachability)
158 PIPE_OPERATOR(AAMemoryBehavior)
159 PIPE_OPERATOR(AAMemoryLocation)
160 PIPE_OPERATOR(AAValueConstantRange)
161 PIPE_OPERATOR(AAPrivatizablePtr)
162 PIPE_OPERATOR(AAUndefinedBehavior)
163 PIPE_OPERATOR(AAPotentialConstantValues)
164 PIPE_OPERATOR(AANoUndef)
165 PIPE_OPERATOR(AACallEdges)
166 PIPE_OPERATOR(AAFunctionReachability)
167 PIPE_OPERATOR(AAPointerInfo)
168 PIPE_OPERATOR(AAAssumptionInfo)
169 
170 #undef PIPE_OPERATOR
171 
172 template <>
173 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S,
174                                                      const DerefState &R) {
175   ChangeStatus CS0 =
176       clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
177   ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
178   return CS0 | CS1;
179 }
180 
181 } // namespace llvm
182 
183 /// Get pointer operand of memory accessing instruction. If \p I is
184 /// not a memory accessing instruction, return nullptr. If \p AllowVolatile,
185 /// is set to false and the instruction is volatile, return nullptr.
186 static const Value *getPointerOperand(const Instruction *I,
187                                       bool AllowVolatile) {
188   if (!AllowVolatile && I->isVolatile())
189     return nullptr;
190 
191   if (auto *LI = dyn_cast<LoadInst>(I)) {
192     return LI->getPointerOperand();
193   }
194 
195   if (auto *SI = dyn_cast<StoreInst>(I)) {
196     return SI->getPointerOperand();
197   }
198 
199   if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) {
200     return CXI->getPointerOperand();
201   }
202 
203   if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) {
204     return RMWI->getPointerOperand();
205   }
206 
207   return nullptr;
208 }
209 
210 /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and
211 /// advanced by \p Offset bytes. To aid later analysis the method tries to build
212 /// getelement pointer instructions that traverse the natural type of \p Ptr if
213 /// possible. If that fails, the remaining offset is adjusted byte-wise, hence
214 /// through a cast to i8*.
215 ///
216 /// TODO: This could probably live somewhere more prominantly if it doesn't
217 ///       already exist.
218 static Value *constructPointer(Type *ResTy, Type *PtrElemTy, Value *Ptr,
219                                int64_t Offset, IRBuilder<NoFolder> &IRB,
220                                const DataLayout &DL) {
221   assert(Offset >= 0 && "Negative offset not supported yet!");
222   LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset
223                     << "-bytes as " << *ResTy << "\n");
224 
225   if (Offset) {
226     Type *Ty = PtrElemTy;
227     APInt IntOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), Offset);
228     SmallVector<APInt> IntIndices = DL.getGEPIndicesForOffset(Ty, IntOffset);
229 
230     SmallVector<Value *, 4> ValIndices;
231     std::string GEPName = Ptr->getName().str();
232     for (const APInt &Index : IntIndices) {
233       ValIndices.push_back(IRB.getInt(Index));
234       GEPName += "." + std::to_string(Index.getZExtValue());
235     }
236 
237     // Create a GEP for the indices collected above.
238     Ptr = IRB.CreateGEP(PtrElemTy, Ptr, ValIndices, GEPName);
239 
240     // If an offset is left we use byte-wise adjustment.
241     if (IntOffset != 0) {
242       Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy());
243       Ptr = IRB.CreateGEP(IRB.getInt8Ty(), Ptr, IRB.getInt(IntOffset),
244                           GEPName + ".b" + Twine(IntOffset.getZExtValue()));
245     }
246   }
247 
248   // Ensure the result has the requested type.
249   Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, ResTy,
250                                                 Ptr->getName() + ".cast");
251 
252   LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n");
253   return Ptr;
254 }
255 
256 /// Recursively visit all values that might become \p IRP at some point. This
257 /// will be done by looking through cast instructions, selects, phis, and calls
258 /// with the "returned" attribute. Once we cannot look through the value any
259 /// further, the callback \p VisitValueCB is invoked and passed the current
260 /// value, the \p State, and a flag to indicate if we stripped anything.
261 /// Stripped means that we unpacked the value associated with \p IRP at least
262 /// once. Note that the value used for the callback may still be the value
263 /// associated with \p IRP (due to PHIs). To limit how much effort is invested,
264 /// we will never visit more values than specified by \p MaxValues.
265 /// If \p VS does not contain the Interprocedural bit, only values valid in the
266 /// scope of \p CtxI will be visited and simplification into other scopes is
267 /// prevented.
268 template <typename StateTy>
269 static bool genericValueTraversal(
270     Attributor &A, IRPosition IRP, const AbstractAttribute &QueryingAA,
271     StateTy &State,
272     function_ref<bool(Value &, const Instruction *, StateTy &, bool)>
273         VisitValueCB,
274     const Instruction *CtxI, bool &UsedAssumedInformation,
275     bool UseValueSimplify = true, int MaxValues = 16,
276     function_ref<Value *(Value *)> StripCB = nullptr,
277     AA::ValueScope VS = AA::Interprocedural) {
278 
279   struct LivenessInfo {
280     const AAIsDead *LivenessAA = nullptr;
281     bool AnyDead = false;
282   };
283   SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs;
284   auto GetLivenessInfo = [&](const Function &F) -> LivenessInfo & {
285     LivenessInfo &LI = LivenessAAs[&F];
286     if (!LI.LivenessAA)
287       LI.LivenessAA = &A.getAAFor<AAIsDead>(QueryingAA, IRPosition::function(F),
288                                             DepClassTy::NONE);
289     return LI;
290   };
291 
292   Value *InitialV = &IRP.getAssociatedValue();
293   using Item = std::pair<Value *, const Instruction *>;
294   SmallSet<Item, 16> Visited;
295   SmallVector<Item, 16> Worklist;
296   Worklist.push_back({InitialV, CtxI});
297 
298   int Iteration = 0;
299   do {
300     Item I = Worklist.pop_back_val();
301     Value *V = I.first;
302     CtxI = I.second;
303     if (StripCB)
304       V = StripCB(V);
305 
306     // Check if we should process the current value. To prevent endless
307     // recursion keep a record of the values we followed!
308     if (!Visited.insert(I).second)
309       continue;
310 
311     // Make sure we limit the compile time for complex expressions.
312     if (Iteration++ >= MaxValues) {
313       LLVM_DEBUG(dbgs() << "Generic value traversal reached iteration limit: "
314                         << Iteration << "!\n");
315       return false;
316     }
317 
318     // Explicitly look through calls with a "returned" attribute if we do
319     // not have a pointer as stripPointerCasts only works on them.
320     Value *NewV = nullptr;
321     if (V->getType()->isPointerTy()) {
322       NewV = V->stripPointerCasts();
323     } else {
324       auto *CB = dyn_cast<CallBase>(V);
325       if (CB && CB->getCalledFunction()) {
326         for (Argument &Arg : CB->getCalledFunction()->args())
327           if (Arg.hasReturnedAttr()) {
328             NewV = CB->getArgOperand(Arg.getArgNo());
329             break;
330           }
331       }
332     }
333     if (NewV && NewV != V) {
334       Worklist.push_back({NewV, CtxI});
335       continue;
336     }
337 
338     // Look through select instructions, visit assumed potential values.
339     if (auto *SI = dyn_cast<SelectInst>(V)) {
340       Optional<Constant *> C = A.getAssumedConstant(
341           *SI->getCondition(), QueryingAA, UsedAssumedInformation);
342       bool NoValueYet = !C.hasValue();
343       if (NoValueYet || isa_and_nonnull<UndefValue>(*C))
344         continue;
345       if (auto *CI = dyn_cast_or_null<ConstantInt>(*C)) {
346         if (CI->isZero())
347           Worklist.push_back({SI->getFalseValue(), CtxI});
348         else
349           Worklist.push_back({SI->getTrueValue(), CtxI});
350         continue;
351       }
352       // We could not simplify the condition, assume both values.(
353       Worklist.push_back({SI->getTrueValue(), CtxI});
354       Worklist.push_back({SI->getFalseValue(), CtxI});
355       continue;
356     }
357 
358     // Look through phi nodes, visit all live operands.
359     if (auto *PHI = dyn_cast<PHINode>(V)) {
360       LivenessInfo &LI = GetLivenessInfo(*PHI->getFunction());
361       for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
362         BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
363         if (LI.LivenessAA->isEdgeDead(IncomingBB, PHI->getParent())) {
364           LI.AnyDead = true;
365           UsedAssumedInformation |= !LI.LivenessAA->isAtFixpoint();
366           continue;
367         }
368         Worklist.push_back(
369             {PHI->getIncomingValue(u), IncomingBB->getTerminator()});
370       }
371       continue;
372     }
373 
374     if (auto *Arg = dyn_cast<Argument>(V)) {
375       if ((VS & AA::Interprocedural) && !Arg->hasPassPointeeByValueCopyAttr()) {
376         SmallVector<Item> CallSiteValues;
377         bool UsedAssumedInformation = false;
378         if (A.checkForAllCallSites(
379                 [&](AbstractCallSite ACS) {
380                   // Callbacks might not have a corresponding call site operand,
381                   // stick with the argument in that case.
382                   Value *CSOp = ACS.getCallArgOperand(*Arg);
383                   if (!CSOp)
384                     return false;
385                   CallSiteValues.push_back({CSOp, ACS.getInstruction()});
386                   return true;
387                 },
388                 *Arg->getParent(), true, &QueryingAA, UsedAssumedInformation)) {
389           Worklist.append(CallSiteValues);
390           continue;
391         }
392       }
393     }
394 
395     if (UseValueSimplify && !isa<Constant>(V)) {
396       Optional<Value *> SimpleV =
397           A.getAssumedSimplified(*V, QueryingAA, UsedAssumedInformation);
398       if (!SimpleV.hasValue())
399         continue;
400       Value *NewV = SimpleV.getValue();
401       if (NewV && NewV != V) {
402         if ((VS & AA::Interprocedural) || !CtxI ||
403             AA::isValidInScope(*NewV, CtxI->getFunction())) {
404           Worklist.push_back({NewV, CtxI});
405           continue;
406         }
407       }
408     }
409 
410     if (auto *LI = dyn_cast<LoadInst>(V)) {
411       bool UsedAssumedInformation = false;
412       // If we ask for the potentially loaded values from the initial pointer we
413       // will simply end up here again. The load is as far as we can make it.
414       if (LI->getPointerOperand() != InitialV) {
415         SmallSetVector<Value *, 4> PotentialCopies;
416         SmallSetVector<Instruction *, 4> PotentialValueOrigins;
417         if (AA::getPotentiallyLoadedValues(A, *LI, PotentialCopies,
418                                            PotentialValueOrigins, QueryingAA,
419                                            UsedAssumedInformation,
420                                            /* OnlyExact */ true)) {
421           // Values have to be dynamically unique or we loose the fact that a
422           // single llvm::Value might represent two runtime values (e.g., stack
423           // locations in different recursive calls).
424           bool DynamicallyUnique =
425               llvm::all_of(PotentialCopies, [&A, &QueryingAA](Value *PC) {
426                 return AA::isDynamicallyUnique(A, QueryingAA, *PC);
427               });
428           if (DynamicallyUnique &&
429               ((VS & AA::Interprocedural) || !CtxI ||
430                llvm::all_of(PotentialCopies, [CtxI](Value *PC) {
431                  return AA::isValidInScope(*PC, CtxI->getFunction());
432                }))) {
433             for (auto *PotentialCopy : PotentialCopies)
434               Worklist.push_back({PotentialCopy, CtxI});
435             continue;
436           }
437         }
438       }
439     }
440 
441     // Once a leaf is reached we inform the user through the callback.
442     if (!VisitValueCB(*V, CtxI, State, Iteration > 1)) {
443       LLVM_DEBUG(dbgs() << "Generic value traversal visit callback failed for: "
444                         << *V << "!\n");
445       return false;
446     }
447   } while (!Worklist.empty());
448 
449   // If we actually used liveness information so we have to record a dependence.
450   for (auto &It : LivenessAAs)
451     if (It.second.AnyDead)
452       A.recordDependence(*It.second.LivenessAA, QueryingAA,
453                          DepClassTy::OPTIONAL);
454 
455   // All values have been visited.
456   return true;
457 }
458 
459 bool AA::getAssumedUnderlyingObjects(Attributor &A, const Value &Ptr,
460                                      SmallVectorImpl<Value *> &Objects,
461                                      const AbstractAttribute &QueryingAA,
462                                      const Instruction *CtxI,
463                                      bool &UsedAssumedInformation,
464                                      AA::ValueScope VS) {
465   auto StripCB = [&](Value *V) { return getUnderlyingObject(V); };
466   SmallPtrSet<Value *, 8> SeenObjects;
467   auto VisitValueCB = [&SeenObjects](Value &Val, const Instruction *,
468                                      SmallVectorImpl<Value *> &Objects,
469                                      bool) -> bool {
470     if (SeenObjects.insert(&Val).second)
471       Objects.push_back(&Val);
472     return true;
473   };
474   if (!genericValueTraversal<decltype(Objects)>(
475           A, IRPosition::value(Ptr), QueryingAA, Objects, VisitValueCB, CtxI,
476           UsedAssumedInformation, true, 32, StripCB, VS))
477     return false;
478   return true;
479 }
480 
481 static const Value *
482 stripAndAccumulateOffsets(Attributor &A, const AbstractAttribute &QueryingAA,
483                           const Value *Val, const DataLayout &DL, APInt &Offset,
484                           bool GetMinOffset, bool AllowNonInbounds,
485                           bool UseAssumed = false) {
486 
487   auto AttributorAnalysis = [&](Value &V, APInt &ROffset) -> bool {
488     const IRPosition &Pos = IRPosition::value(V);
489     // Only track dependence if we are going to use the assumed info.
490     const AAValueConstantRange &ValueConstantRangeAA =
491         A.getAAFor<AAValueConstantRange>(QueryingAA, Pos,
492                                          UseAssumed ? DepClassTy::OPTIONAL
493                                                     : DepClassTy::NONE);
494     ConstantRange Range = UseAssumed ? ValueConstantRangeAA.getAssumed()
495                                      : ValueConstantRangeAA.getKnown();
496     if (Range.isFullSet())
497       return false;
498 
499     // We can only use the lower part of the range because the upper part can
500     // be higher than what the value can really be.
501     if (GetMinOffset)
502       ROffset = Range.getSignedMin();
503     else
504       ROffset = Range.getSignedMax();
505     return true;
506   };
507 
508   return Val->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds,
509                                                 /* AllowInvariant */ true,
510                                                 AttributorAnalysis);
511 }
512 
513 static const Value *
514 getMinimalBaseOfPointer(Attributor &A, const AbstractAttribute &QueryingAA,
515                         const Value *Ptr, int64_t &BytesOffset,
516                         const DataLayout &DL, bool AllowNonInbounds = false) {
517   APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
518   const Value *Base =
519       stripAndAccumulateOffsets(A, QueryingAA, Ptr, DL, OffsetAPInt,
520                                 /* GetMinOffset */ true, AllowNonInbounds);
521 
522   BytesOffset = OffsetAPInt.getSExtValue();
523   return Base;
524 }
525 
526 /// Clamp the information known for all returned values of a function
527 /// (identified by \p QueryingAA) into \p S.
528 template <typename AAType, typename StateType = typename AAType::StateType>
529 static void clampReturnedValueStates(
530     Attributor &A, const AAType &QueryingAA, StateType &S,
531     const IRPosition::CallBaseContext *CBContext = nullptr) {
532   LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for "
533                     << QueryingAA << " into " << S << "\n");
534 
535   assert((QueryingAA.getIRPosition().getPositionKind() ==
536               IRPosition::IRP_RETURNED ||
537           QueryingAA.getIRPosition().getPositionKind() ==
538               IRPosition::IRP_CALL_SITE_RETURNED) &&
539          "Can only clamp returned value states for a function returned or call "
540          "site returned position!");
541 
542   // Use an optional state as there might not be any return values and we want
543   // to join (IntegerState::operator&) the state of all there are.
544   Optional<StateType> T;
545 
546   // Callback for each possibly returned value.
547   auto CheckReturnValue = [&](Value &RV) -> bool {
548     const IRPosition &RVPos = IRPosition::value(RV, CBContext);
549     const AAType &AA =
550         A.getAAFor<AAType>(QueryingAA, RVPos, DepClassTy::REQUIRED);
551     LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr()
552                       << " @ " << RVPos << "\n");
553     const StateType &AAS = AA.getState();
554     if (!T.hasValue())
555       T = StateType::getBestState(AAS);
556     *T &= AAS;
557     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T
558                       << "\n");
559     return T->isValidState();
560   };
561 
562   if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA))
563     S.indicatePessimisticFixpoint();
564   else if (T.hasValue())
565     S ^= *T;
566 }
567 
568 namespace {
569 /// Helper class for generic deduction: return value -> returned position.
570 template <typename AAType, typename BaseType,
571           typename StateType = typename BaseType::StateType,
572           bool PropagateCallBaseContext = false>
573 struct AAReturnedFromReturnedValues : public BaseType {
574   AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A)
575       : BaseType(IRP, A) {}
576 
577   /// See AbstractAttribute::updateImpl(...).
578   ChangeStatus updateImpl(Attributor &A) override {
579     StateType S(StateType::getBestState(this->getState()));
580     clampReturnedValueStates<AAType, StateType>(
581         A, *this, S,
582         PropagateCallBaseContext ? this->getCallBaseContext() : nullptr);
583     // TODO: If we know we visited all returned values, thus no are assumed
584     // dead, we can take the known information from the state T.
585     return clampStateAndIndicateChange<StateType>(this->getState(), S);
586   }
587 };
588 
589 /// Clamp the information known at all call sites for a given argument
590 /// (identified by \p QueryingAA) into \p S.
591 template <typename AAType, typename StateType = typename AAType::StateType>
592 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA,
593                                         StateType &S) {
594   LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for "
595                     << QueryingAA << " into " << S << "\n");
596 
597   assert(QueryingAA.getIRPosition().getPositionKind() ==
598              IRPosition::IRP_ARGUMENT &&
599          "Can only clamp call site argument states for an argument position!");
600 
601   // Use an optional state as there might not be any return values and we want
602   // to join (IntegerState::operator&) the state of all there are.
603   Optional<StateType> T;
604 
605   // The argument number which is also the call site argument number.
606   unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo();
607 
608   auto CallSiteCheck = [&](AbstractCallSite ACS) {
609     const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
610     // Check if a coresponding argument was found or if it is on not associated
611     // (which can happen for callback calls).
612     if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
613       return false;
614 
615     const AAType &AA =
616         A.getAAFor<AAType>(QueryingAA, ACSArgPos, DepClassTy::REQUIRED);
617     LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction()
618                       << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n");
619     const StateType &AAS = AA.getState();
620     if (!T.hasValue())
621       T = StateType::getBestState(AAS);
622     *T &= AAS;
623     LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T
624                       << "\n");
625     return T->isValidState();
626   };
627 
628   bool UsedAssumedInformation = false;
629   if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true,
630                               UsedAssumedInformation))
631     S.indicatePessimisticFixpoint();
632   else if (T.hasValue())
633     S ^= *T;
634 }
635 
636 /// This function is the bridge between argument position and the call base
637 /// context.
638 template <typename AAType, typename BaseType,
639           typename StateType = typename AAType::StateType>
640 bool getArgumentStateFromCallBaseContext(Attributor &A,
641                                          BaseType &QueryingAttribute,
642                                          IRPosition &Pos, StateType &State) {
643   assert((Pos.getPositionKind() == IRPosition::IRP_ARGUMENT) &&
644          "Expected an 'argument' position !");
645   const CallBase *CBContext = Pos.getCallBaseContext();
646   if (!CBContext)
647     return false;
648 
649   int ArgNo = Pos.getCallSiteArgNo();
650   assert(ArgNo >= 0 && "Invalid Arg No!");
651 
652   const auto &AA = A.getAAFor<AAType>(
653       QueryingAttribute, IRPosition::callsite_argument(*CBContext, ArgNo),
654       DepClassTy::REQUIRED);
655   const StateType &CBArgumentState =
656       static_cast<const StateType &>(AA.getState());
657 
658   LLVM_DEBUG(dbgs() << "[Attributor] Briding Call site context to argument"
659                     << "Position:" << Pos << "CB Arg state:" << CBArgumentState
660                     << "\n");
661 
662   // NOTE: If we want to do call site grouping it should happen here.
663   State ^= CBArgumentState;
664   return true;
665 }
666 
667 /// Helper class for generic deduction: call site argument -> argument position.
668 template <typename AAType, typename BaseType,
669           typename StateType = typename AAType::StateType,
670           bool BridgeCallBaseContext = false>
671 struct AAArgumentFromCallSiteArguments : public BaseType {
672   AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A)
673       : BaseType(IRP, A) {}
674 
675   /// See AbstractAttribute::updateImpl(...).
676   ChangeStatus updateImpl(Attributor &A) override {
677     StateType S = StateType::getBestState(this->getState());
678 
679     if (BridgeCallBaseContext) {
680       bool Success =
681           getArgumentStateFromCallBaseContext<AAType, BaseType, StateType>(
682               A, *this, this->getIRPosition(), S);
683       if (Success)
684         return clampStateAndIndicateChange<StateType>(this->getState(), S);
685     }
686     clampCallSiteArgumentStates<AAType, StateType>(A, *this, S);
687 
688     // TODO: If we know we visited all incoming values, thus no are assumed
689     // dead, we can take the known information from the state T.
690     return clampStateAndIndicateChange<StateType>(this->getState(), S);
691   }
692 };
693 
694 /// Helper class for generic replication: function returned -> cs returned.
695 template <typename AAType, typename BaseType,
696           typename StateType = typename BaseType::StateType,
697           bool IntroduceCallBaseContext = false>
698 struct AACallSiteReturnedFromReturned : public BaseType {
699   AACallSiteReturnedFromReturned(const IRPosition &IRP, Attributor &A)
700       : BaseType(IRP, A) {}
701 
702   /// See AbstractAttribute::updateImpl(...).
703   ChangeStatus updateImpl(Attributor &A) override {
704     assert(this->getIRPosition().getPositionKind() ==
705                IRPosition::IRP_CALL_SITE_RETURNED &&
706            "Can only wrap function returned positions for call site returned "
707            "positions!");
708     auto &S = this->getState();
709 
710     const Function *AssociatedFunction =
711         this->getIRPosition().getAssociatedFunction();
712     if (!AssociatedFunction)
713       return S.indicatePessimisticFixpoint();
714 
715     CallBase &CBContext = cast<CallBase>(this->getAnchorValue());
716     if (IntroduceCallBaseContext)
717       LLVM_DEBUG(dbgs() << "[Attributor] Introducing call base context:"
718                         << CBContext << "\n");
719 
720     IRPosition FnPos = IRPosition::returned(
721         *AssociatedFunction, IntroduceCallBaseContext ? &CBContext : nullptr);
722     const AAType &AA = A.getAAFor<AAType>(*this, FnPos, DepClassTy::REQUIRED);
723     return clampStateAndIndicateChange(S, AA.getState());
724   }
725 };
726 
727 /// Helper function to accumulate uses.
728 template <class AAType, typename StateType = typename AAType::StateType>
729 static void followUsesInContext(AAType &AA, Attributor &A,
730                                 MustBeExecutedContextExplorer &Explorer,
731                                 const Instruction *CtxI,
732                                 SetVector<const Use *> &Uses,
733                                 StateType &State) {
734   auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI);
735   for (unsigned u = 0; u < Uses.size(); ++u) {
736     const Use *U = Uses[u];
737     if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
738       bool Found = Explorer.findInContextOf(UserI, EIt, EEnd);
739       if (Found && AA.followUseInMBEC(A, U, UserI, State))
740         for (const Use &Us : UserI->uses())
741           Uses.insert(&Us);
742     }
743   }
744 }
745 
746 /// Use the must-be-executed-context around \p I to add information into \p S.
747 /// The AAType class is required to have `followUseInMBEC` method with the
748 /// following signature and behaviour:
749 ///
750 /// bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I)
751 /// U - Underlying use.
752 /// I - The user of the \p U.
753 /// Returns true if the value should be tracked transitively.
754 ///
755 template <class AAType, typename StateType = typename AAType::StateType>
756 static void followUsesInMBEC(AAType &AA, Attributor &A, StateType &S,
757                              Instruction &CtxI) {
758 
759   // Container for (transitive) uses of the associated value.
760   SetVector<const Use *> Uses;
761   for (const Use &U : AA.getIRPosition().getAssociatedValue().uses())
762     Uses.insert(&U);
763 
764   MustBeExecutedContextExplorer &Explorer =
765       A.getInfoCache().getMustBeExecutedContextExplorer();
766 
767   followUsesInContext<AAType>(AA, A, Explorer, &CtxI, Uses, S);
768 
769   if (S.isAtFixpoint())
770     return;
771 
772   SmallVector<const BranchInst *, 4> BrInsts;
773   auto Pred = [&](const Instruction *I) {
774     if (const BranchInst *Br = dyn_cast<BranchInst>(I))
775       if (Br->isConditional())
776         BrInsts.push_back(Br);
777     return true;
778   };
779 
780   // Here, accumulate conditional branch instructions in the context. We
781   // explore the child paths and collect the known states. The disjunction of
782   // those states can be merged to its own state. Let ParentState_i be a state
783   // to indicate the known information for an i-th branch instruction in the
784   // context. ChildStates are created for its successors respectively.
785   //
786   // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1}
787   // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2}
788   //      ...
789   // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m}
790   //
791   // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m
792   //
793   // FIXME: Currently, recursive branches are not handled. For example, we
794   // can't deduce that ptr must be dereferenced in below function.
795   //
796   // void f(int a, int c, int *ptr) {
797   //    if(a)
798   //      if (b) {
799   //        *ptr = 0;
800   //      } else {
801   //        *ptr = 1;
802   //      }
803   //    else {
804   //      if (b) {
805   //        *ptr = 0;
806   //      } else {
807   //        *ptr = 1;
808   //      }
809   //    }
810   // }
811 
812   Explorer.checkForAllContext(&CtxI, Pred);
813   for (const BranchInst *Br : BrInsts) {
814     StateType ParentState;
815 
816     // The known state of the parent state is a conjunction of children's
817     // known states so it is initialized with a best state.
818     ParentState.indicateOptimisticFixpoint();
819 
820     for (const BasicBlock *BB : Br->successors()) {
821       StateType ChildState;
822 
823       size_t BeforeSize = Uses.size();
824       followUsesInContext(AA, A, Explorer, &BB->front(), Uses, ChildState);
825 
826       // Erase uses which only appear in the child.
827       for (auto It = Uses.begin() + BeforeSize; It != Uses.end();)
828         It = Uses.erase(It);
829 
830       ParentState &= ChildState;
831     }
832 
833     // Use only known state.
834     S += ParentState;
835   }
836 }
837 } // namespace
838 
839 /// ------------------------ PointerInfo ---------------------------------------
840 
841 namespace llvm {
842 namespace AA {
843 namespace PointerInfo {
844 
845 struct State;
846 
847 } // namespace PointerInfo
848 } // namespace AA
849 
850 /// Helper for AA::PointerInfo::Acccess DenseMap/Set usage.
851 template <>
852 struct DenseMapInfo<AAPointerInfo::Access> : DenseMapInfo<Instruction *> {
853   using Access = AAPointerInfo::Access;
854   static inline Access getEmptyKey();
855   static inline Access getTombstoneKey();
856   static unsigned getHashValue(const Access &A);
857   static bool isEqual(const Access &LHS, const Access &RHS);
858 };
859 
860 /// Helper that allows OffsetAndSize as a key in a DenseMap.
861 template <>
862 struct DenseMapInfo<AAPointerInfo ::OffsetAndSize>
863     : DenseMapInfo<std::pair<int64_t, int64_t>> {};
864 
865 /// Helper for AA::PointerInfo::Acccess DenseMap/Set usage ignoring everythign
866 /// but the instruction
867 struct AccessAsInstructionInfo : DenseMapInfo<Instruction *> {
868   using Base = DenseMapInfo<Instruction *>;
869   using Access = AAPointerInfo::Access;
870   static inline Access getEmptyKey();
871   static inline Access getTombstoneKey();
872   static unsigned getHashValue(const Access &A);
873   static bool isEqual(const Access &LHS, const Access &RHS);
874 };
875 
876 } // namespace llvm
877 
878 /// A type to track pointer/struct usage and accesses for AAPointerInfo.
879 struct AA::PointerInfo::State : public AbstractState {
880 
881   ~State() {
882     // We do not delete the Accesses objects but need to destroy them still.
883     for (auto &It : AccessBins)
884       It.second->~Accesses();
885   }
886 
887   /// Return the best possible representable state.
888   static State getBestState(const State &SIS) { return State(); }
889 
890   /// Return the worst possible representable state.
891   static State getWorstState(const State &SIS) {
892     State R;
893     R.indicatePessimisticFixpoint();
894     return R;
895   }
896 
897   State() = default;
898   State(State &&SIS) : AccessBins(std::move(SIS.AccessBins)) {
899     SIS.AccessBins.clear();
900   }
901 
902   const State &getAssumed() const { return *this; }
903 
904   /// See AbstractState::isValidState().
905   bool isValidState() const override { return BS.isValidState(); }
906 
907   /// See AbstractState::isAtFixpoint().
908   bool isAtFixpoint() const override { return BS.isAtFixpoint(); }
909 
910   /// See AbstractState::indicateOptimisticFixpoint().
911   ChangeStatus indicateOptimisticFixpoint() override {
912     BS.indicateOptimisticFixpoint();
913     return ChangeStatus::UNCHANGED;
914   }
915 
916   /// See AbstractState::indicatePessimisticFixpoint().
917   ChangeStatus indicatePessimisticFixpoint() override {
918     BS.indicatePessimisticFixpoint();
919     return ChangeStatus::CHANGED;
920   }
921 
922   State &operator=(const State &R) {
923     if (this == &R)
924       return *this;
925     BS = R.BS;
926     AccessBins = R.AccessBins;
927     return *this;
928   }
929 
930   State &operator=(State &&R) {
931     if (this == &R)
932       return *this;
933     std::swap(BS, R.BS);
934     std::swap(AccessBins, R.AccessBins);
935     return *this;
936   }
937 
938   bool operator==(const State &R) const {
939     if (BS != R.BS)
940       return false;
941     if (AccessBins.size() != R.AccessBins.size())
942       return false;
943     auto It = begin(), RIt = R.begin(), E = end();
944     while (It != E) {
945       if (It->getFirst() != RIt->getFirst())
946         return false;
947       auto &Accs = It->getSecond();
948       auto &RAccs = RIt->getSecond();
949       if (Accs->size() != RAccs->size())
950         return false;
951       for (const auto &ZipIt : llvm::zip(*Accs, *RAccs))
952         if (std::get<0>(ZipIt) != std::get<1>(ZipIt))
953           return false;
954       ++It;
955       ++RIt;
956     }
957     return true;
958   }
959   bool operator!=(const State &R) const { return !(*this == R); }
960 
961   /// We store accesses in a set with the instruction as key.
962   struct Accesses {
963     SmallVector<AAPointerInfo::Access, 4> Accesses;
964     DenseMap<const Instruction *, unsigned> Map;
965 
966     unsigned size() const { return Accesses.size(); }
967 
968     using vec_iterator = decltype(Accesses)::iterator;
969     vec_iterator begin() { return Accesses.begin(); }
970     vec_iterator end() { return Accesses.end(); }
971 
972     using iterator = decltype(Map)::const_iterator;
973     iterator find(AAPointerInfo::Access &Acc) {
974       return Map.find(Acc.getRemoteInst());
975     }
976     iterator find_end() { return Map.end(); }
977 
978     AAPointerInfo::Access &get(iterator &It) {
979       return Accesses[It->getSecond()];
980     }
981 
982     void insert(AAPointerInfo::Access &Acc) {
983       Map[Acc.getRemoteInst()] = Accesses.size();
984       Accesses.push_back(Acc);
985     }
986   };
987 
988   /// We store all accesses in bins denoted by their offset and size.
989   using AccessBinsTy = DenseMap<AAPointerInfo::OffsetAndSize, Accesses *>;
990 
991   AccessBinsTy::const_iterator begin() const { return AccessBins.begin(); }
992   AccessBinsTy::const_iterator end() const { return AccessBins.end(); }
993 
994 protected:
995   /// The bins with all the accesses for the associated pointer.
996   AccessBinsTy AccessBins;
997 
998   /// Add a new access to the state at offset \p Offset and with size \p Size.
999   /// The access is associated with \p I, writes \p Content (if anything), and
1000   /// is of kind \p Kind.
1001   /// \Returns CHANGED, if the state changed, UNCHANGED otherwise.
1002   ChangeStatus addAccess(Attributor &A, int64_t Offset, int64_t Size,
1003                          Instruction &I, Optional<Value *> Content,
1004                          AAPointerInfo::AccessKind Kind, Type *Ty,
1005                          Instruction *RemoteI = nullptr,
1006                          Accesses *BinPtr = nullptr) {
1007     AAPointerInfo::OffsetAndSize Key{Offset, Size};
1008     Accesses *&Bin = BinPtr ? BinPtr : AccessBins[Key];
1009     if (!Bin)
1010       Bin = new (A.Allocator) Accesses;
1011     AAPointerInfo::Access Acc(&I, RemoteI ? RemoteI : &I, Content, Kind, Ty);
1012     // Check if we have an access for this instruction in this bin, if not,
1013     // simply add it.
1014     auto It = Bin->find(Acc);
1015     if (It == Bin->find_end()) {
1016       Bin->insert(Acc);
1017       return ChangeStatus::CHANGED;
1018     }
1019     // If the existing access is the same as then new one, nothing changed.
1020     AAPointerInfo::Access &Current = Bin->get(It);
1021     AAPointerInfo::Access Before = Current;
1022     // The new one will be combined with the existing one.
1023     Current &= Acc;
1024     return Current == Before ? ChangeStatus::UNCHANGED : ChangeStatus::CHANGED;
1025   }
1026 
1027   /// See AAPointerInfo::forallInterferingAccesses.
1028   bool forallInterferingAccesses(
1029       AAPointerInfo::OffsetAndSize OAS,
1030       function_ref<bool(const AAPointerInfo::Access &, bool)> CB) const {
1031     if (!isValidState())
1032       return false;
1033 
1034     for (auto &It : AccessBins) {
1035       AAPointerInfo::OffsetAndSize ItOAS = It.getFirst();
1036       if (!OAS.mayOverlap(ItOAS))
1037         continue;
1038       bool IsExact = OAS == ItOAS && !OAS.offsetOrSizeAreUnknown();
1039       for (auto &Access : *It.getSecond())
1040         if (!CB(Access, IsExact))
1041           return false;
1042     }
1043     return true;
1044   }
1045 
1046   /// See AAPointerInfo::forallInterferingAccesses.
1047   bool forallInterferingAccesses(
1048       Instruction &I,
1049       function_ref<bool(const AAPointerInfo::Access &, bool)> CB) const {
1050     if (!isValidState())
1051       return false;
1052 
1053     // First find the offset and size of I.
1054     AAPointerInfo::OffsetAndSize OAS(-1, -1);
1055     for (auto &It : AccessBins) {
1056       for (auto &Access : *It.getSecond()) {
1057         if (Access.getRemoteInst() == &I) {
1058           OAS = It.getFirst();
1059           break;
1060         }
1061       }
1062       if (OAS.getSize() != -1)
1063         break;
1064     }
1065     // No access for I was found, we are done.
1066     if (OAS.getSize() == -1)
1067       return true;
1068 
1069     // Now that we have an offset and size, find all overlapping ones and use
1070     // the callback on the accesses.
1071     return forallInterferingAccesses(OAS, CB);
1072   }
1073 
1074 private:
1075   /// State to track fixpoint and validity.
1076   BooleanState BS;
1077 };
1078 
1079 namespace {
1080 struct AAPointerInfoImpl
1081     : public StateWrapper<AA::PointerInfo::State, AAPointerInfo> {
1082   using BaseTy = StateWrapper<AA::PointerInfo::State, AAPointerInfo>;
1083   AAPointerInfoImpl(const IRPosition &IRP, Attributor &A) : BaseTy(IRP) {}
1084 
1085   /// See AbstractAttribute::initialize(...).
1086   void initialize(Attributor &A) override { AAPointerInfo::initialize(A); }
1087 
1088   /// See AbstractAttribute::getAsStr().
1089   const std::string getAsStr() const override {
1090     return std::string("PointerInfo ") +
1091            (isValidState() ? (std::string("#") +
1092                               std::to_string(AccessBins.size()) + " bins")
1093                            : "<invalid>");
1094   }
1095 
1096   /// See AbstractAttribute::manifest(...).
1097   ChangeStatus manifest(Attributor &A) override {
1098     return AAPointerInfo::manifest(A);
1099   }
1100 
1101   bool forallInterferingAccesses(
1102       OffsetAndSize OAS,
1103       function_ref<bool(const AAPointerInfo::Access &, bool)> CB)
1104       const override {
1105     return State::forallInterferingAccesses(OAS, CB);
1106   }
1107   bool forallInterferingAccesses(
1108       Attributor &A, const AbstractAttribute &QueryingAA, Instruction &I,
1109       function_ref<bool(const Access &, bool)> UserCB) const override {
1110     SmallPtrSet<const Access *, 8> DominatingWrites;
1111     SmallVector<std::pair<const Access *, bool>, 8> InterferingAccesses;
1112 
1113     Function &Scope = *I.getFunction();
1114     const auto &NoSyncAA = A.getAAFor<AANoSync>(
1115         QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL);
1116     const auto *ExecDomainAA = A.lookupAAFor<AAExecutionDomain>(
1117         IRPosition::function(Scope), &QueryingAA, DepClassTy::OPTIONAL);
1118     const bool NoSync = NoSyncAA.isAssumedNoSync();
1119 
1120     // Helper to determine if we need to consider threading, which we cannot
1121     // right now. However, if the function is (assumed) nosync or the thread
1122     // executing all instructions is the main thread only we can ignore
1123     // threading.
1124     auto CanIgnoreThreading = [&](const Instruction &I) -> bool {
1125       if (NoSync)
1126         return true;
1127       if (ExecDomainAA && ExecDomainAA->isExecutedByInitialThreadOnly(I))
1128         return true;
1129       return false;
1130     };
1131 
1132     // Helper to determine if the access is executed by the same thread as the
1133     // load, for now it is sufficient to avoid any potential threading effects
1134     // as we cannot deal with them anyway.
1135     auto IsSameThreadAsLoad = [&](const Access &Acc) -> bool {
1136       return CanIgnoreThreading(*Acc.getLocalInst());
1137     };
1138 
1139     // TODO: Use inter-procedural reachability and dominance.
1140     const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
1141         QueryingAA, IRPosition::function(Scope), DepClassTy::OPTIONAL);
1142 
1143     const bool FindInterferingWrites = I.mayReadFromMemory();
1144     const bool FindInterferingReads = I.mayWriteToMemory();
1145     const bool UseDominanceReasoning = FindInterferingWrites;
1146     const bool CanUseCFGResoning = CanIgnoreThreading(I);
1147     InformationCache &InfoCache = A.getInfoCache();
1148     const DominatorTree *DT =
1149         NoRecurseAA.isKnownNoRecurse() && UseDominanceReasoning
1150             ? InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
1151                   Scope)
1152             : nullptr;
1153 
1154     enum GPUAddressSpace : unsigned {
1155       Generic = 0,
1156       Global = 1,
1157       Shared = 3,
1158       Constant = 4,
1159       Local = 5,
1160     };
1161 
1162     // Helper to check if a value has "kernel lifetime", that is it will not
1163     // outlive a GPU kernel. This is true for shared, constant, and local
1164     // globals on AMD and NVIDIA GPUs.
1165     auto HasKernelLifetime = [&](Value *V, Module &M) {
1166       Triple T(M.getTargetTriple());
1167       if (!(T.isAMDGPU() || T.isNVPTX()))
1168         return false;
1169       switch (V->getType()->getPointerAddressSpace()) {
1170       case GPUAddressSpace::Shared:
1171       case GPUAddressSpace::Constant:
1172       case GPUAddressSpace::Local:
1173         return true;
1174       default:
1175         return false;
1176       };
1177     };
1178 
1179     // The IsLiveInCalleeCB will be used by the AA::isPotentiallyReachable query
1180     // to determine if we should look at reachability from the callee. For
1181     // certain pointers we know the lifetime and we do not have to step into the
1182     // callee to determine reachability as the pointer would be dead in the
1183     // callee. See the conditional initialization below.
1184     std::function<bool(const Function &)> IsLiveInCalleeCB;
1185 
1186     if (auto *AI = dyn_cast<AllocaInst>(&getAssociatedValue())) {
1187       // If the alloca containing function is not recursive the alloca
1188       // must be dead in the callee.
1189       const Function *AIFn = AI->getFunction();
1190       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
1191           *this, IRPosition::function(*AIFn), DepClassTy::OPTIONAL);
1192       if (NoRecurseAA.isAssumedNoRecurse()) {
1193         IsLiveInCalleeCB = [AIFn](const Function &Fn) { return AIFn != &Fn; };
1194       }
1195     } else if (auto *GV = dyn_cast<GlobalValue>(&getAssociatedValue())) {
1196       // If the global has kernel lifetime we can stop if we reach a kernel
1197       // as it is "dead" in the (unknown) callees.
1198       if (HasKernelLifetime(GV, *GV->getParent()))
1199         IsLiveInCalleeCB = [](const Function &Fn) {
1200           return !Fn.hasFnAttribute("kernel");
1201         };
1202     }
1203 
1204     auto AccessCB = [&](const Access &Acc, bool Exact) {
1205       if ((!FindInterferingWrites || !Acc.isWrite()) &&
1206           (!FindInterferingReads || !Acc.isRead()))
1207         return true;
1208 
1209       // For now we only filter accesses based on CFG reasoning which does not
1210       // work yet if we have threading effects, or the access is complicated.
1211       if (CanUseCFGResoning) {
1212         if ((!Acc.isWrite() ||
1213              !AA::isPotentiallyReachable(A, *Acc.getLocalInst(), I, QueryingAA,
1214                                          IsLiveInCalleeCB)) &&
1215             (!Acc.isRead() ||
1216              !AA::isPotentiallyReachable(A, I, *Acc.getLocalInst(), QueryingAA,
1217                                          IsLiveInCalleeCB)))
1218           return true;
1219         if (DT && Exact && (Acc.getLocalInst()->getFunction() == &Scope) &&
1220             IsSameThreadAsLoad(Acc)) {
1221           if (DT->dominates(Acc.getLocalInst(), &I))
1222             DominatingWrites.insert(&Acc);
1223         }
1224       }
1225 
1226       InterferingAccesses.push_back({&Acc, Exact});
1227       return true;
1228     };
1229     if (!State::forallInterferingAccesses(I, AccessCB))
1230       return false;
1231 
1232     // If we cannot use CFG reasoning we only filter the non-write accesses
1233     // and are done here.
1234     if (!CanUseCFGResoning) {
1235       for (auto &It : InterferingAccesses)
1236         if (!UserCB(*It.first, It.second))
1237           return false;
1238       return true;
1239     }
1240 
1241     // Helper to determine if we can skip a specific write access. This is in
1242     // the worst case quadratic as we are looking for another write that will
1243     // hide the effect of this one.
1244     auto CanSkipAccess = [&](const Access &Acc, bool Exact) {
1245       if (!IsSameThreadAsLoad(Acc))
1246         return false;
1247       if (!DominatingWrites.count(&Acc))
1248         return false;
1249       for (const Access *DomAcc : DominatingWrites) {
1250         assert(Acc.getLocalInst()->getFunction() ==
1251                    DomAcc->getLocalInst()->getFunction() &&
1252                "Expected dominating writes to be in the same function!");
1253 
1254         if (DomAcc != &Acc &&
1255             DT->dominates(Acc.getLocalInst(), DomAcc->getLocalInst())) {
1256           return true;
1257         }
1258       }
1259       return false;
1260     };
1261 
1262     // Run the user callback on all accesses we cannot skip and return if that
1263     // succeeded for all or not.
1264     unsigned NumInterferingAccesses = InterferingAccesses.size();
1265     for (auto &It : InterferingAccesses) {
1266       if (!DT || NumInterferingAccesses > MaxInterferingAccesses ||
1267           !CanSkipAccess(*It.first, It.second)) {
1268         if (!UserCB(*It.first, It.second))
1269           return false;
1270       }
1271     }
1272     return true;
1273   }
1274 
1275   ChangeStatus translateAndAddCalleeState(Attributor &A,
1276                                           const AAPointerInfo &CalleeAA,
1277                                           int64_t CallArgOffset, CallBase &CB) {
1278     using namespace AA::PointerInfo;
1279     if (!CalleeAA.getState().isValidState() || !isValidState())
1280       return indicatePessimisticFixpoint();
1281 
1282     const auto &CalleeImplAA = static_cast<const AAPointerInfoImpl &>(CalleeAA);
1283     bool IsByval = CalleeImplAA.getAssociatedArgument()->hasByValAttr();
1284 
1285     // Combine the accesses bin by bin.
1286     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1287     for (auto &It : CalleeImplAA.getState()) {
1288       OffsetAndSize OAS = OffsetAndSize::getUnknown();
1289       if (CallArgOffset != OffsetAndSize::Unknown)
1290         OAS = OffsetAndSize(It.first.getOffset() + CallArgOffset,
1291                             It.first.getSize());
1292       Accesses *Bin = AccessBins[OAS];
1293       for (const AAPointerInfo::Access &RAcc : *It.second) {
1294         if (IsByval && !RAcc.isRead())
1295           continue;
1296         bool UsedAssumedInformation = false;
1297         Optional<Value *> Content = A.translateArgumentToCallSiteContent(
1298             RAcc.getContent(), CB, *this, UsedAssumedInformation);
1299         AccessKind AK =
1300             AccessKind(RAcc.getKind() & (IsByval ? AccessKind::AK_READ
1301                                                  : AccessKind::AK_READ_WRITE));
1302         Changed =
1303             Changed | addAccess(A, OAS.getOffset(), OAS.getSize(), CB, Content,
1304                                 AK, RAcc.getType(), RAcc.getRemoteInst(), Bin);
1305       }
1306     }
1307     return Changed;
1308   }
1309 
1310   /// Statistic tracking for all AAPointerInfo implementations.
1311   /// See AbstractAttribute::trackStatistics().
1312   void trackPointerInfoStatistics(const IRPosition &IRP) const {}
1313 };
1314 
1315 struct AAPointerInfoFloating : public AAPointerInfoImpl {
1316   using AccessKind = AAPointerInfo::AccessKind;
1317   AAPointerInfoFloating(const IRPosition &IRP, Attributor &A)
1318       : AAPointerInfoImpl(IRP, A) {}
1319 
1320   /// See AbstractAttribute::initialize(...).
1321   void initialize(Attributor &A) override { AAPointerInfoImpl::initialize(A); }
1322 
1323   /// Deal with an access and signal if it was handled successfully.
1324   bool handleAccess(Attributor &A, Instruction &I, Value &Ptr,
1325                     Optional<Value *> Content, AccessKind Kind, int64_t Offset,
1326                     ChangeStatus &Changed, Type *Ty,
1327                     int64_t Size = OffsetAndSize::Unknown) {
1328     using namespace AA::PointerInfo;
1329     // No need to find a size if one is given or the offset is unknown.
1330     if (Offset != OffsetAndSize::Unknown && Size == OffsetAndSize::Unknown &&
1331         Ty) {
1332       const DataLayout &DL = A.getDataLayout();
1333       TypeSize AccessSize = DL.getTypeStoreSize(Ty);
1334       if (!AccessSize.isScalable())
1335         Size = AccessSize.getFixedSize();
1336     }
1337     Changed = Changed | addAccess(A, Offset, Size, I, Content, Kind, Ty);
1338     return true;
1339   };
1340 
1341   /// Helper struct, will support ranges eventually.
1342   struct OffsetInfo {
1343     int64_t Offset = OffsetAndSize::Unknown;
1344 
1345     bool operator==(const OffsetInfo &OI) const { return Offset == OI.Offset; }
1346   };
1347 
1348   /// See AbstractAttribute::updateImpl(...).
1349   ChangeStatus updateImpl(Attributor &A) override {
1350     using namespace AA::PointerInfo;
1351     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1352     Value &AssociatedValue = getAssociatedValue();
1353 
1354     const DataLayout &DL = A.getDataLayout();
1355     DenseMap<Value *, OffsetInfo> OffsetInfoMap;
1356     OffsetInfoMap[&AssociatedValue] = OffsetInfo{0};
1357 
1358     auto HandlePassthroughUser = [&](Value *Usr, OffsetInfo PtrOI,
1359                                      bool &Follow) {
1360       OffsetInfo &UsrOI = OffsetInfoMap[Usr];
1361       UsrOI = PtrOI;
1362       Follow = true;
1363       return true;
1364     };
1365 
1366     const auto *TLI = getAnchorScope()
1367                           ? A.getInfoCache().getTargetLibraryInfoForFunction(
1368                                 *getAnchorScope())
1369                           : nullptr;
1370     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
1371       Value *CurPtr = U.get();
1372       User *Usr = U.getUser();
1373       LLVM_DEBUG(dbgs() << "[AAPointerInfo] Analyze " << *CurPtr << " in "
1374                         << *Usr << "\n");
1375       assert(OffsetInfoMap.count(CurPtr) &&
1376              "The current pointer offset should have been seeded!");
1377 
1378       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Usr)) {
1379         if (CE->isCast())
1380           return HandlePassthroughUser(Usr, OffsetInfoMap[CurPtr], Follow);
1381         if (CE->isCompare())
1382           return true;
1383         if (!isa<GEPOperator>(CE)) {
1384           LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled constant user " << *CE
1385                             << "\n");
1386           return false;
1387         }
1388       }
1389       if (auto *GEP = dyn_cast<GEPOperator>(Usr)) {
1390         // Note the order here, the Usr access might change the map, CurPtr is
1391         // already in it though.
1392         OffsetInfo &UsrOI = OffsetInfoMap[Usr];
1393         OffsetInfo &PtrOI = OffsetInfoMap[CurPtr];
1394         UsrOI = PtrOI;
1395 
1396         // TODO: Use range information.
1397         if (PtrOI.Offset == OffsetAndSize::Unknown ||
1398             !GEP->hasAllConstantIndices()) {
1399           UsrOI.Offset = OffsetAndSize::Unknown;
1400           Follow = true;
1401           return true;
1402         }
1403 
1404         SmallVector<Value *, 8> Indices;
1405         for (Use &Idx : GEP->indices()) {
1406           if (auto *CIdx = dyn_cast<ConstantInt>(Idx)) {
1407             Indices.push_back(CIdx);
1408             continue;
1409           }
1410 
1411           LLVM_DEBUG(dbgs() << "[AAPointerInfo] Non constant GEP index " << *GEP
1412                             << " : " << *Idx << "\n");
1413           return false;
1414         }
1415         UsrOI.Offset = PtrOI.Offset + DL.getIndexedOffsetInType(
1416                                           GEP->getSourceElementType(), Indices);
1417         Follow = true;
1418         return true;
1419       }
1420       if (isa<CastInst>(Usr) || isa<SelectInst>(Usr))
1421         return HandlePassthroughUser(Usr, OffsetInfoMap[CurPtr], Follow);
1422 
1423       // For PHIs we need to take care of the recurrence explicitly as the value
1424       // might change while we iterate through a loop. For now, we give up if
1425       // the PHI is not invariant.
1426       if (isa<PHINode>(Usr)) {
1427         // Note the order here, the Usr access might change the map, CurPtr is
1428         // already in it though.
1429         OffsetInfo &UsrOI = OffsetInfoMap[Usr];
1430         OffsetInfo &PtrOI = OffsetInfoMap[CurPtr];
1431         // Check if the PHI is invariant (so far).
1432         if (UsrOI == PtrOI)
1433           return true;
1434 
1435         // Check if the PHI operand has already an unknown offset as we can't
1436         // improve on that anymore.
1437         if (PtrOI.Offset == OffsetAndSize::Unknown) {
1438           UsrOI = PtrOI;
1439           Follow = true;
1440           return true;
1441         }
1442 
1443         // Check if the PHI operand is not dependent on the PHI itself.
1444         // TODO: This is not great as we look at the pointer type. However, it
1445         // is unclear where the Offset size comes from with typeless pointers.
1446         APInt Offset(
1447             DL.getIndexSizeInBits(CurPtr->getType()->getPointerAddressSpace()),
1448             0);
1449         if (&AssociatedValue == CurPtr->stripAndAccumulateConstantOffsets(
1450                                     DL, Offset, /* AllowNonInbounds */ true)) {
1451           if (Offset != PtrOI.Offset) {
1452             LLVM_DEBUG(dbgs()
1453                        << "[AAPointerInfo] PHI operand pointer offset mismatch "
1454                        << *CurPtr << " in " << *Usr << "\n");
1455             return false;
1456           }
1457           return HandlePassthroughUser(Usr, PtrOI, Follow);
1458         }
1459 
1460         // TODO: Approximate in case we know the direction of the recurrence.
1461         LLVM_DEBUG(dbgs() << "[AAPointerInfo] PHI operand is too complex "
1462                           << *CurPtr << " in " << *Usr << "\n");
1463         UsrOI = PtrOI;
1464         UsrOI.Offset = OffsetAndSize::Unknown;
1465         Follow = true;
1466         return true;
1467       }
1468 
1469       if (auto *LoadI = dyn_cast<LoadInst>(Usr))
1470         return handleAccess(A, *LoadI, *CurPtr, /* Content */ nullptr,
1471                             AccessKind::AK_READ, OffsetInfoMap[CurPtr].Offset,
1472                             Changed, LoadI->getType());
1473       if (auto *StoreI = dyn_cast<StoreInst>(Usr)) {
1474         if (StoreI->getValueOperand() == CurPtr) {
1475           LLVM_DEBUG(dbgs() << "[AAPointerInfo] Escaping use in store "
1476                             << *StoreI << "\n");
1477           return false;
1478         }
1479         bool UsedAssumedInformation = false;
1480         Optional<Value *> Content = A.getAssumedSimplified(
1481             *StoreI->getValueOperand(), *this, UsedAssumedInformation);
1482         return handleAccess(A, *StoreI, *CurPtr, Content, AccessKind::AK_WRITE,
1483                             OffsetInfoMap[CurPtr].Offset, Changed,
1484                             StoreI->getValueOperand()->getType());
1485       }
1486       if (auto *CB = dyn_cast<CallBase>(Usr)) {
1487         if (CB->isLifetimeStartOrEnd())
1488           return true;
1489         if (TLI && isFreeCall(CB, TLI))
1490           return true;
1491         if (CB->isArgOperand(&U)) {
1492           unsigned ArgNo = CB->getArgOperandNo(&U);
1493           const auto &CSArgPI = A.getAAFor<AAPointerInfo>(
1494               *this, IRPosition::callsite_argument(*CB, ArgNo),
1495               DepClassTy::REQUIRED);
1496           Changed = translateAndAddCalleeState(
1497                         A, CSArgPI, OffsetInfoMap[CurPtr].Offset, *CB) |
1498                     Changed;
1499           return true;
1500         }
1501         LLVM_DEBUG(dbgs() << "[AAPointerInfo] Call user not handled " << *CB
1502                           << "\n");
1503         // TODO: Allow some call uses
1504         return false;
1505       }
1506 
1507       LLVM_DEBUG(dbgs() << "[AAPointerInfo] User not handled " << *Usr << "\n");
1508       return false;
1509     };
1510     auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
1511       if (OffsetInfoMap.count(NewU))
1512         return OffsetInfoMap[NewU] == OffsetInfoMap[OldU];
1513       OffsetInfoMap[NewU] = OffsetInfoMap[OldU];
1514       return true;
1515     };
1516     if (!A.checkForAllUses(UsePred, *this, AssociatedValue,
1517                            /* CheckBBLivenessOnly */ true, DepClassTy::OPTIONAL,
1518                            /* IgnoreDroppableUses */ true, EquivalentUseCB))
1519       return indicatePessimisticFixpoint();
1520 
1521     LLVM_DEBUG({
1522       dbgs() << "Accesses by bin after update:\n";
1523       for (auto &It : AccessBins) {
1524         dbgs() << "[" << It.first.getOffset() << "-"
1525                << It.first.getOffset() + It.first.getSize()
1526                << "] : " << It.getSecond()->size() << "\n";
1527         for (auto &Acc : *It.getSecond()) {
1528           dbgs() << "     - " << Acc.getKind() << " - " << *Acc.getLocalInst()
1529                  << "\n";
1530           if (Acc.getLocalInst() != Acc.getRemoteInst())
1531             dbgs() << "     -->                         "
1532                    << *Acc.getRemoteInst() << "\n";
1533           if (!Acc.isWrittenValueYetUndetermined()) {
1534             if (Acc.getWrittenValue())
1535               dbgs() << "       - c: " << *Acc.getWrittenValue() << "\n";
1536             else
1537               dbgs() << "       - c: <unknown>\n";
1538           }
1539         }
1540       }
1541     });
1542 
1543     return Changed;
1544   }
1545 
1546   /// See AbstractAttribute::trackStatistics()
1547   void trackStatistics() const override {
1548     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1549   }
1550 };
1551 
1552 struct AAPointerInfoReturned final : AAPointerInfoImpl {
1553   AAPointerInfoReturned(const IRPosition &IRP, Attributor &A)
1554       : AAPointerInfoImpl(IRP, A) {}
1555 
1556   /// See AbstractAttribute::updateImpl(...).
1557   ChangeStatus updateImpl(Attributor &A) override {
1558     return indicatePessimisticFixpoint();
1559   }
1560 
1561   /// See AbstractAttribute::trackStatistics()
1562   void trackStatistics() const override {
1563     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1564   }
1565 };
1566 
1567 struct AAPointerInfoArgument final : AAPointerInfoFloating {
1568   AAPointerInfoArgument(const IRPosition &IRP, Attributor &A)
1569       : AAPointerInfoFloating(IRP, A) {}
1570 
1571   /// See AbstractAttribute::initialize(...).
1572   void initialize(Attributor &A) override {
1573     AAPointerInfoFloating::initialize(A);
1574     if (getAnchorScope()->isDeclaration())
1575       indicatePessimisticFixpoint();
1576   }
1577 
1578   /// See AbstractAttribute::trackStatistics()
1579   void trackStatistics() const override {
1580     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1581   }
1582 };
1583 
1584 struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
1585   AAPointerInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
1586       : AAPointerInfoFloating(IRP, A) {}
1587 
1588   /// See AbstractAttribute::updateImpl(...).
1589   ChangeStatus updateImpl(Attributor &A) override {
1590     using namespace AA::PointerInfo;
1591     // We handle memory intrinsics explicitly, at least the first (=
1592     // destination) and second (=source) arguments as we know how they are
1593     // accessed.
1594     if (auto *MI = dyn_cast_or_null<MemIntrinsic>(getCtxI())) {
1595       ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1596       int64_t LengthVal = OffsetAndSize::Unknown;
1597       if (Length)
1598         LengthVal = Length->getSExtValue();
1599       Value &Ptr = getAssociatedValue();
1600       unsigned ArgNo = getIRPosition().getCallSiteArgNo();
1601       ChangeStatus Changed = ChangeStatus::UNCHANGED;
1602       if (ArgNo == 0) {
1603         handleAccess(A, *MI, Ptr, nullptr, AccessKind::AK_WRITE, 0, Changed,
1604                      nullptr, LengthVal);
1605       } else if (ArgNo == 1) {
1606         handleAccess(A, *MI, Ptr, nullptr, AccessKind::AK_READ, 0, Changed,
1607                      nullptr, LengthVal);
1608       } else {
1609         LLVM_DEBUG(dbgs() << "[AAPointerInfo] Unhandled memory intrinsic "
1610                           << *MI << "\n");
1611         return indicatePessimisticFixpoint();
1612       }
1613       return Changed;
1614     }
1615 
1616     // TODO: Once we have call site specific value information we can provide
1617     //       call site specific liveness information and then it makes
1618     //       sense to specialize attributes for call sites arguments instead of
1619     //       redirecting requests to the callee argument.
1620     Argument *Arg = getAssociatedArgument();
1621     if (!Arg)
1622       return indicatePessimisticFixpoint();
1623     const IRPosition &ArgPos = IRPosition::argument(*Arg);
1624     auto &ArgAA =
1625         A.getAAFor<AAPointerInfo>(*this, ArgPos, DepClassTy::REQUIRED);
1626     return translateAndAddCalleeState(A, ArgAA, 0, *cast<CallBase>(getCtxI()));
1627   }
1628 
1629   /// See AbstractAttribute::trackStatistics()
1630   void trackStatistics() const override {
1631     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1632   }
1633 };
1634 
1635 struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating {
1636   AAPointerInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
1637       : AAPointerInfoFloating(IRP, A) {}
1638 
1639   /// See AbstractAttribute::trackStatistics()
1640   void trackStatistics() const override {
1641     AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1642   }
1643 };
1644 } // namespace
1645 
1646 /// -----------------------NoUnwind Function Attribute--------------------------
1647 
1648 namespace {
1649 struct AANoUnwindImpl : AANoUnwind {
1650   AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {}
1651 
1652   const std::string getAsStr() const override {
1653     return getAssumed() ? "nounwind" : "may-unwind";
1654   }
1655 
1656   /// See AbstractAttribute::updateImpl(...).
1657   ChangeStatus updateImpl(Attributor &A) override {
1658     auto Opcodes = {
1659         (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
1660         (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
1661         (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
1662 
1663     auto CheckForNoUnwind = [&](Instruction &I) {
1664       if (!I.mayThrow())
1665         return true;
1666 
1667       if (const auto *CB = dyn_cast<CallBase>(&I)) {
1668         const auto &NoUnwindAA = A.getAAFor<AANoUnwind>(
1669             *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED);
1670         return NoUnwindAA.isAssumedNoUnwind();
1671       }
1672       return false;
1673     };
1674 
1675     bool UsedAssumedInformation = false;
1676     if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes,
1677                                    UsedAssumedInformation))
1678       return indicatePessimisticFixpoint();
1679 
1680     return ChangeStatus::UNCHANGED;
1681   }
1682 };
1683 
1684 struct AANoUnwindFunction final : public AANoUnwindImpl {
1685   AANoUnwindFunction(const IRPosition &IRP, Attributor &A)
1686       : AANoUnwindImpl(IRP, A) {}
1687 
1688   /// See AbstractAttribute::trackStatistics()
1689   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) }
1690 };
1691 
1692 /// NoUnwind attribute deduction for a call sites.
1693 struct AANoUnwindCallSite final : AANoUnwindImpl {
1694   AANoUnwindCallSite(const IRPosition &IRP, Attributor &A)
1695       : AANoUnwindImpl(IRP, A) {}
1696 
1697   /// See AbstractAttribute::initialize(...).
1698   void initialize(Attributor &A) override {
1699     AANoUnwindImpl::initialize(A);
1700     Function *F = getAssociatedFunction();
1701     if (!F || F->isDeclaration())
1702       indicatePessimisticFixpoint();
1703   }
1704 
1705   /// See AbstractAttribute::updateImpl(...).
1706   ChangeStatus updateImpl(Attributor &A) override {
1707     // TODO: Once we have call site specific value information we can provide
1708     //       call site specific liveness information and then it makes
1709     //       sense to specialize attributes for call sites arguments instead of
1710     //       redirecting requests to the callee argument.
1711     Function *F = getAssociatedFunction();
1712     const IRPosition &FnPos = IRPosition::function(*F);
1713     auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::REQUIRED);
1714     return clampStateAndIndicateChange(getState(), FnAA.getState());
1715   }
1716 
1717   /// See AbstractAttribute::trackStatistics()
1718   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); }
1719 };
1720 } // namespace
1721 
1722 /// --------------------- Function Return Values -------------------------------
1723 
1724 namespace {
1725 /// "Attribute" that collects all potential returned values and the return
1726 /// instructions that they arise from.
1727 ///
1728 /// If there is a unique returned value R, the manifest method will:
1729 ///   - mark R with the "returned" attribute, if R is an argument.
1730 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState {
1731 
1732   /// Mapping of values potentially returned by the associated function to the
1733   /// return instructions that might return them.
1734   MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues;
1735 
1736   /// State flags
1737   ///
1738   ///{
1739   bool IsFixed = false;
1740   bool IsValidState = true;
1741   ///}
1742 
1743 public:
1744   AAReturnedValuesImpl(const IRPosition &IRP, Attributor &A)
1745       : AAReturnedValues(IRP, A) {}
1746 
1747   /// See AbstractAttribute::initialize(...).
1748   void initialize(Attributor &A) override {
1749     // Reset the state.
1750     IsFixed = false;
1751     IsValidState = true;
1752     ReturnedValues.clear();
1753 
1754     Function *F = getAssociatedFunction();
1755     if (!F || F->isDeclaration()) {
1756       indicatePessimisticFixpoint();
1757       return;
1758     }
1759     assert(!F->getReturnType()->isVoidTy() &&
1760            "Did not expect a void return type!");
1761 
1762     // The map from instruction opcodes to those instructions in the function.
1763     auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F);
1764 
1765     // Look through all arguments, if one is marked as returned we are done.
1766     for (Argument &Arg : F->args()) {
1767       if (Arg.hasReturnedAttr()) {
1768         auto &ReturnInstSet = ReturnedValues[&Arg];
1769         if (auto *Insts = OpcodeInstMap.lookup(Instruction::Ret))
1770           for (Instruction *RI : *Insts)
1771             ReturnInstSet.insert(cast<ReturnInst>(RI));
1772 
1773         indicateOptimisticFixpoint();
1774         return;
1775       }
1776     }
1777 
1778     if (!A.isFunctionIPOAmendable(*F))
1779       indicatePessimisticFixpoint();
1780   }
1781 
1782   /// See AbstractAttribute::manifest(...).
1783   ChangeStatus manifest(Attributor &A) override;
1784 
1785   /// See AbstractAttribute::getState(...).
1786   AbstractState &getState() override { return *this; }
1787 
1788   /// See AbstractAttribute::getState(...).
1789   const AbstractState &getState() const override { return *this; }
1790 
1791   /// See AbstractAttribute::updateImpl(Attributor &A).
1792   ChangeStatus updateImpl(Attributor &A) override;
1793 
1794   llvm::iterator_range<iterator> returned_values() override {
1795     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
1796   }
1797 
1798   llvm::iterator_range<const_iterator> returned_values() const override {
1799     return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end());
1800   }
1801 
1802   /// Return the number of potential return values, -1 if unknown.
1803   size_t getNumReturnValues() const override {
1804     return isValidState() ? ReturnedValues.size() : -1;
1805   }
1806 
1807   /// Return an assumed unique return value if a single candidate is found. If
1808   /// there cannot be one, return a nullptr. If it is not clear yet, return the
1809   /// Optional::NoneType.
1810   Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const;
1811 
1812   /// See AbstractState::checkForAllReturnedValues(...).
1813   bool checkForAllReturnedValuesAndReturnInsts(
1814       function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
1815       const override;
1816 
1817   /// Pretty print the attribute similar to the IR representation.
1818   const std::string getAsStr() const override;
1819 
1820   /// See AbstractState::isAtFixpoint().
1821   bool isAtFixpoint() const override { return IsFixed; }
1822 
1823   /// See AbstractState::isValidState().
1824   bool isValidState() const override { return IsValidState; }
1825 
1826   /// See AbstractState::indicateOptimisticFixpoint(...).
1827   ChangeStatus indicateOptimisticFixpoint() override {
1828     IsFixed = true;
1829     return ChangeStatus::UNCHANGED;
1830   }
1831 
1832   ChangeStatus indicatePessimisticFixpoint() override {
1833     IsFixed = true;
1834     IsValidState = false;
1835     return ChangeStatus::CHANGED;
1836   }
1837 };
1838 
1839 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
1840   ChangeStatus Changed = ChangeStatus::UNCHANGED;
1841 
1842   // Bookkeeping.
1843   assert(isValidState());
1844   STATS_DECLTRACK(KnownReturnValues, FunctionReturn,
1845                   "Number of function with known return values");
1846 
1847   // Check if we have an assumed unique return value that we could manifest.
1848   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A);
1849 
1850   if (!UniqueRV.hasValue() || !UniqueRV.getValue())
1851     return Changed;
1852 
1853   // Bookkeeping.
1854   STATS_DECLTRACK(UniqueReturnValue, FunctionReturn,
1855                   "Number of function with unique return");
1856   // If the assumed unique return value is an argument, annotate it.
1857   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
1858     if (UniqueRVArg->getType()->canLosslesslyBitCastTo(
1859             getAssociatedFunction()->getReturnType())) {
1860       getIRPosition() = IRPosition::argument(*UniqueRVArg);
1861       Changed = IRAttribute::manifest(A);
1862     }
1863   }
1864   return Changed;
1865 }
1866 
1867 const std::string AAReturnedValuesImpl::getAsStr() const {
1868   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
1869          (isValidState() ? std::to_string(getNumReturnValues()) : "?") + ")";
1870 }
1871 
1872 Optional<Value *>
1873 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const {
1874   // If checkForAllReturnedValues provides a unique value, ignoring potential
1875   // undef values that can also be present, it is assumed to be the actual
1876   // return value and forwarded to the caller of this method. If there are
1877   // multiple, a nullptr is returned indicating there cannot be a unique
1878   // returned value.
1879   Optional<Value *> UniqueRV;
1880   Type *Ty = getAssociatedFunction()->getReturnType();
1881 
1882   auto Pred = [&](Value &RV) -> bool {
1883     UniqueRV = AA::combineOptionalValuesInAAValueLatice(UniqueRV, &RV, Ty);
1884     return UniqueRV != Optional<Value *>(nullptr);
1885   };
1886 
1887   if (!A.checkForAllReturnedValues(Pred, *this))
1888     UniqueRV = nullptr;
1889 
1890   return UniqueRV;
1891 }
1892 
1893 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
1894     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred)
1895     const {
1896   if (!isValidState())
1897     return false;
1898 
1899   // Check all returned values but ignore call sites as long as we have not
1900   // encountered an overdefined one during an update.
1901   for (auto &It : ReturnedValues) {
1902     Value *RV = It.first;
1903     if (!Pred(*RV, It.second))
1904       return false;
1905   }
1906 
1907   return true;
1908 }
1909 
1910 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
1911   ChangeStatus Changed = ChangeStatus::UNCHANGED;
1912 
1913   auto ReturnValueCB = [&](Value &V, const Instruction *CtxI, ReturnInst &Ret,
1914                            bool) -> bool {
1915     assert(AA::isValidInScope(V, Ret.getFunction()) &&
1916            "Assumed returned value should be valid in function scope!");
1917     if (ReturnedValues[&V].insert(&Ret))
1918       Changed = ChangeStatus::CHANGED;
1919     return true;
1920   };
1921 
1922   bool UsedAssumedInformation = false;
1923   auto ReturnInstCB = [&](Instruction &I) {
1924     ReturnInst &Ret = cast<ReturnInst>(I);
1925     return genericValueTraversal<ReturnInst>(
1926         A, IRPosition::value(*Ret.getReturnValue()), *this, Ret, ReturnValueCB,
1927         &I, UsedAssumedInformation, /* UseValueSimplify */ true,
1928         /* MaxValues */ 16,
1929         /* StripCB */ nullptr, AA::Intraprocedural);
1930   };
1931 
1932   // Discover returned values from all live returned instructions in the
1933   // associated function.
1934   if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret},
1935                                  UsedAssumedInformation))
1936     return indicatePessimisticFixpoint();
1937   return Changed;
1938 }
1939 
1940 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl {
1941   AAReturnedValuesFunction(const IRPosition &IRP, Attributor &A)
1942       : AAReturnedValuesImpl(IRP, A) {}
1943 
1944   /// See AbstractAttribute::trackStatistics()
1945   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) }
1946 };
1947 
1948 /// Returned values information for a call sites.
1949 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl {
1950   AAReturnedValuesCallSite(const IRPosition &IRP, Attributor &A)
1951       : AAReturnedValuesImpl(IRP, A) {}
1952 
1953   /// See AbstractAttribute::initialize(...).
1954   void initialize(Attributor &A) override {
1955     // TODO: Once we have call site specific value information we can provide
1956     //       call site specific liveness information and then it makes
1957     //       sense to specialize attributes for call sites instead of
1958     //       redirecting requests to the callee.
1959     llvm_unreachable("Abstract attributes for returned values are not "
1960                      "supported for call sites yet!");
1961   }
1962 
1963   /// See AbstractAttribute::updateImpl(...).
1964   ChangeStatus updateImpl(Attributor &A) override {
1965     return indicatePessimisticFixpoint();
1966   }
1967 
1968   /// See AbstractAttribute::trackStatistics()
1969   void trackStatistics() const override {}
1970 };
1971 } // namespace
1972 
1973 /// ------------------------ NoSync Function Attribute -------------------------
1974 
1975 bool AANoSync::isNonRelaxedAtomic(const Instruction *I) {
1976   if (!I->isAtomic())
1977     return false;
1978 
1979   if (auto *FI = dyn_cast<FenceInst>(I))
1980     // All legal orderings for fence are stronger than monotonic.
1981     return FI->getSyncScopeID() != SyncScope::SingleThread;
1982   if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) {
1983     // Unordered is not a legal ordering for cmpxchg.
1984     return (AI->getSuccessOrdering() != AtomicOrdering::Monotonic ||
1985             AI->getFailureOrdering() != AtomicOrdering::Monotonic);
1986   }
1987 
1988   AtomicOrdering Ordering;
1989   switch (I->getOpcode()) {
1990   case Instruction::AtomicRMW:
1991     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
1992     break;
1993   case Instruction::Store:
1994     Ordering = cast<StoreInst>(I)->getOrdering();
1995     break;
1996   case Instruction::Load:
1997     Ordering = cast<LoadInst>(I)->getOrdering();
1998     break;
1999   default:
2000     llvm_unreachable(
2001         "New atomic operations need to be known in the attributor.");
2002   }
2003 
2004   return (Ordering != AtomicOrdering::Unordered &&
2005           Ordering != AtomicOrdering::Monotonic);
2006 }
2007 
2008 /// Return true if this intrinsic is nosync.  This is only used for intrinsics
2009 /// which would be nosync except that they have a volatile flag.  All other
2010 /// intrinsics are simply annotated with the nosync attribute in Intrinsics.td.
2011 bool AANoSync::isNoSyncIntrinsic(const Instruction *I) {
2012   if (auto *MI = dyn_cast<MemIntrinsic>(I))
2013     return !MI->isVolatile();
2014   return false;
2015 }
2016 
2017 namespace {
2018 struct AANoSyncImpl : AANoSync {
2019   AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {}
2020 
2021   const std::string getAsStr() const override {
2022     return getAssumed() ? "nosync" : "may-sync";
2023   }
2024 
2025   /// See AbstractAttribute::updateImpl(...).
2026   ChangeStatus updateImpl(Attributor &A) override;
2027 };
2028 
2029 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) {
2030 
2031   auto CheckRWInstForNoSync = [&](Instruction &I) {
2032     return AA::isNoSyncInst(A, I, *this);
2033   };
2034 
2035   auto CheckForNoSync = [&](Instruction &I) {
2036     // At this point we handled all read/write effects and they are all
2037     // nosync, so they can be skipped.
2038     if (I.mayReadOrWriteMemory())
2039       return true;
2040 
2041     // non-convergent and readnone imply nosync.
2042     return !cast<CallBase>(I).isConvergent();
2043   };
2044 
2045   bool UsedAssumedInformation = false;
2046   if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this,
2047                                           UsedAssumedInformation) ||
2048       !A.checkForAllCallLikeInstructions(CheckForNoSync, *this,
2049                                          UsedAssumedInformation))
2050     return indicatePessimisticFixpoint();
2051 
2052   return ChangeStatus::UNCHANGED;
2053 }
2054 
2055 struct AANoSyncFunction final : public AANoSyncImpl {
2056   AANoSyncFunction(const IRPosition &IRP, Attributor &A)
2057       : AANoSyncImpl(IRP, A) {}
2058 
2059   /// See AbstractAttribute::trackStatistics()
2060   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) }
2061 };
2062 
2063 /// NoSync attribute deduction for a call sites.
2064 struct AANoSyncCallSite final : AANoSyncImpl {
2065   AANoSyncCallSite(const IRPosition &IRP, Attributor &A)
2066       : AANoSyncImpl(IRP, A) {}
2067 
2068   /// See AbstractAttribute::initialize(...).
2069   void initialize(Attributor &A) override {
2070     AANoSyncImpl::initialize(A);
2071     Function *F = getAssociatedFunction();
2072     if (!F || F->isDeclaration())
2073       indicatePessimisticFixpoint();
2074   }
2075 
2076   /// See AbstractAttribute::updateImpl(...).
2077   ChangeStatus updateImpl(Attributor &A) override {
2078     // TODO: Once we have call site specific value information we can provide
2079     //       call site specific liveness information and then it makes
2080     //       sense to specialize attributes for call sites arguments instead of
2081     //       redirecting requests to the callee argument.
2082     Function *F = getAssociatedFunction();
2083     const IRPosition &FnPos = IRPosition::function(*F);
2084     auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos, DepClassTy::REQUIRED);
2085     return clampStateAndIndicateChange(getState(), FnAA.getState());
2086   }
2087 
2088   /// See AbstractAttribute::trackStatistics()
2089   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); }
2090 };
2091 } // namespace
2092 
2093 /// ------------------------ No-Free Attributes ----------------------------
2094 
2095 namespace {
2096 struct AANoFreeImpl : public AANoFree {
2097   AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {}
2098 
2099   /// See AbstractAttribute::updateImpl(...).
2100   ChangeStatus updateImpl(Attributor &A) override {
2101     auto CheckForNoFree = [&](Instruction &I) {
2102       const auto &CB = cast<CallBase>(I);
2103       if (CB.hasFnAttr(Attribute::NoFree))
2104         return true;
2105 
2106       const auto &NoFreeAA = A.getAAFor<AANoFree>(
2107           *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
2108       return NoFreeAA.isAssumedNoFree();
2109     };
2110 
2111     bool UsedAssumedInformation = false;
2112     if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this,
2113                                            UsedAssumedInformation))
2114       return indicatePessimisticFixpoint();
2115     return ChangeStatus::UNCHANGED;
2116   }
2117 
2118   /// See AbstractAttribute::getAsStr().
2119   const std::string getAsStr() const override {
2120     return getAssumed() ? "nofree" : "may-free";
2121   }
2122 };
2123 
2124 struct AANoFreeFunction final : public AANoFreeImpl {
2125   AANoFreeFunction(const IRPosition &IRP, Attributor &A)
2126       : AANoFreeImpl(IRP, A) {}
2127 
2128   /// See AbstractAttribute::trackStatistics()
2129   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) }
2130 };
2131 
2132 /// NoFree attribute deduction for a call sites.
2133 struct AANoFreeCallSite final : AANoFreeImpl {
2134   AANoFreeCallSite(const IRPosition &IRP, Attributor &A)
2135       : AANoFreeImpl(IRP, A) {}
2136 
2137   /// See AbstractAttribute::initialize(...).
2138   void initialize(Attributor &A) override {
2139     AANoFreeImpl::initialize(A);
2140     Function *F = getAssociatedFunction();
2141     if (!F || F->isDeclaration())
2142       indicatePessimisticFixpoint();
2143   }
2144 
2145   /// See AbstractAttribute::updateImpl(...).
2146   ChangeStatus updateImpl(Attributor &A) override {
2147     // TODO: Once we have call site specific value information we can provide
2148     //       call site specific liveness information and then it makes
2149     //       sense to specialize attributes for call sites arguments instead of
2150     //       redirecting requests to the callee argument.
2151     Function *F = getAssociatedFunction();
2152     const IRPosition &FnPos = IRPosition::function(*F);
2153     auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos, DepClassTy::REQUIRED);
2154     return clampStateAndIndicateChange(getState(), FnAA.getState());
2155   }
2156 
2157   /// See AbstractAttribute::trackStatistics()
2158   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); }
2159 };
2160 
2161 /// NoFree attribute for floating values.
2162 struct AANoFreeFloating : AANoFreeImpl {
2163   AANoFreeFloating(const IRPosition &IRP, Attributor &A)
2164       : AANoFreeImpl(IRP, A) {}
2165 
2166   /// See AbstractAttribute::trackStatistics()
2167   void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)}
2168 
2169   /// See Abstract Attribute::updateImpl(...).
2170   ChangeStatus updateImpl(Attributor &A) override {
2171     const IRPosition &IRP = getIRPosition();
2172 
2173     const auto &NoFreeAA = A.getAAFor<AANoFree>(
2174         *this, IRPosition::function_scope(IRP), DepClassTy::OPTIONAL);
2175     if (NoFreeAA.isAssumedNoFree())
2176       return ChangeStatus::UNCHANGED;
2177 
2178     Value &AssociatedValue = getIRPosition().getAssociatedValue();
2179     auto Pred = [&](const Use &U, bool &Follow) -> bool {
2180       Instruction *UserI = cast<Instruction>(U.getUser());
2181       if (auto *CB = dyn_cast<CallBase>(UserI)) {
2182         if (CB->isBundleOperand(&U))
2183           return false;
2184         if (!CB->isArgOperand(&U))
2185           return true;
2186         unsigned ArgNo = CB->getArgOperandNo(&U);
2187 
2188         const auto &NoFreeArg = A.getAAFor<AANoFree>(
2189             *this, IRPosition::callsite_argument(*CB, ArgNo),
2190             DepClassTy::REQUIRED);
2191         return NoFreeArg.isAssumedNoFree();
2192       }
2193 
2194       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
2195           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
2196         Follow = true;
2197         return true;
2198       }
2199       if (isa<StoreInst>(UserI) || isa<LoadInst>(UserI) ||
2200           isa<ReturnInst>(UserI))
2201         return true;
2202 
2203       // Unknown user.
2204       return false;
2205     };
2206     if (!A.checkForAllUses(Pred, *this, AssociatedValue))
2207       return indicatePessimisticFixpoint();
2208 
2209     return ChangeStatus::UNCHANGED;
2210   }
2211 };
2212 
2213 /// NoFree attribute for a call site argument.
2214 struct AANoFreeArgument final : AANoFreeFloating {
2215   AANoFreeArgument(const IRPosition &IRP, Attributor &A)
2216       : AANoFreeFloating(IRP, A) {}
2217 
2218   /// See AbstractAttribute::trackStatistics()
2219   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) }
2220 };
2221 
2222 /// NoFree attribute for call site arguments.
2223 struct AANoFreeCallSiteArgument final : AANoFreeFloating {
2224   AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A)
2225       : AANoFreeFloating(IRP, A) {}
2226 
2227   /// See AbstractAttribute::updateImpl(...).
2228   ChangeStatus updateImpl(Attributor &A) override {
2229     // TODO: Once we have call site specific value information we can provide
2230     //       call site specific liveness information and then it makes
2231     //       sense to specialize attributes for call sites arguments instead of
2232     //       redirecting requests to the callee argument.
2233     Argument *Arg = getAssociatedArgument();
2234     if (!Arg)
2235       return indicatePessimisticFixpoint();
2236     const IRPosition &ArgPos = IRPosition::argument(*Arg);
2237     auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos, DepClassTy::REQUIRED);
2238     return clampStateAndIndicateChange(getState(), ArgAA.getState());
2239   }
2240 
2241   /// See AbstractAttribute::trackStatistics()
2242   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)};
2243 };
2244 
2245 /// NoFree attribute for function return value.
2246 struct AANoFreeReturned final : AANoFreeFloating {
2247   AANoFreeReturned(const IRPosition &IRP, Attributor &A)
2248       : AANoFreeFloating(IRP, A) {
2249     llvm_unreachable("NoFree is not applicable to function returns!");
2250   }
2251 
2252   /// See AbstractAttribute::initialize(...).
2253   void initialize(Attributor &A) override {
2254     llvm_unreachable("NoFree is not applicable to function returns!");
2255   }
2256 
2257   /// See AbstractAttribute::updateImpl(...).
2258   ChangeStatus updateImpl(Attributor &A) override {
2259     llvm_unreachable("NoFree is not applicable to function returns!");
2260   }
2261 
2262   /// See AbstractAttribute::trackStatistics()
2263   void trackStatistics() const override {}
2264 };
2265 
2266 /// NoFree attribute deduction for a call site return value.
2267 struct AANoFreeCallSiteReturned final : AANoFreeFloating {
2268   AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A)
2269       : AANoFreeFloating(IRP, A) {}
2270 
2271   ChangeStatus manifest(Attributor &A) override {
2272     return ChangeStatus::UNCHANGED;
2273   }
2274   /// See AbstractAttribute::trackStatistics()
2275   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) }
2276 };
2277 } // namespace
2278 
2279 /// ------------------------ NonNull Argument Attribute ------------------------
2280 namespace {
2281 static int64_t getKnownNonNullAndDerefBytesForUse(
2282     Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue,
2283     const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) {
2284   TrackUse = false;
2285 
2286   const Value *UseV = U->get();
2287   if (!UseV->getType()->isPointerTy())
2288     return 0;
2289 
2290   // We need to follow common pointer manipulation uses to the accesses they
2291   // feed into. We can try to be smart to avoid looking through things we do not
2292   // like for now, e.g., non-inbounds GEPs.
2293   if (isa<CastInst>(I)) {
2294     TrackUse = true;
2295     return 0;
2296   }
2297 
2298   if (isa<GetElementPtrInst>(I)) {
2299     TrackUse = true;
2300     return 0;
2301   }
2302 
2303   Type *PtrTy = UseV->getType();
2304   const Function *F = I->getFunction();
2305   bool NullPointerIsDefined =
2306       F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true;
2307   const DataLayout &DL = A.getInfoCache().getDL();
2308   if (const auto *CB = dyn_cast<CallBase>(I)) {
2309     if (CB->isBundleOperand(U)) {
2310       if (RetainedKnowledge RK = getKnowledgeFromUse(
2311               U, {Attribute::NonNull, Attribute::Dereferenceable})) {
2312         IsNonNull |=
2313             (RK.AttrKind == Attribute::NonNull || !NullPointerIsDefined);
2314         return RK.ArgValue;
2315       }
2316       return 0;
2317     }
2318 
2319     if (CB->isCallee(U)) {
2320       IsNonNull |= !NullPointerIsDefined;
2321       return 0;
2322     }
2323 
2324     unsigned ArgNo = CB->getArgOperandNo(U);
2325     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
2326     // As long as we only use known information there is no need to track
2327     // dependences here.
2328     auto &DerefAA =
2329         A.getAAFor<AADereferenceable>(QueryingAA, IRP, DepClassTy::NONE);
2330     IsNonNull |= DerefAA.isKnownNonNull();
2331     return DerefAA.getKnownDereferenceableBytes();
2332   }
2333 
2334   Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
2335   if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile())
2336     return 0;
2337 
2338   int64_t Offset;
2339   const Value *Base =
2340       getMinimalBaseOfPointer(A, QueryingAA, Loc->Ptr, Offset, DL);
2341   if (Base && Base == &AssociatedValue) {
2342     int64_t DerefBytes = Loc->Size.getValue() + Offset;
2343     IsNonNull |= !NullPointerIsDefined;
2344     return std::max(int64_t(0), DerefBytes);
2345   }
2346 
2347   /// Corner case when an offset is 0.
2348   Base = GetPointerBaseWithConstantOffset(Loc->Ptr, Offset, DL,
2349                                           /*AllowNonInbounds*/ true);
2350   if (Base && Base == &AssociatedValue && Offset == 0) {
2351     int64_t DerefBytes = Loc->Size.getValue();
2352     IsNonNull |= !NullPointerIsDefined;
2353     return std::max(int64_t(0), DerefBytes);
2354   }
2355 
2356   return 0;
2357 }
2358 
2359 struct AANonNullImpl : AANonNull {
2360   AANonNullImpl(const IRPosition &IRP, Attributor &A)
2361       : AANonNull(IRP, A),
2362         NullIsDefined(NullPointerIsDefined(
2363             getAnchorScope(),
2364             getAssociatedValue().getType()->getPointerAddressSpace())) {}
2365 
2366   /// See AbstractAttribute::initialize(...).
2367   void initialize(Attributor &A) override {
2368     Value &V = getAssociatedValue();
2369     if (!NullIsDefined &&
2370         hasAttr({Attribute::NonNull, Attribute::Dereferenceable},
2371                 /* IgnoreSubsumingPositions */ false, &A)) {
2372       indicateOptimisticFixpoint();
2373       return;
2374     }
2375 
2376     if (isa<ConstantPointerNull>(V)) {
2377       indicatePessimisticFixpoint();
2378       return;
2379     }
2380 
2381     AANonNull::initialize(A);
2382 
2383     bool CanBeNull, CanBeFreed;
2384     if (V.getPointerDereferenceableBytes(A.getDataLayout(), CanBeNull,
2385                                          CanBeFreed)) {
2386       if (!CanBeNull) {
2387         indicateOptimisticFixpoint();
2388         return;
2389       }
2390     }
2391 
2392     if (isa<GlobalValue>(&getAssociatedValue())) {
2393       indicatePessimisticFixpoint();
2394       return;
2395     }
2396 
2397     if (Instruction *CtxI = getCtxI())
2398       followUsesInMBEC(*this, A, getState(), *CtxI);
2399   }
2400 
2401   /// See followUsesInMBEC
2402   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
2403                        AANonNull::StateType &State) {
2404     bool IsNonNull = false;
2405     bool TrackUse = false;
2406     getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I,
2407                                        IsNonNull, TrackUse);
2408     State.setKnown(IsNonNull);
2409     return TrackUse;
2410   }
2411 
2412   /// See AbstractAttribute::getAsStr().
2413   const std::string getAsStr() const override {
2414     return getAssumed() ? "nonnull" : "may-null";
2415   }
2416 
2417   /// Flag to determine if the underlying value can be null and still allow
2418   /// valid accesses.
2419   const bool NullIsDefined;
2420 };
2421 
2422 /// NonNull attribute for a floating value.
2423 struct AANonNullFloating : public AANonNullImpl {
2424   AANonNullFloating(const IRPosition &IRP, Attributor &A)
2425       : AANonNullImpl(IRP, A) {}
2426 
2427   /// See AbstractAttribute::updateImpl(...).
2428   ChangeStatus updateImpl(Attributor &A) override {
2429     const DataLayout &DL = A.getDataLayout();
2430 
2431     DominatorTree *DT = nullptr;
2432     AssumptionCache *AC = nullptr;
2433     InformationCache &InfoCache = A.getInfoCache();
2434     if (const Function *Fn = getAnchorScope()) {
2435       DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn);
2436       AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn);
2437     }
2438 
2439     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
2440                             AANonNull::StateType &T, bool Stripped) -> bool {
2441       const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V),
2442                                              DepClassTy::REQUIRED);
2443       if (!Stripped && this == &AA) {
2444         if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT))
2445           T.indicatePessimisticFixpoint();
2446       } else {
2447         // Use abstract attribute information.
2448         const AANonNull::StateType &NS = AA.getState();
2449         T ^= NS;
2450       }
2451       return T.isValidState();
2452     };
2453 
2454     StateType T;
2455     bool UsedAssumedInformation = false;
2456     if (!genericValueTraversal<StateType>(A, getIRPosition(), *this, T,
2457                                           VisitValueCB, getCtxI(),
2458                                           UsedAssumedInformation))
2459       return indicatePessimisticFixpoint();
2460 
2461     return clampStateAndIndicateChange(getState(), T);
2462   }
2463 
2464   /// See AbstractAttribute::trackStatistics()
2465   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2466 };
2467 
2468 /// NonNull attribute for function return value.
2469 struct AANonNullReturned final
2470     : AAReturnedFromReturnedValues<AANonNull, AANonNull> {
2471   AANonNullReturned(const IRPosition &IRP, Attributor &A)
2472       : AAReturnedFromReturnedValues<AANonNull, AANonNull>(IRP, A) {}
2473 
2474   /// See AbstractAttribute::getAsStr().
2475   const std::string getAsStr() const override {
2476     return getAssumed() ? "nonnull" : "may-null";
2477   }
2478 
2479   /// See AbstractAttribute::trackStatistics()
2480   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) }
2481 };
2482 
2483 /// NonNull attribute for function argument.
2484 struct AANonNullArgument final
2485     : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
2486   AANonNullArgument(const IRPosition &IRP, Attributor &A)
2487       : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {}
2488 
2489   /// See AbstractAttribute::trackStatistics()
2490   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) }
2491 };
2492 
2493 struct AANonNullCallSiteArgument final : AANonNullFloating {
2494   AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A)
2495       : AANonNullFloating(IRP, A) {}
2496 
2497   /// See AbstractAttribute::trackStatistics()
2498   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) }
2499 };
2500 
2501 /// NonNull attribute for a call site return position.
2502 struct AANonNullCallSiteReturned final
2503     : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> {
2504   AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A)
2505       : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP, A) {}
2506 
2507   /// See AbstractAttribute::trackStatistics()
2508   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) }
2509 };
2510 } // namespace
2511 
2512 /// ------------------------ No-Recurse Attributes ----------------------------
2513 
2514 namespace {
2515 struct AANoRecurseImpl : public AANoRecurse {
2516   AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {}
2517 
2518   /// See AbstractAttribute::getAsStr()
2519   const std::string getAsStr() const override {
2520     return getAssumed() ? "norecurse" : "may-recurse";
2521   }
2522 };
2523 
2524 struct AANoRecurseFunction final : AANoRecurseImpl {
2525   AANoRecurseFunction(const IRPosition &IRP, Attributor &A)
2526       : AANoRecurseImpl(IRP, A) {}
2527 
2528   /// See AbstractAttribute::updateImpl(...).
2529   ChangeStatus updateImpl(Attributor &A) override {
2530 
2531     // If all live call sites are known to be no-recurse, we are as well.
2532     auto CallSitePred = [&](AbstractCallSite ACS) {
2533       const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
2534           *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
2535           DepClassTy::NONE);
2536       return NoRecurseAA.isKnownNoRecurse();
2537     };
2538     bool UsedAssumedInformation = false;
2539     if (A.checkForAllCallSites(CallSitePred, *this, true,
2540                                UsedAssumedInformation)) {
2541       // If we know all call sites and all are known no-recurse, we are done.
2542       // If all known call sites, which might not be all that exist, are known
2543       // to be no-recurse, we are not done but we can continue to assume
2544       // no-recurse. If one of the call sites we have not visited will become
2545       // live, another update is triggered.
2546       if (!UsedAssumedInformation)
2547         indicateOptimisticFixpoint();
2548       return ChangeStatus::UNCHANGED;
2549     }
2550 
2551     const AAFunctionReachability &EdgeReachability =
2552         A.getAAFor<AAFunctionReachability>(*this, getIRPosition(),
2553                                            DepClassTy::REQUIRED);
2554     if (EdgeReachability.canReach(A, *getAnchorScope()))
2555       return indicatePessimisticFixpoint();
2556     return ChangeStatus::UNCHANGED;
2557   }
2558 
2559   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) }
2560 };
2561 
2562 /// NoRecurse attribute deduction for a call sites.
2563 struct AANoRecurseCallSite final : AANoRecurseImpl {
2564   AANoRecurseCallSite(const IRPosition &IRP, Attributor &A)
2565       : AANoRecurseImpl(IRP, A) {}
2566 
2567   /// See AbstractAttribute::initialize(...).
2568   void initialize(Attributor &A) override {
2569     AANoRecurseImpl::initialize(A);
2570     Function *F = getAssociatedFunction();
2571     if (!F || F->isDeclaration())
2572       indicatePessimisticFixpoint();
2573   }
2574 
2575   /// See AbstractAttribute::updateImpl(...).
2576   ChangeStatus updateImpl(Attributor &A) override {
2577     // TODO: Once we have call site specific value information we can provide
2578     //       call site specific liveness information and then it makes
2579     //       sense to specialize attributes for call sites arguments instead of
2580     //       redirecting requests to the callee argument.
2581     Function *F = getAssociatedFunction();
2582     const IRPosition &FnPos = IRPosition::function(*F);
2583     auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos, DepClassTy::REQUIRED);
2584     return clampStateAndIndicateChange(getState(), FnAA.getState());
2585   }
2586 
2587   /// See AbstractAttribute::trackStatistics()
2588   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); }
2589 };
2590 } // namespace
2591 
2592 /// -------------------- Undefined-Behavior Attributes ------------------------
2593 
2594 namespace {
2595 struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior {
2596   AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A)
2597       : AAUndefinedBehavior(IRP, A) {}
2598 
2599   /// See AbstractAttribute::updateImpl(...).
2600   // through a pointer (i.e. also branches etc.)
2601   ChangeStatus updateImpl(Attributor &A) override {
2602     const size_t UBPrevSize = KnownUBInsts.size();
2603     const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2604 
2605     auto InspectMemAccessInstForUB = [&](Instruction &I) {
2606       // Lang ref now states volatile store is not UB, let's skip them.
2607       if (I.isVolatile() && I.mayWriteToMemory())
2608         return true;
2609 
2610       // Skip instructions that are already saved.
2611       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2612         return true;
2613 
2614       // If we reach here, we know we have an instruction
2615       // that accesses memory through a pointer operand,
2616       // for which getPointerOperand() should give it to us.
2617       Value *PtrOp =
2618           const_cast<Value *>(getPointerOperand(&I, /* AllowVolatile */ true));
2619       assert(PtrOp &&
2620              "Expected pointer operand of memory accessing instruction");
2621 
2622       // Either we stopped and the appropriate action was taken,
2623       // or we got back a simplified value to continue.
2624       Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I);
2625       if (!SimplifiedPtrOp.hasValue() || !SimplifiedPtrOp.getValue())
2626         return true;
2627       const Value *PtrOpVal = SimplifiedPtrOp.getValue();
2628 
2629       // A memory access through a pointer is considered UB
2630       // only if the pointer has constant null value.
2631       // TODO: Expand it to not only check constant values.
2632       if (!isa<ConstantPointerNull>(PtrOpVal)) {
2633         AssumedNoUBInsts.insert(&I);
2634         return true;
2635       }
2636       const Type *PtrTy = PtrOpVal->getType();
2637 
2638       // Because we only consider instructions inside functions,
2639       // assume that a parent function exists.
2640       const Function *F = I.getFunction();
2641 
2642       // A memory access using constant null pointer is only considered UB
2643       // if null pointer is _not_ defined for the target platform.
2644       if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()))
2645         AssumedNoUBInsts.insert(&I);
2646       else
2647         KnownUBInsts.insert(&I);
2648       return true;
2649     };
2650 
2651     auto InspectBrInstForUB = [&](Instruction &I) {
2652       // A conditional branch instruction is considered UB if it has `undef`
2653       // condition.
2654 
2655       // Skip instructions that are already saved.
2656       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2657         return true;
2658 
2659       // We know we have a branch instruction.
2660       auto *BrInst = cast<BranchInst>(&I);
2661 
2662       // Unconditional branches are never considered UB.
2663       if (BrInst->isUnconditional())
2664         return true;
2665 
2666       // Either we stopped and the appropriate action was taken,
2667       // or we got back a simplified value to continue.
2668       Optional<Value *> SimplifiedCond =
2669           stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst);
2670       if (!SimplifiedCond.hasValue() || !SimplifiedCond.getValue())
2671         return true;
2672       AssumedNoUBInsts.insert(&I);
2673       return true;
2674     };
2675 
2676     auto InspectCallSiteForUB = [&](Instruction &I) {
2677       // Check whether a callsite always cause UB or not
2678 
2679       // Skip instructions that are already saved.
2680       if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2681         return true;
2682 
2683       // Check nonnull and noundef argument attribute violation for each
2684       // callsite.
2685       CallBase &CB = cast<CallBase>(I);
2686       Function *Callee = CB.getCalledFunction();
2687       if (!Callee)
2688         return true;
2689       for (unsigned idx = 0; idx < CB.arg_size(); idx++) {
2690         // If current argument is known to be simplified to null pointer and the
2691         // corresponding argument position is known to have nonnull attribute,
2692         // the argument is poison. Furthermore, if the argument is poison and
2693         // the position is known to have noundef attriubte, this callsite is
2694         // considered UB.
2695         if (idx >= Callee->arg_size())
2696           break;
2697         Value *ArgVal = CB.getArgOperand(idx);
2698         if (!ArgVal)
2699           continue;
2700         // Here, we handle three cases.
2701         //   (1) Not having a value means it is dead. (we can replace the value
2702         //       with undef)
2703         //   (2) Simplified to undef. The argument violate noundef attriubte.
2704         //   (3) Simplified to null pointer where known to be nonnull.
2705         //       The argument is a poison value and violate noundef attribute.
2706         IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx);
2707         auto &NoUndefAA =
2708             A.getAAFor<AANoUndef>(*this, CalleeArgumentIRP, DepClassTy::NONE);
2709         if (!NoUndefAA.isKnownNoUndef())
2710           continue;
2711         bool UsedAssumedInformation = false;
2712         Optional<Value *> SimplifiedVal = A.getAssumedSimplified(
2713             IRPosition::value(*ArgVal), *this, UsedAssumedInformation);
2714         if (UsedAssumedInformation)
2715           continue;
2716         if (SimplifiedVal.hasValue() && !SimplifiedVal.getValue())
2717           return true;
2718         if (!SimplifiedVal.hasValue() ||
2719             isa<UndefValue>(*SimplifiedVal.getValue())) {
2720           KnownUBInsts.insert(&I);
2721           continue;
2722         }
2723         if (!ArgVal->getType()->isPointerTy() ||
2724             !isa<ConstantPointerNull>(*SimplifiedVal.getValue()))
2725           continue;
2726         auto &NonNullAA =
2727             A.getAAFor<AANonNull>(*this, CalleeArgumentIRP, DepClassTy::NONE);
2728         if (NonNullAA.isKnownNonNull())
2729           KnownUBInsts.insert(&I);
2730       }
2731       return true;
2732     };
2733 
2734     auto InspectReturnInstForUB = [&](Instruction &I) {
2735       auto &RI = cast<ReturnInst>(I);
2736       // Either we stopped and the appropriate action was taken,
2737       // or we got back a simplified return value to continue.
2738       Optional<Value *> SimplifiedRetValue =
2739           stopOnUndefOrAssumed(A, RI.getReturnValue(), &I);
2740       if (!SimplifiedRetValue.hasValue() || !SimplifiedRetValue.getValue())
2741         return true;
2742 
2743       // Check if a return instruction always cause UB or not
2744       // Note: It is guaranteed that the returned position of the anchor
2745       //       scope has noundef attribute when this is called.
2746       //       We also ensure the return position is not "assumed dead"
2747       //       because the returned value was then potentially simplified to
2748       //       `undef` in AAReturnedValues without removing the `noundef`
2749       //       attribute yet.
2750 
2751       // When the returned position has noundef attriubte, UB occurs in the
2752       // following cases.
2753       //   (1) Returned value is known to be undef.
2754       //   (2) The value is known to be a null pointer and the returned
2755       //       position has nonnull attribute (because the returned value is
2756       //       poison).
2757       if (isa<ConstantPointerNull>(*SimplifiedRetValue)) {
2758         auto &NonNullAA = A.getAAFor<AANonNull>(
2759             *this, IRPosition::returned(*getAnchorScope()), DepClassTy::NONE);
2760         if (NonNullAA.isKnownNonNull())
2761           KnownUBInsts.insert(&I);
2762       }
2763 
2764       return true;
2765     };
2766 
2767     bool UsedAssumedInformation = false;
2768     A.checkForAllInstructions(InspectMemAccessInstForUB, *this,
2769                               {Instruction::Load, Instruction::Store,
2770                                Instruction::AtomicCmpXchg,
2771                                Instruction::AtomicRMW},
2772                               UsedAssumedInformation,
2773                               /* CheckBBLivenessOnly */ true);
2774     A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br},
2775                               UsedAssumedInformation,
2776                               /* CheckBBLivenessOnly */ true);
2777     A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this,
2778                                       UsedAssumedInformation);
2779 
2780     // If the returned position of the anchor scope has noundef attriubte, check
2781     // all returned instructions.
2782     if (!getAnchorScope()->getReturnType()->isVoidTy()) {
2783       const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope());
2784       if (!A.isAssumedDead(ReturnIRP, this, nullptr, UsedAssumedInformation)) {
2785         auto &RetPosNoUndefAA =
2786             A.getAAFor<AANoUndef>(*this, ReturnIRP, DepClassTy::NONE);
2787         if (RetPosNoUndefAA.isKnownNoUndef())
2788           A.checkForAllInstructions(InspectReturnInstForUB, *this,
2789                                     {Instruction::Ret}, UsedAssumedInformation,
2790                                     /* CheckBBLivenessOnly */ true);
2791       }
2792     }
2793 
2794     if (NoUBPrevSize != AssumedNoUBInsts.size() ||
2795         UBPrevSize != KnownUBInsts.size())
2796       return ChangeStatus::CHANGED;
2797     return ChangeStatus::UNCHANGED;
2798   }
2799 
2800   bool isKnownToCauseUB(Instruction *I) const override {
2801     return KnownUBInsts.count(I);
2802   }
2803 
2804   bool isAssumedToCauseUB(Instruction *I) const override {
2805     // In simple words, if an instruction is not in the assumed to _not_
2806     // cause UB, then it is assumed UB (that includes those
2807     // in the KnownUBInsts set). The rest is boilerplate
2808     // is to ensure that it is one of the instructions we test
2809     // for UB.
2810 
2811     switch (I->getOpcode()) {
2812     case Instruction::Load:
2813     case Instruction::Store:
2814     case Instruction::AtomicCmpXchg:
2815     case Instruction::AtomicRMW:
2816       return !AssumedNoUBInsts.count(I);
2817     case Instruction::Br: {
2818       auto *BrInst = cast<BranchInst>(I);
2819       if (BrInst->isUnconditional())
2820         return false;
2821       return !AssumedNoUBInsts.count(I);
2822     } break;
2823     default:
2824       return false;
2825     }
2826     return false;
2827   }
2828 
2829   ChangeStatus manifest(Attributor &A) override {
2830     if (KnownUBInsts.empty())
2831       return ChangeStatus::UNCHANGED;
2832     for (Instruction *I : KnownUBInsts)
2833       A.changeToUnreachableAfterManifest(I);
2834     return ChangeStatus::CHANGED;
2835   }
2836 
2837   /// See AbstractAttribute::getAsStr()
2838   const std::string getAsStr() const override {
2839     return getAssumed() ? "undefined-behavior" : "no-ub";
2840   }
2841 
2842   /// Note: The correctness of this analysis depends on the fact that the
2843   /// following 2 sets will stop changing after some point.
2844   /// "Change" here means that their size changes.
2845   /// The size of each set is monotonically increasing
2846   /// (we only add items to them) and it is upper bounded by the number of
2847   /// instructions in the processed function (we can never save more
2848   /// elements in either set than this number). Hence, at some point,
2849   /// they will stop increasing.
2850   /// Consequently, at some point, both sets will have stopped
2851   /// changing, effectively making the analysis reach a fixpoint.
2852 
2853   /// Note: These 2 sets are disjoint and an instruction can be considered
2854   /// one of 3 things:
2855   /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in
2856   ///    the KnownUBInsts set.
2857   /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior
2858   ///    has a reason to assume it).
2859   /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior
2860   ///    could not find a reason to assume or prove that it can cause UB,
2861   ///    hence it assumes it doesn't. We have a set for these instructions
2862   ///    so that we don't reprocess them in every update.
2863   ///    Note however that instructions in this set may cause UB.
2864 
2865 protected:
2866   /// A set of all live instructions _known_ to cause UB.
2867   SmallPtrSet<Instruction *, 8> KnownUBInsts;
2868 
2869 private:
2870   /// A set of all the (live) instructions that are assumed to _not_ cause UB.
2871   SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
2872 
2873   // Should be called on updates in which if we're processing an instruction
2874   // \p I that depends on a value \p V, one of the following has to happen:
2875   // - If the value is assumed, then stop.
2876   // - If the value is known but undef, then consider it UB.
2877   // - Otherwise, do specific processing with the simplified value.
2878   // We return None in the first 2 cases to signify that an appropriate
2879   // action was taken and the caller should stop.
2880   // Otherwise, we return the simplified value that the caller should
2881   // use for specific processing.
2882   Optional<Value *> stopOnUndefOrAssumed(Attributor &A, Value *V,
2883                                          Instruction *I) {
2884     bool UsedAssumedInformation = false;
2885     Optional<Value *> SimplifiedV = A.getAssumedSimplified(
2886         IRPosition::value(*V), *this, UsedAssumedInformation);
2887     if (!UsedAssumedInformation) {
2888       // Don't depend on assumed values.
2889       if (!SimplifiedV.hasValue()) {
2890         // If it is known (which we tested above) but it doesn't have a value,
2891         // then we can assume `undef` and hence the instruction is UB.
2892         KnownUBInsts.insert(I);
2893         return llvm::None;
2894       }
2895       if (!SimplifiedV.getValue())
2896         return nullptr;
2897       V = *SimplifiedV;
2898     }
2899     if (isa<UndefValue>(V)) {
2900       KnownUBInsts.insert(I);
2901       return llvm::None;
2902     }
2903     return V;
2904   }
2905 };
2906 
2907 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
2908   AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A)
2909       : AAUndefinedBehaviorImpl(IRP, A) {}
2910 
2911   /// See AbstractAttribute::trackStatistics()
2912   void trackStatistics() const override {
2913     STATS_DECL(UndefinedBehaviorInstruction, Instruction,
2914                "Number of instructions known to have UB");
2915     BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) +=
2916         KnownUBInsts.size();
2917   }
2918 };
2919 } // namespace
2920 
2921 /// ------------------------ Will-Return Attributes ----------------------------
2922 
2923 namespace {
2924 // Helper function that checks whether a function has any cycle which we don't
2925 // know if it is bounded or not.
2926 // Loops with maximum trip count are considered bounded, any other cycle not.
2927 static bool mayContainUnboundedCycle(Function &F, Attributor &A) {
2928   ScalarEvolution *SE =
2929       A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F);
2930   LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F);
2931   // If either SCEV or LoopInfo is not available for the function then we assume
2932   // any cycle to be unbounded cycle.
2933   // We use scc_iterator which uses Tarjan algorithm to find all the maximal
2934   // SCCs.To detect if there's a cycle, we only need to find the maximal ones.
2935   if (!SE || !LI) {
2936     for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI)
2937       if (SCCI.hasCycle())
2938         return true;
2939     return false;
2940   }
2941 
2942   // If there's irreducible control, the function may contain non-loop cycles.
2943   if (mayContainIrreducibleControl(F, LI))
2944     return true;
2945 
2946   // Any loop that does not have a max trip count is considered unbounded cycle.
2947   for (auto *L : LI->getLoopsInPreorder()) {
2948     if (!SE->getSmallConstantMaxTripCount(L))
2949       return true;
2950   }
2951   return false;
2952 }
2953 
2954 struct AAWillReturnImpl : public AAWillReturn {
2955   AAWillReturnImpl(const IRPosition &IRP, Attributor &A)
2956       : AAWillReturn(IRP, A) {}
2957 
2958   /// See AbstractAttribute::initialize(...).
2959   void initialize(Attributor &A) override {
2960     AAWillReturn::initialize(A);
2961 
2962     if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ true)) {
2963       indicateOptimisticFixpoint();
2964       return;
2965     }
2966   }
2967 
2968   /// Check for `mustprogress` and `readonly` as they imply `willreturn`.
2969   bool isImpliedByMustprogressAndReadonly(Attributor &A, bool KnownOnly) {
2970     // Check for `mustprogress` in the scope and the associated function which
2971     // might be different if this is a call site.
2972     if ((!getAnchorScope() || !getAnchorScope()->mustProgress()) &&
2973         (!getAssociatedFunction() || !getAssociatedFunction()->mustProgress()))
2974       return false;
2975 
2976     bool IsKnown;
2977     if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
2978       return IsKnown || !KnownOnly;
2979     return false;
2980   }
2981 
2982   /// See AbstractAttribute::updateImpl(...).
2983   ChangeStatus updateImpl(Attributor &A) override {
2984     if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
2985       return ChangeStatus::UNCHANGED;
2986 
2987     auto CheckForWillReturn = [&](Instruction &I) {
2988       IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I));
2989       const auto &WillReturnAA =
2990           A.getAAFor<AAWillReturn>(*this, IPos, DepClassTy::REQUIRED);
2991       if (WillReturnAA.isKnownWillReturn())
2992         return true;
2993       if (!WillReturnAA.isAssumedWillReturn())
2994         return false;
2995       const auto &NoRecurseAA =
2996           A.getAAFor<AANoRecurse>(*this, IPos, DepClassTy::REQUIRED);
2997       return NoRecurseAA.isAssumedNoRecurse();
2998     };
2999 
3000     bool UsedAssumedInformation = false;
3001     if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this,
3002                                            UsedAssumedInformation))
3003       return indicatePessimisticFixpoint();
3004 
3005     return ChangeStatus::UNCHANGED;
3006   }
3007 
3008   /// See AbstractAttribute::getAsStr()
3009   const std::string getAsStr() const override {
3010     return getAssumed() ? "willreturn" : "may-noreturn";
3011   }
3012 };
3013 
3014 struct AAWillReturnFunction final : AAWillReturnImpl {
3015   AAWillReturnFunction(const IRPosition &IRP, Attributor &A)
3016       : AAWillReturnImpl(IRP, A) {}
3017 
3018   /// See AbstractAttribute::initialize(...).
3019   void initialize(Attributor &A) override {
3020     AAWillReturnImpl::initialize(A);
3021 
3022     Function *F = getAnchorScope();
3023     if (!F || F->isDeclaration() || mayContainUnboundedCycle(*F, A))
3024       indicatePessimisticFixpoint();
3025   }
3026 
3027   /// See AbstractAttribute::trackStatistics()
3028   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) }
3029 };
3030 
3031 /// WillReturn attribute deduction for a call sites.
3032 struct AAWillReturnCallSite final : AAWillReturnImpl {
3033   AAWillReturnCallSite(const IRPosition &IRP, Attributor &A)
3034       : AAWillReturnImpl(IRP, A) {}
3035 
3036   /// See AbstractAttribute::initialize(...).
3037   void initialize(Attributor &A) override {
3038     AAWillReturnImpl::initialize(A);
3039     Function *F = getAssociatedFunction();
3040     if (!F || !A.isFunctionIPOAmendable(*F))
3041       indicatePessimisticFixpoint();
3042   }
3043 
3044   /// See AbstractAttribute::updateImpl(...).
3045   ChangeStatus updateImpl(Attributor &A) override {
3046     if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false))
3047       return ChangeStatus::UNCHANGED;
3048 
3049     // TODO: Once we have call site specific value information we can provide
3050     //       call site specific liveness information and then it makes
3051     //       sense to specialize attributes for call sites arguments instead of
3052     //       redirecting requests to the callee argument.
3053     Function *F = getAssociatedFunction();
3054     const IRPosition &FnPos = IRPosition::function(*F);
3055     auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos, DepClassTy::REQUIRED);
3056     return clampStateAndIndicateChange(getState(), FnAA.getState());
3057   }
3058 
3059   /// See AbstractAttribute::trackStatistics()
3060   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); }
3061 };
3062 } // namespace
3063 
3064 /// -------------------AAReachability Attribute--------------------------
3065 
3066 namespace {
3067 struct AAReachabilityImpl : AAReachability {
3068   AAReachabilityImpl(const IRPosition &IRP, Attributor &A)
3069       : AAReachability(IRP, A) {}
3070 
3071   const std::string getAsStr() const override {
3072     // TODO: Return the number of reachable queries.
3073     return "reachable";
3074   }
3075 
3076   /// See AbstractAttribute::updateImpl(...).
3077   ChangeStatus updateImpl(Attributor &A) override {
3078     return ChangeStatus::UNCHANGED;
3079   }
3080 };
3081 
3082 struct AAReachabilityFunction final : public AAReachabilityImpl {
3083   AAReachabilityFunction(const IRPosition &IRP, Attributor &A)
3084       : AAReachabilityImpl(IRP, A) {}
3085 
3086   /// See AbstractAttribute::trackStatistics()
3087   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); }
3088 };
3089 } // namespace
3090 
3091 /// ------------------------ NoAlias Argument Attribute ------------------------
3092 
3093 namespace {
3094 struct AANoAliasImpl : AANoAlias {
3095   AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) {
3096     assert(getAssociatedType()->isPointerTy() &&
3097            "Noalias is a pointer attribute");
3098   }
3099 
3100   const std::string getAsStr() const override {
3101     return getAssumed() ? "noalias" : "may-alias";
3102   }
3103 };
3104 
3105 /// NoAlias attribute for a floating value.
3106 struct AANoAliasFloating final : AANoAliasImpl {
3107   AANoAliasFloating(const IRPosition &IRP, Attributor &A)
3108       : AANoAliasImpl(IRP, A) {}
3109 
3110   /// See AbstractAttribute::initialize(...).
3111   void initialize(Attributor &A) override {
3112     AANoAliasImpl::initialize(A);
3113     Value *Val = &getAssociatedValue();
3114     do {
3115       CastInst *CI = dyn_cast<CastInst>(Val);
3116       if (!CI)
3117         break;
3118       Value *Base = CI->getOperand(0);
3119       if (!Base->hasOneUse())
3120         break;
3121       Val = Base;
3122     } while (true);
3123 
3124     if (!Val->getType()->isPointerTy()) {
3125       indicatePessimisticFixpoint();
3126       return;
3127     }
3128 
3129     if (isa<AllocaInst>(Val))
3130       indicateOptimisticFixpoint();
3131     else if (isa<ConstantPointerNull>(Val) &&
3132              !NullPointerIsDefined(getAnchorScope(),
3133                                    Val->getType()->getPointerAddressSpace()))
3134       indicateOptimisticFixpoint();
3135     else if (Val != &getAssociatedValue()) {
3136       const auto &ValNoAliasAA = A.getAAFor<AANoAlias>(
3137           *this, IRPosition::value(*Val), DepClassTy::OPTIONAL);
3138       if (ValNoAliasAA.isKnownNoAlias())
3139         indicateOptimisticFixpoint();
3140     }
3141   }
3142 
3143   /// See AbstractAttribute::updateImpl(...).
3144   ChangeStatus updateImpl(Attributor &A) override {
3145     // TODO: Implement this.
3146     return indicatePessimisticFixpoint();
3147   }
3148 
3149   /// See AbstractAttribute::trackStatistics()
3150   void trackStatistics() const override {
3151     STATS_DECLTRACK_FLOATING_ATTR(noalias)
3152   }
3153 };
3154 
3155 /// NoAlias attribute for an argument.
3156 struct AANoAliasArgument final
3157     : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
3158   using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
3159   AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
3160 
3161   /// See AbstractAttribute::initialize(...).
3162   void initialize(Attributor &A) override {
3163     Base::initialize(A);
3164     // See callsite argument attribute and callee argument attribute.
3165     if (hasAttr({Attribute::ByVal}))
3166       indicateOptimisticFixpoint();
3167   }
3168 
3169   /// See AbstractAttribute::update(...).
3170   ChangeStatus updateImpl(Attributor &A) override {
3171     // We have to make sure no-alias on the argument does not break
3172     // synchronization when this is a callback argument, see also [1] below.
3173     // If synchronization cannot be affected, we delegate to the base updateImpl
3174     // function, otherwise we give up for now.
3175 
3176     // If the function is no-sync, no-alias cannot break synchronization.
3177     const auto &NoSyncAA =
3178         A.getAAFor<AANoSync>(*this, IRPosition::function_scope(getIRPosition()),
3179                              DepClassTy::OPTIONAL);
3180     if (NoSyncAA.isAssumedNoSync())
3181       return Base::updateImpl(A);
3182 
3183     // If the argument is read-only, no-alias cannot break synchronization.
3184     bool IsKnown;
3185     if (AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
3186       return Base::updateImpl(A);
3187 
3188     // If the argument is never passed through callbacks, no-alias cannot break
3189     // synchronization.
3190     bool UsedAssumedInformation = false;
3191     if (A.checkForAllCallSites(
3192             [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this,
3193             true, UsedAssumedInformation))
3194       return Base::updateImpl(A);
3195 
3196     // TODO: add no-alias but make sure it doesn't break synchronization by
3197     // introducing fake uses. See:
3198     // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel,
3199     //     International Workshop on OpenMP 2018,
3200     //     http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf
3201 
3202     return indicatePessimisticFixpoint();
3203   }
3204 
3205   /// See AbstractAttribute::trackStatistics()
3206   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) }
3207 };
3208 
3209 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
3210   AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A)
3211       : AANoAliasImpl(IRP, A) {}
3212 
3213   /// See AbstractAttribute::initialize(...).
3214   void initialize(Attributor &A) override {
3215     // See callsite argument attribute and callee argument attribute.
3216     const auto &CB = cast<CallBase>(getAnchorValue());
3217     if (CB.paramHasAttr(getCallSiteArgNo(), Attribute::NoAlias))
3218       indicateOptimisticFixpoint();
3219     Value &Val = getAssociatedValue();
3220     if (isa<ConstantPointerNull>(Val) &&
3221         !NullPointerIsDefined(getAnchorScope(),
3222                               Val.getType()->getPointerAddressSpace()))
3223       indicateOptimisticFixpoint();
3224   }
3225 
3226   /// Determine if the underlying value may alias with the call site argument
3227   /// \p OtherArgNo of \p ICS (= the underlying call site).
3228   bool mayAliasWithArgument(Attributor &A, AAResults *&AAR,
3229                             const AAMemoryBehavior &MemBehaviorAA,
3230                             const CallBase &CB, unsigned OtherArgNo) {
3231     // We do not need to worry about aliasing with the underlying IRP.
3232     if (this->getCalleeArgNo() == (int)OtherArgNo)
3233       return false;
3234 
3235     // If it is not a pointer or pointer vector we do not alias.
3236     const Value *ArgOp = CB.getArgOperand(OtherArgNo);
3237     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
3238       return false;
3239 
3240     auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
3241         *this, IRPosition::callsite_argument(CB, OtherArgNo), DepClassTy::NONE);
3242 
3243     // If the argument is readnone, there is no read-write aliasing.
3244     if (CBArgMemBehaviorAA.isAssumedReadNone()) {
3245       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3246       return false;
3247     }
3248 
3249     // If the argument is readonly and the underlying value is readonly, there
3250     // is no read-write aliasing.
3251     bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly();
3252     if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) {
3253       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3254       A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL);
3255       return false;
3256     }
3257 
3258     // We have to utilize actual alias analysis queries so we need the object.
3259     if (!AAR)
3260       AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope());
3261 
3262     // Try to rule it out at the call site.
3263     bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp);
3264     LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between "
3265                          "callsite arguments: "
3266                       << getAssociatedValue() << " " << *ArgOp << " => "
3267                       << (IsAliasing ? "" : "no-") << "alias \n");
3268 
3269     return IsAliasing;
3270   }
3271 
3272   bool
3273   isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR,
3274                                          const AAMemoryBehavior &MemBehaviorAA,
3275                                          const AANoAlias &NoAliasAA) {
3276     // We can deduce "noalias" if the following conditions hold.
3277     // (i)   Associated value is assumed to be noalias in the definition.
3278     // (ii)  Associated value is assumed to be no-capture in all the uses
3279     //       possibly executed before this callsite.
3280     // (iii) There is no other pointer argument which could alias with the
3281     //       value.
3282 
3283     bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias();
3284     if (!AssociatedValueIsNoAliasAtDef) {
3285       LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue()
3286                         << " is not no-alias at the definition\n");
3287       return false;
3288     }
3289 
3290     auto IsDereferenceableOrNull = [&](Value *O, const DataLayout &DL) {
3291       const auto &DerefAA = A.getAAFor<AADereferenceable>(
3292           *this, IRPosition::value(*O), DepClassTy::OPTIONAL);
3293       return DerefAA.getAssumedDereferenceableBytes();
3294     };
3295 
3296     A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL);
3297 
3298     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3299     const Function *ScopeFn = VIRP.getAnchorScope();
3300     auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, VIRP, DepClassTy::NONE);
3301     // Check whether the value is captured in the scope using AANoCapture.
3302     // Look at CFG and check only uses possibly executed before this
3303     // callsite.
3304     auto UsePred = [&](const Use &U, bool &Follow) -> bool {
3305       Instruction *UserI = cast<Instruction>(U.getUser());
3306 
3307       // If UserI is the curr instruction and there is a single potential use of
3308       // the value in UserI we allow the use.
3309       // TODO: We should inspect the operands and allow those that cannot alias
3310       //       with the value.
3311       if (UserI == getCtxI() && UserI->getNumOperands() == 1)
3312         return true;
3313 
3314       if (ScopeFn) {
3315         if (auto *CB = dyn_cast<CallBase>(UserI)) {
3316           if (CB->isArgOperand(&U)) {
3317 
3318             unsigned ArgNo = CB->getArgOperandNo(&U);
3319 
3320             const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
3321                 *this, IRPosition::callsite_argument(*CB, ArgNo),
3322                 DepClassTy::OPTIONAL);
3323 
3324             if (NoCaptureAA.isAssumedNoCapture())
3325               return true;
3326           }
3327         }
3328 
3329         if (!AA::isPotentiallyReachable(A, *UserI, *getCtxI(), *this))
3330           return true;
3331       }
3332 
3333       // TODO: We should track the capturing uses in AANoCapture but the problem
3334       //       is CGSCC runs. For those we would need to "allow" AANoCapture for
3335       //       a value in the module slice.
3336       switch (DetermineUseCaptureKind(U, IsDereferenceableOrNull)) {
3337       case UseCaptureKind::NO_CAPTURE:
3338         return true;
3339       case UseCaptureKind::MAY_CAPTURE:
3340         LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *UserI
3341                           << "\n");
3342         return false;
3343       case UseCaptureKind::PASSTHROUGH:
3344         Follow = true;
3345         return true;
3346       }
3347       llvm_unreachable("unknown UseCaptureKind");
3348     };
3349 
3350     if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
3351       if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) {
3352         LLVM_DEBUG(
3353             dbgs() << "[AANoAliasCSArg] " << getAssociatedValue()
3354                    << " cannot be noalias as it is potentially captured\n");
3355         return false;
3356       }
3357     }
3358     A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL);
3359 
3360     // Check there is no other pointer argument which could alias with the
3361     // value passed at this call site.
3362     // TODO: AbstractCallSite
3363     const auto &CB = cast<CallBase>(getAnchorValue());
3364     for (unsigned OtherArgNo = 0; OtherArgNo < CB.arg_size(); OtherArgNo++)
3365       if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo))
3366         return false;
3367 
3368     return true;
3369   }
3370 
3371   /// See AbstractAttribute::updateImpl(...).
3372   ChangeStatus updateImpl(Attributor &A) override {
3373     // If the argument is readnone we are done as there are no accesses via the
3374     // argument.
3375     auto &MemBehaviorAA =
3376         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
3377     if (MemBehaviorAA.isAssumedReadNone()) {
3378       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
3379       return ChangeStatus::UNCHANGED;
3380     }
3381 
3382     const IRPosition &VIRP = IRPosition::value(getAssociatedValue());
3383     const auto &NoAliasAA =
3384         A.getAAFor<AANoAlias>(*this, VIRP, DepClassTy::NONE);
3385 
3386     AAResults *AAR = nullptr;
3387     if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA,
3388                                                NoAliasAA)) {
3389       LLVM_DEBUG(
3390           dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n");
3391       return ChangeStatus::UNCHANGED;
3392     }
3393 
3394     return indicatePessimisticFixpoint();
3395   }
3396 
3397   /// See AbstractAttribute::trackStatistics()
3398   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) }
3399 };
3400 
3401 /// NoAlias attribute for function return value.
3402 struct AANoAliasReturned final : AANoAliasImpl {
3403   AANoAliasReturned(const IRPosition &IRP, Attributor &A)
3404       : AANoAliasImpl(IRP, A) {}
3405 
3406   /// See AbstractAttribute::initialize(...).
3407   void initialize(Attributor &A) override {
3408     AANoAliasImpl::initialize(A);
3409     Function *F = getAssociatedFunction();
3410     if (!F || F->isDeclaration())
3411       indicatePessimisticFixpoint();
3412   }
3413 
3414   /// See AbstractAttribute::updateImpl(...).
3415   virtual ChangeStatus updateImpl(Attributor &A) override {
3416 
3417     auto CheckReturnValue = [&](Value &RV) -> bool {
3418       if (Constant *C = dyn_cast<Constant>(&RV))
3419         if (C->isNullValue() || isa<UndefValue>(C))
3420           return true;
3421 
3422       /// For now, we can only deduce noalias if we have call sites.
3423       /// FIXME: add more support.
3424       if (!isa<CallBase>(&RV))
3425         return false;
3426 
3427       const IRPosition &RVPos = IRPosition::value(RV);
3428       const auto &NoAliasAA =
3429           A.getAAFor<AANoAlias>(*this, RVPos, DepClassTy::REQUIRED);
3430       if (!NoAliasAA.isAssumedNoAlias())
3431         return false;
3432 
3433       const auto &NoCaptureAA =
3434           A.getAAFor<AANoCapture>(*this, RVPos, DepClassTy::REQUIRED);
3435       return NoCaptureAA.isAssumedNoCaptureMaybeReturned();
3436     };
3437 
3438     if (!A.checkForAllReturnedValues(CheckReturnValue, *this))
3439       return indicatePessimisticFixpoint();
3440 
3441     return ChangeStatus::UNCHANGED;
3442   }
3443 
3444   /// See AbstractAttribute::trackStatistics()
3445   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) }
3446 };
3447 
3448 /// NoAlias attribute deduction for a call site return value.
3449 struct AANoAliasCallSiteReturned final : AANoAliasImpl {
3450   AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A)
3451       : AANoAliasImpl(IRP, A) {}
3452 
3453   /// See AbstractAttribute::initialize(...).
3454   void initialize(Attributor &A) override {
3455     AANoAliasImpl::initialize(A);
3456     Function *F = getAssociatedFunction();
3457     if (!F || F->isDeclaration())
3458       indicatePessimisticFixpoint();
3459   }
3460 
3461   /// See AbstractAttribute::updateImpl(...).
3462   ChangeStatus updateImpl(Attributor &A) override {
3463     // TODO: Once we have call site specific value information we can provide
3464     //       call site specific liveness information and then it makes
3465     //       sense to specialize attributes for call sites arguments instead of
3466     //       redirecting requests to the callee argument.
3467     Function *F = getAssociatedFunction();
3468     const IRPosition &FnPos = IRPosition::returned(*F);
3469     auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos, DepClassTy::REQUIRED);
3470     return clampStateAndIndicateChange(getState(), FnAA.getState());
3471   }
3472 
3473   /// See AbstractAttribute::trackStatistics()
3474   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); }
3475 };
3476 } // namespace
3477 
3478 /// -------------------AAIsDead Function Attribute-----------------------
3479 
3480 namespace {
3481 struct AAIsDeadValueImpl : public AAIsDead {
3482   AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
3483 
3484   /// See AbstractAttribute::initialize(...).
3485   void initialize(Attributor &A) override {
3486     if (auto *Scope = getAnchorScope())
3487       if (!A.isRunOn(*Scope))
3488         indicatePessimisticFixpoint();
3489   }
3490 
3491   /// See AAIsDead::isAssumedDead().
3492   bool isAssumedDead() const override { return isAssumed(IS_DEAD); }
3493 
3494   /// See AAIsDead::isKnownDead().
3495   bool isKnownDead() const override { return isKnown(IS_DEAD); }
3496 
3497   /// See AAIsDead::isAssumedDead(BasicBlock *).
3498   bool isAssumedDead(const BasicBlock *BB) const override { return false; }
3499 
3500   /// See AAIsDead::isKnownDead(BasicBlock *).
3501   bool isKnownDead(const BasicBlock *BB) const override { return false; }
3502 
3503   /// See AAIsDead::isAssumedDead(Instruction *I).
3504   bool isAssumedDead(const Instruction *I) const override {
3505     return I == getCtxI() && isAssumedDead();
3506   }
3507 
3508   /// See AAIsDead::isKnownDead(Instruction *I).
3509   bool isKnownDead(const Instruction *I) const override {
3510     return isAssumedDead(I) && isKnownDead();
3511   }
3512 
3513   /// See AbstractAttribute::getAsStr().
3514   virtual const std::string getAsStr() const override {
3515     return isAssumedDead() ? "assumed-dead" : "assumed-live";
3516   }
3517 
3518   /// Check if all uses are assumed dead.
3519   bool areAllUsesAssumedDead(Attributor &A, Value &V) {
3520     // Callers might not check the type, void has no uses.
3521     if (V.getType()->isVoidTy() || V.use_empty())
3522       return true;
3523 
3524     // If we replace a value with a constant there are no uses left afterwards.
3525     if (!isa<Constant>(V)) {
3526       if (auto *I = dyn_cast<Instruction>(&V))
3527         if (!A.isRunOn(*I->getFunction()))
3528           return false;
3529       bool UsedAssumedInformation = false;
3530       Optional<Constant *> C =
3531           A.getAssumedConstant(V, *this, UsedAssumedInformation);
3532       if (!C.hasValue() || *C)
3533         return true;
3534     }
3535 
3536     auto UsePred = [&](const Use &U, bool &Follow) { return false; };
3537     // Explicitly set the dependence class to required because we want a long
3538     // chain of N dependent instructions to be considered live as soon as one is
3539     // without going through N update cycles. This is not required for
3540     // correctness.
3541     return A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ false,
3542                              DepClassTy::REQUIRED,
3543                              /* IgnoreDroppableUses */ false);
3544   }
3545 
3546   /// Determine if \p I is assumed to be side-effect free.
3547   bool isAssumedSideEffectFree(Attributor &A, Instruction *I) {
3548     if (!I || wouldInstructionBeTriviallyDead(I))
3549       return true;
3550 
3551     auto *CB = dyn_cast<CallBase>(I);
3552     if (!CB || isa<IntrinsicInst>(CB))
3553       return false;
3554 
3555     const IRPosition &CallIRP = IRPosition::callsite_function(*CB);
3556     const auto &NoUnwindAA =
3557         A.getAndUpdateAAFor<AANoUnwind>(*this, CallIRP, DepClassTy::NONE);
3558     if (!NoUnwindAA.isAssumedNoUnwind())
3559       return false;
3560     if (!NoUnwindAA.isKnownNoUnwind())
3561       A.recordDependence(NoUnwindAA, *this, DepClassTy::OPTIONAL);
3562 
3563     bool IsKnown;
3564     return AA::isAssumedReadOnly(A, CallIRP, *this, IsKnown);
3565   }
3566 };
3567 
3568 struct AAIsDeadFloating : public AAIsDeadValueImpl {
3569   AAIsDeadFloating(const IRPosition &IRP, Attributor &A)
3570       : AAIsDeadValueImpl(IRP, A) {}
3571 
3572   /// See AbstractAttribute::initialize(...).
3573   void initialize(Attributor &A) override {
3574     AAIsDeadValueImpl::initialize(A);
3575 
3576     if (isa<UndefValue>(getAssociatedValue())) {
3577       indicatePessimisticFixpoint();
3578       return;
3579     }
3580 
3581     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
3582     if (!isAssumedSideEffectFree(A, I)) {
3583       if (!isa_and_nonnull<StoreInst>(I))
3584         indicatePessimisticFixpoint();
3585       else
3586         removeAssumedBits(HAS_NO_EFFECT);
3587     }
3588   }
3589 
3590   bool isDeadStore(Attributor &A, StoreInst &SI) {
3591     // Lang ref now states volatile store is not UB/dead, let's skip them.
3592     if (SI.isVolatile())
3593       return false;
3594 
3595     bool UsedAssumedInformation = false;
3596     SmallSetVector<Value *, 4> PotentialCopies;
3597     if (!AA::getPotentialCopiesOfStoredValue(A, SI, PotentialCopies, *this,
3598                                              UsedAssumedInformation))
3599       return false;
3600     return llvm::all_of(PotentialCopies, [&](Value *V) {
3601       return A.isAssumedDead(IRPosition::value(*V), this, nullptr,
3602                              UsedAssumedInformation);
3603     });
3604   }
3605 
3606   /// See AbstractAttribute::getAsStr().
3607   const std::string getAsStr() const override {
3608     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
3609     if (isa_and_nonnull<StoreInst>(I))
3610       if (isValidState())
3611         return "assumed-dead-store";
3612     return AAIsDeadValueImpl::getAsStr();
3613   }
3614 
3615   /// See AbstractAttribute::updateImpl(...).
3616   ChangeStatus updateImpl(Attributor &A) override {
3617     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
3618     if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
3619       if (!isDeadStore(A, *SI))
3620         return indicatePessimisticFixpoint();
3621     } else {
3622       if (!isAssumedSideEffectFree(A, I))
3623         return indicatePessimisticFixpoint();
3624       if (!areAllUsesAssumedDead(A, getAssociatedValue()))
3625         return indicatePessimisticFixpoint();
3626     }
3627     return ChangeStatus::UNCHANGED;
3628   }
3629 
3630   bool isRemovableStore() const override {
3631     return isAssumed(IS_REMOVABLE) && isa<StoreInst>(&getAssociatedValue());
3632   }
3633 
3634   /// See AbstractAttribute::manifest(...).
3635   ChangeStatus manifest(Attributor &A) override {
3636     Value &V = getAssociatedValue();
3637     if (auto *I = dyn_cast<Instruction>(&V)) {
3638       // If we get here we basically know the users are all dead. We check if
3639       // isAssumedSideEffectFree returns true here again because it might not be
3640       // the case and only the users are dead but the instruction (=call) is
3641       // still needed.
3642       if (isa<StoreInst>(I) ||
3643           (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I))) {
3644         A.deleteAfterManifest(*I);
3645         return ChangeStatus::CHANGED;
3646       }
3647     }
3648     return ChangeStatus::UNCHANGED;
3649   }
3650 
3651   /// See AbstractAttribute::trackStatistics()
3652   void trackStatistics() const override {
3653     STATS_DECLTRACK_FLOATING_ATTR(IsDead)
3654   }
3655 };
3656 
3657 struct AAIsDeadArgument : public AAIsDeadFloating {
3658   AAIsDeadArgument(const IRPosition &IRP, Attributor &A)
3659       : AAIsDeadFloating(IRP, A) {}
3660 
3661   /// See AbstractAttribute::initialize(...).
3662   void initialize(Attributor &A) override {
3663     AAIsDeadFloating::initialize(A);
3664     if (!A.isFunctionIPOAmendable(*getAnchorScope()))
3665       indicatePessimisticFixpoint();
3666   }
3667 
3668   /// See AbstractAttribute::manifest(...).
3669   ChangeStatus manifest(Attributor &A) override {
3670     Argument &Arg = *getAssociatedArgument();
3671     if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {}))
3672       if (A.registerFunctionSignatureRewrite(
3673               Arg, /* ReplacementTypes */ {},
3674               Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{},
3675               Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) {
3676         return ChangeStatus::CHANGED;
3677       }
3678     return ChangeStatus::UNCHANGED;
3679   }
3680 
3681   /// See AbstractAttribute::trackStatistics()
3682   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) }
3683 };
3684 
3685 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl {
3686   AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A)
3687       : AAIsDeadValueImpl(IRP, A) {}
3688 
3689   /// See AbstractAttribute::initialize(...).
3690   void initialize(Attributor &A) override {
3691     AAIsDeadValueImpl::initialize(A);
3692     if (isa<UndefValue>(getAssociatedValue()))
3693       indicatePessimisticFixpoint();
3694   }
3695 
3696   /// See AbstractAttribute::updateImpl(...).
3697   ChangeStatus updateImpl(Attributor &A) override {
3698     // TODO: Once we have call site specific value information we can provide
3699     //       call site specific liveness information and then it makes
3700     //       sense to specialize attributes for call sites arguments instead of
3701     //       redirecting requests to the callee argument.
3702     Argument *Arg = getAssociatedArgument();
3703     if (!Arg)
3704       return indicatePessimisticFixpoint();
3705     const IRPosition &ArgPos = IRPosition::argument(*Arg);
3706     auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos, DepClassTy::REQUIRED);
3707     return clampStateAndIndicateChange(getState(), ArgAA.getState());
3708   }
3709 
3710   /// See AbstractAttribute::manifest(...).
3711   ChangeStatus manifest(Attributor &A) override {
3712     CallBase &CB = cast<CallBase>(getAnchorValue());
3713     Use &U = CB.getArgOperandUse(getCallSiteArgNo());
3714     assert(!isa<UndefValue>(U.get()) &&
3715            "Expected undef values to be filtered out!");
3716     UndefValue &UV = *UndefValue::get(U->getType());
3717     if (A.changeUseAfterManifest(U, UV))
3718       return ChangeStatus::CHANGED;
3719     return ChangeStatus::UNCHANGED;
3720   }
3721 
3722   /// See AbstractAttribute::trackStatistics()
3723   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) }
3724 };
3725 
3726 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating {
3727   AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A)
3728       : AAIsDeadFloating(IRP, A) {}
3729 
3730   /// See AAIsDead::isAssumedDead().
3731   bool isAssumedDead() const override {
3732     return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
3733   }
3734 
3735   /// See AbstractAttribute::initialize(...).
3736   void initialize(Attributor &A) override {
3737     AAIsDeadFloating::initialize(A);
3738     if (isa<UndefValue>(getAssociatedValue())) {
3739       indicatePessimisticFixpoint();
3740       return;
3741     }
3742 
3743     // We track this separately as a secondary state.
3744     IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI());
3745   }
3746 
3747   /// See AbstractAttribute::updateImpl(...).
3748   ChangeStatus updateImpl(Attributor &A) override {
3749     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3750     if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) {
3751       IsAssumedSideEffectFree = false;
3752       Changed = ChangeStatus::CHANGED;
3753     }
3754     if (!areAllUsesAssumedDead(A, getAssociatedValue()))
3755       return indicatePessimisticFixpoint();
3756     return Changed;
3757   }
3758 
3759   /// See AbstractAttribute::trackStatistics()
3760   void trackStatistics() const override {
3761     if (IsAssumedSideEffectFree)
3762       STATS_DECLTRACK_CSRET_ATTR(IsDead)
3763     else
3764       STATS_DECLTRACK_CSRET_ATTR(UnusedResult)
3765   }
3766 
3767   /// See AbstractAttribute::getAsStr().
3768   const std::string getAsStr() const override {
3769     return isAssumedDead()
3770                ? "assumed-dead"
3771                : (getAssumed() ? "assumed-dead-users" : "assumed-live");
3772   }
3773 
3774 private:
3775   bool IsAssumedSideEffectFree = true;
3776 };
3777 
3778 struct AAIsDeadReturned : public AAIsDeadValueImpl {
3779   AAIsDeadReturned(const IRPosition &IRP, Attributor &A)
3780       : AAIsDeadValueImpl(IRP, A) {}
3781 
3782   /// See AbstractAttribute::updateImpl(...).
3783   ChangeStatus updateImpl(Attributor &A) override {
3784 
3785     bool UsedAssumedInformation = false;
3786     A.checkForAllInstructions([](Instruction &) { return true; }, *this,
3787                               {Instruction::Ret}, UsedAssumedInformation);
3788 
3789     auto PredForCallSite = [&](AbstractCallSite ACS) {
3790       if (ACS.isCallbackCall() || !ACS.getInstruction())
3791         return false;
3792       return areAllUsesAssumedDead(A, *ACS.getInstruction());
3793     };
3794 
3795     if (!A.checkForAllCallSites(PredForCallSite, *this, true,
3796                                 UsedAssumedInformation))
3797       return indicatePessimisticFixpoint();
3798 
3799     return ChangeStatus::UNCHANGED;
3800   }
3801 
3802   /// See AbstractAttribute::manifest(...).
3803   ChangeStatus manifest(Attributor &A) override {
3804     // TODO: Rewrite the signature to return void?
3805     bool AnyChange = false;
3806     UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType());
3807     auto RetInstPred = [&](Instruction &I) {
3808       ReturnInst &RI = cast<ReturnInst>(I);
3809       if (!isa<UndefValue>(RI.getReturnValue()))
3810         AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV);
3811       return true;
3812     };
3813     bool UsedAssumedInformation = false;
3814     A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret},
3815                               UsedAssumedInformation);
3816     return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
3817   }
3818 
3819   /// See AbstractAttribute::trackStatistics()
3820   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) }
3821 };
3822 
3823 struct AAIsDeadFunction : public AAIsDead {
3824   AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {}
3825 
3826   /// See AbstractAttribute::initialize(...).
3827   void initialize(Attributor &A) override {
3828     Function *F = getAnchorScope();
3829     if (!F || F->isDeclaration() || !A.isRunOn(*F)) {
3830       indicatePessimisticFixpoint();
3831       return;
3832     }
3833     ToBeExploredFrom.insert(&F->getEntryBlock().front());
3834     assumeLive(A, F->getEntryBlock());
3835   }
3836 
3837   /// See AbstractAttribute::getAsStr().
3838   const std::string getAsStr() const override {
3839     return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" +
3840            std::to_string(getAnchorScope()->size()) + "][#TBEP " +
3841            std::to_string(ToBeExploredFrom.size()) + "][#KDE " +
3842            std::to_string(KnownDeadEnds.size()) + "]";
3843   }
3844 
3845   /// See AbstractAttribute::manifest(...).
3846   ChangeStatus manifest(Attributor &A) override {
3847     assert(getState().isValidState() &&
3848            "Attempted to manifest an invalid state!");
3849 
3850     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
3851     Function &F = *getAnchorScope();
3852 
3853     if (AssumedLiveBlocks.empty()) {
3854       A.deleteAfterManifest(F);
3855       return ChangeStatus::CHANGED;
3856     }
3857 
3858     // Flag to determine if we can change an invoke to a call assuming the
3859     // callee is nounwind. This is not possible if the personality of the
3860     // function allows to catch asynchronous exceptions.
3861     bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
3862 
3863     KnownDeadEnds.set_union(ToBeExploredFrom);
3864     for (const Instruction *DeadEndI : KnownDeadEnds) {
3865       auto *CB = dyn_cast<CallBase>(DeadEndI);
3866       if (!CB)
3867         continue;
3868       const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>(
3869           *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
3870       bool MayReturn = !NoReturnAA.isAssumedNoReturn();
3871       if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
3872         continue;
3873 
3874       if (auto *II = dyn_cast<InvokeInst>(DeadEndI))
3875         A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II));
3876       else
3877         A.changeToUnreachableAfterManifest(
3878             const_cast<Instruction *>(DeadEndI->getNextNode()));
3879       HasChanged = ChangeStatus::CHANGED;
3880     }
3881 
3882     STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted.");
3883     for (BasicBlock &BB : F)
3884       if (!AssumedLiveBlocks.count(&BB)) {
3885         A.deleteAfterManifest(BB);
3886         ++BUILD_STAT_NAME(AAIsDead, BasicBlock);
3887         HasChanged = ChangeStatus::CHANGED;
3888       }
3889 
3890     return HasChanged;
3891   }
3892 
3893   /// See AbstractAttribute::updateImpl(...).
3894   ChangeStatus updateImpl(Attributor &A) override;
3895 
3896   bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override {
3897     assert(From->getParent() == getAnchorScope() &&
3898            To->getParent() == getAnchorScope() &&
3899            "Used AAIsDead of the wrong function");
3900     return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To));
3901   }
3902 
3903   /// See AbstractAttribute::trackStatistics()
3904   void trackStatistics() const override {}
3905 
3906   /// Returns true if the function is assumed dead.
3907   bool isAssumedDead() const override { return false; }
3908 
3909   /// See AAIsDead::isKnownDead().
3910   bool isKnownDead() const override { return false; }
3911 
3912   /// See AAIsDead::isAssumedDead(BasicBlock *).
3913   bool isAssumedDead(const BasicBlock *BB) const override {
3914     assert(BB->getParent() == getAnchorScope() &&
3915            "BB must be in the same anchor scope function.");
3916 
3917     if (!getAssumed())
3918       return false;
3919     return !AssumedLiveBlocks.count(BB);
3920   }
3921 
3922   /// See AAIsDead::isKnownDead(BasicBlock *).
3923   bool isKnownDead(const BasicBlock *BB) const override {
3924     return getKnown() && isAssumedDead(BB);
3925   }
3926 
3927   /// See AAIsDead::isAssumed(Instruction *I).
3928   bool isAssumedDead(const Instruction *I) const override {
3929     assert(I->getParent()->getParent() == getAnchorScope() &&
3930            "Instruction must be in the same anchor scope function.");
3931 
3932     if (!getAssumed())
3933       return false;
3934 
3935     // If it is not in AssumedLiveBlocks then it for sure dead.
3936     // Otherwise, it can still be after noreturn call in a live block.
3937     if (!AssumedLiveBlocks.count(I->getParent()))
3938       return true;
3939 
3940     // If it is not after a liveness barrier it is live.
3941     const Instruction *PrevI = I->getPrevNode();
3942     while (PrevI) {
3943       if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
3944         return true;
3945       PrevI = PrevI->getPrevNode();
3946     }
3947     return false;
3948   }
3949 
3950   /// See AAIsDead::isKnownDead(Instruction *I).
3951   bool isKnownDead(const Instruction *I) const override {
3952     return getKnown() && isAssumedDead(I);
3953   }
3954 
3955   /// Assume \p BB is (partially) live now and indicate to the Attributor \p A
3956   /// that internal function called from \p BB should now be looked at.
3957   bool assumeLive(Attributor &A, const BasicBlock &BB) {
3958     if (!AssumedLiveBlocks.insert(&BB).second)
3959       return false;
3960 
3961     // We assume that all of BB is (probably) live now and if there are calls to
3962     // internal functions we will assume that those are now live as well. This
3963     // is a performance optimization for blocks with calls to a lot of internal
3964     // functions. It can however cause dead functions to be treated as live.
3965     for (const Instruction &I : BB)
3966       if (const auto *CB = dyn_cast<CallBase>(&I))
3967         if (const Function *F = CB->getCalledFunction())
3968           if (F->hasLocalLinkage())
3969             A.markLiveInternalFunction(*F);
3970     return true;
3971   }
3972 
3973   /// Collection of instructions that need to be explored again, e.g., we
3974   /// did assume they do not transfer control to (one of their) successors.
3975   SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
3976 
3977   /// Collection of instructions that are known to not transfer control.
3978   SmallSetVector<const Instruction *, 8> KnownDeadEnds;
3979 
3980   /// Collection of all assumed live edges
3981   DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
3982 
3983   /// Collection of all assumed live BasicBlocks.
3984   DenseSet<const BasicBlock *> AssumedLiveBlocks;
3985 };
3986 
3987 static bool
3988 identifyAliveSuccessors(Attributor &A, const CallBase &CB,
3989                         AbstractAttribute &AA,
3990                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
3991   const IRPosition &IPos = IRPosition::callsite_function(CB);
3992 
3993   const auto &NoReturnAA =
3994       A.getAndUpdateAAFor<AANoReturn>(AA, IPos, DepClassTy::OPTIONAL);
3995   if (NoReturnAA.isAssumedNoReturn())
3996     return !NoReturnAA.isKnownNoReturn();
3997   if (CB.isTerminator())
3998     AliveSuccessors.push_back(&CB.getSuccessor(0)->front());
3999   else
4000     AliveSuccessors.push_back(CB.getNextNode());
4001   return false;
4002 }
4003 
4004 static bool
4005 identifyAliveSuccessors(Attributor &A, const InvokeInst &II,
4006                         AbstractAttribute &AA,
4007                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4008   bool UsedAssumedInformation =
4009       identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
4010 
4011   // First, determine if we can change an invoke to a call assuming the
4012   // callee is nounwind. This is not possible if the personality of the
4013   // function allows to catch asynchronous exceptions.
4014   if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) {
4015     AliveSuccessors.push_back(&II.getUnwindDest()->front());
4016   } else {
4017     const IRPosition &IPos = IRPosition::callsite_function(II);
4018     const auto &AANoUnw =
4019         A.getAndUpdateAAFor<AANoUnwind>(AA, IPos, DepClassTy::OPTIONAL);
4020     if (AANoUnw.isAssumedNoUnwind()) {
4021       UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
4022     } else {
4023       AliveSuccessors.push_back(&II.getUnwindDest()->front());
4024     }
4025   }
4026   return UsedAssumedInformation;
4027 }
4028 
4029 static bool
4030 identifyAliveSuccessors(Attributor &A, const BranchInst &BI,
4031                         AbstractAttribute &AA,
4032                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4033   bool UsedAssumedInformation = false;
4034   if (BI.getNumSuccessors() == 1) {
4035     AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
4036   } else {
4037     Optional<Constant *> C =
4038         A.getAssumedConstant(*BI.getCondition(), AA, UsedAssumedInformation);
4039     if (!C.hasValue() || isa_and_nonnull<UndefValue>(C.getValue())) {
4040       // No value yet, assume both edges are dead.
4041     } else if (isa_and_nonnull<ConstantInt>(*C)) {
4042       const BasicBlock *SuccBB =
4043           BI.getSuccessor(1 - cast<ConstantInt>(*C)->getValue().getZExtValue());
4044       AliveSuccessors.push_back(&SuccBB->front());
4045     } else {
4046       AliveSuccessors.push_back(&BI.getSuccessor(0)->front());
4047       AliveSuccessors.push_back(&BI.getSuccessor(1)->front());
4048       UsedAssumedInformation = false;
4049     }
4050   }
4051   return UsedAssumedInformation;
4052 }
4053 
4054 static bool
4055 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI,
4056                         AbstractAttribute &AA,
4057                         SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4058   bool UsedAssumedInformation = false;
4059   Optional<Constant *> C =
4060       A.getAssumedConstant(*SI.getCondition(), AA, UsedAssumedInformation);
4061   if (!C.hasValue() || isa_and_nonnull<UndefValue>(C.getValue())) {
4062     // No value yet, assume all edges are dead.
4063   } else if (isa_and_nonnull<ConstantInt>(C.getValue())) {
4064     for (auto &CaseIt : SI.cases()) {
4065       if (CaseIt.getCaseValue() == C.getValue()) {
4066         AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front());
4067         return UsedAssumedInformation;
4068       }
4069     }
4070     AliveSuccessors.push_back(&SI.getDefaultDest()->front());
4071     return UsedAssumedInformation;
4072   } else {
4073     for (const BasicBlock *SuccBB : successors(SI.getParent()))
4074       AliveSuccessors.push_back(&SuccBB->front());
4075   }
4076   return UsedAssumedInformation;
4077 }
4078 
4079 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
4080   ChangeStatus Change = ChangeStatus::UNCHANGED;
4081 
4082   LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/"
4083                     << getAnchorScope()->size() << "] BBs and "
4084                     << ToBeExploredFrom.size() << " exploration points and "
4085                     << KnownDeadEnds.size() << " known dead ends\n");
4086 
4087   // Copy and clear the list of instructions we need to explore from. It is
4088   // refilled with instructions the next update has to look at.
4089   SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(),
4090                                                ToBeExploredFrom.end());
4091   decltype(ToBeExploredFrom) NewToBeExploredFrom;
4092 
4093   SmallVector<const Instruction *, 8> AliveSuccessors;
4094   while (!Worklist.empty()) {
4095     const Instruction *I = Worklist.pop_back_val();
4096     LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n");
4097 
4098     // Fast forward for uninteresting instructions. We could look for UB here
4099     // though.
4100     while (!I->isTerminator() && !isa<CallBase>(I))
4101       I = I->getNextNode();
4102 
4103     AliveSuccessors.clear();
4104 
4105     bool UsedAssumedInformation = false;
4106     switch (I->getOpcode()) {
4107     // TODO: look for (assumed) UB to backwards propagate "deadness".
4108     default:
4109       assert(I->isTerminator() &&
4110              "Expected non-terminators to be handled already!");
4111       for (const BasicBlock *SuccBB : successors(I->getParent()))
4112         AliveSuccessors.push_back(&SuccBB->front());
4113       break;
4114     case Instruction::Call:
4115       UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
4116                                                        *this, AliveSuccessors);
4117       break;
4118     case Instruction::Invoke:
4119       UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
4120                                                        *this, AliveSuccessors);
4121       break;
4122     case Instruction::Br:
4123       UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
4124                                                        *this, AliveSuccessors);
4125       break;
4126     case Instruction::Switch:
4127       UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
4128                                                        *this, AliveSuccessors);
4129       break;
4130     }
4131 
4132     if (UsedAssumedInformation) {
4133       NewToBeExploredFrom.insert(I);
4134     } else if (AliveSuccessors.empty() ||
4135                (I->isTerminator() &&
4136                 AliveSuccessors.size() < I->getNumSuccessors())) {
4137       if (KnownDeadEnds.insert(I))
4138         Change = ChangeStatus::CHANGED;
4139     }
4140 
4141     LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: "
4142                       << AliveSuccessors.size() << " UsedAssumedInformation: "
4143                       << UsedAssumedInformation << "\n");
4144 
4145     for (const Instruction *AliveSuccessor : AliveSuccessors) {
4146       if (!I->isTerminator()) {
4147         assert(AliveSuccessors.size() == 1 &&
4148                "Non-terminator expected to have a single successor!");
4149         Worklist.push_back(AliveSuccessor);
4150       } else {
4151         // record the assumed live edge
4152         auto Edge = std::make_pair(I->getParent(), AliveSuccessor->getParent());
4153         if (AssumedLiveEdges.insert(Edge).second)
4154           Change = ChangeStatus::CHANGED;
4155         if (assumeLive(A, *AliveSuccessor->getParent()))
4156           Worklist.push_back(AliveSuccessor);
4157       }
4158     }
4159   }
4160 
4161   // Check if the content of ToBeExploredFrom changed, ignore the order.
4162   if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() ||
4163       llvm::any_of(NewToBeExploredFrom, [&](const Instruction *I) {
4164         return !ToBeExploredFrom.count(I);
4165       })) {
4166     Change = ChangeStatus::CHANGED;
4167     ToBeExploredFrom = std::move(NewToBeExploredFrom);
4168   }
4169 
4170   // If we know everything is live there is no need to query for liveness.
4171   // Instead, indicating a pessimistic fixpoint will cause the state to be
4172   // "invalid" and all queries to be answered conservatively without lookups.
4173   // To be in this state we have to (1) finished the exploration and (3) not
4174   // discovered any non-trivial dead end and (2) not ruled unreachable code
4175   // dead.
4176   if (ToBeExploredFrom.empty() &&
4177       getAnchorScope()->size() == AssumedLiveBlocks.size() &&
4178       llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) {
4179         return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
4180       }))
4181     return indicatePessimisticFixpoint();
4182   return Change;
4183 }
4184 
4185 /// Liveness information for a call sites.
4186 struct AAIsDeadCallSite final : AAIsDeadFunction {
4187   AAIsDeadCallSite(const IRPosition &IRP, Attributor &A)
4188       : AAIsDeadFunction(IRP, A) {}
4189 
4190   /// See AbstractAttribute::initialize(...).
4191   void initialize(Attributor &A) override {
4192     // TODO: Once we have call site specific value information we can provide
4193     //       call site specific liveness information and then it makes
4194     //       sense to specialize attributes for call sites instead of
4195     //       redirecting requests to the callee.
4196     llvm_unreachable("Abstract attributes for liveness are not "
4197                      "supported for call sites yet!");
4198   }
4199 
4200   /// See AbstractAttribute::updateImpl(...).
4201   ChangeStatus updateImpl(Attributor &A) override {
4202     return indicatePessimisticFixpoint();
4203   }
4204 
4205   /// See AbstractAttribute::trackStatistics()
4206   void trackStatistics() const override {}
4207 };
4208 } // namespace
4209 
4210 /// -------------------- Dereferenceable Argument Attribute --------------------
4211 
4212 namespace {
4213 struct AADereferenceableImpl : AADereferenceable {
4214   AADereferenceableImpl(const IRPosition &IRP, Attributor &A)
4215       : AADereferenceable(IRP, A) {}
4216   using StateType = DerefState;
4217 
4218   /// See AbstractAttribute::initialize(...).
4219   void initialize(Attributor &A) override {
4220     SmallVector<Attribute, 4> Attrs;
4221     getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
4222              Attrs, /* IgnoreSubsumingPositions */ false, &A);
4223     for (const Attribute &Attr : Attrs)
4224       takeKnownDerefBytesMaximum(Attr.getValueAsInt());
4225 
4226     const IRPosition &IRP = this->getIRPosition();
4227     NonNullAA = &A.getAAFor<AANonNull>(*this, IRP, DepClassTy::NONE);
4228 
4229     bool CanBeNull, CanBeFreed;
4230     takeKnownDerefBytesMaximum(
4231         IRP.getAssociatedValue().getPointerDereferenceableBytes(
4232             A.getDataLayout(), CanBeNull, CanBeFreed));
4233 
4234     bool IsFnInterface = IRP.isFnInterfaceKind();
4235     Function *FnScope = IRP.getAnchorScope();
4236     if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope))) {
4237       indicatePessimisticFixpoint();
4238       return;
4239     }
4240 
4241     if (Instruction *CtxI = getCtxI())
4242       followUsesInMBEC(*this, A, getState(), *CtxI);
4243   }
4244 
4245   /// See AbstractAttribute::getState()
4246   /// {
4247   StateType &getState() override { return *this; }
4248   const StateType &getState() const override { return *this; }
4249   /// }
4250 
4251   /// Helper function for collecting accessed bytes in must-be-executed-context
4252   void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I,
4253                               DerefState &State) {
4254     const Value *UseV = U->get();
4255     if (!UseV->getType()->isPointerTy())
4256       return;
4257 
4258     Optional<MemoryLocation> Loc = MemoryLocation::getOrNone(I);
4259     if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() || I->isVolatile())
4260       return;
4261 
4262     int64_t Offset;
4263     const Value *Base = GetPointerBaseWithConstantOffset(
4264         Loc->Ptr, Offset, A.getDataLayout(), /*AllowNonInbounds*/ true);
4265     if (Base && Base == &getAssociatedValue())
4266       State.addAccessedBytes(Offset, Loc->Size.getValue());
4267   }
4268 
4269   /// See followUsesInMBEC
4270   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
4271                        AADereferenceable::StateType &State) {
4272     bool IsNonNull = false;
4273     bool TrackUse = false;
4274     int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
4275         A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse);
4276     LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes
4277                       << " for instruction " << *I << "\n");
4278 
4279     addAccessedBytesForUse(A, U, I, State);
4280     State.takeKnownDerefBytesMaximum(DerefBytes);
4281     return TrackUse;
4282   }
4283 
4284   /// See AbstractAttribute::manifest(...).
4285   ChangeStatus manifest(Attributor &A) override {
4286     ChangeStatus Change = AADereferenceable::manifest(A);
4287     if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) {
4288       removeAttrs({Attribute::DereferenceableOrNull});
4289       return ChangeStatus::CHANGED;
4290     }
4291     return Change;
4292   }
4293 
4294   void getDeducedAttributes(LLVMContext &Ctx,
4295                             SmallVectorImpl<Attribute> &Attrs) const override {
4296     // TODO: Add *_globally support
4297     if (isAssumedNonNull())
4298       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
4299           Ctx, getAssumedDereferenceableBytes()));
4300     else
4301       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
4302           Ctx, getAssumedDereferenceableBytes()));
4303   }
4304 
4305   /// See AbstractAttribute::getAsStr().
4306   const std::string getAsStr() const override {
4307     if (!getAssumedDereferenceableBytes())
4308       return "unknown-dereferenceable";
4309     return std::string("dereferenceable") +
4310            (isAssumedNonNull() ? "" : "_or_null") +
4311            (isAssumedGlobal() ? "_globally" : "") + "<" +
4312            std::to_string(getKnownDereferenceableBytes()) + "-" +
4313            std::to_string(getAssumedDereferenceableBytes()) + ">";
4314   }
4315 };
4316 
4317 /// Dereferenceable attribute for a floating value.
4318 struct AADereferenceableFloating : AADereferenceableImpl {
4319   AADereferenceableFloating(const IRPosition &IRP, Attributor &A)
4320       : AADereferenceableImpl(IRP, A) {}
4321 
4322   /// See AbstractAttribute::updateImpl(...).
4323   ChangeStatus updateImpl(Attributor &A) override {
4324     const DataLayout &DL = A.getDataLayout();
4325 
4326     auto VisitValueCB = [&](const Value &V, const Instruction *, DerefState &T,
4327                             bool Stripped) -> bool {
4328       unsigned IdxWidth =
4329           DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
4330       APInt Offset(IdxWidth, 0);
4331       const Value *Base = stripAndAccumulateOffsets(
4332           A, *this, &V, DL, Offset, /* GetMinOffset */ false,
4333           /* AllowNonInbounds */ true);
4334 
4335       const auto &AA = A.getAAFor<AADereferenceable>(
4336           *this, IRPosition::value(*Base), DepClassTy::REQUIRED);
4337       int64_t DerefBytes = 0;
4338       if (!Stripped && this == &AA) {
4339         // Use IR information if we did not strip anything.
4340         // TODO: track globally.
4341         bool CanBeNull, CanBeFreed;
4342         DerefBytes =
4343             Base->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
4344         T.GlobalState.indicatePessimisticFixpoint();
4345       } else {
4346         const DerefState &DS = AA.getState();
4347         DerefBytes = DS.DerefBytesState.getAssumed();
4348         T.GlobalState &= DS.GlobalState;
4349       }
4350 
4351       // For now we do not try to "increase" dereferenceability due to negative
4352       // indices as we first have to come up with code to deal with loops and
4353       // for overflows of the dereferenceable bytes.
4354       int64_t OffsetSExt = Offset.getSExtValue();
4355       if (OffsetSExt < 0)
4356         OffsetSExt = 0;
4357 
4358       T.takeAssumedDerefBytesMinimum(
4359           std::max(int64_t(0), DerefBytes - OffsetSExt));
4360 
4361       if (this == &AA) {
4362         if (!Stripped) {
4363           // If nothing was stripped IR information is all we got.
4364           T.takeKnownDerefBytesMaximum(
4365               std::max(int64_t(0), DerefBytes - OffsetSExt));
4366           T.indicatePessimisticFixpoint();
4367         } else if (OffsetSExt > 0) {
4368           // If something was stripped but there is circular reasoning we look
4369           // for the offset. If it is positive we basically decrease the
4370           // dereferenceable bytes in a circluar loop now, which will simply
4371           // drive them down to the known value in a very slow way which we
4372           // can accelerate.
4373           T.indicatePessimisticFixpoint();
4374         }
4375       }
4376 
4377       return T.isValidState();
4378     };
4379 
4380     DerefState T;
4381     bool UsedAssumedInformation = false;
4382     if (!genericValueTraversal<DerefState>(A, getIRPosition(), *this, T,
4383                                            VisitValueCB, getCtxI(),
4384                                            UsedAssumedInformation))
4385       return indicatePessimisticFixpoint();
4386 
4387     return clampStateAndIndicateChange(getState(), T);
4388   }
4389 
4390   /// See AbstractAttribute::trackStatistics()
4391   void trackStatistics() const override {
4392     STATS_DECLTRACK_FLOATING_ATTR(dereferenceable)
4393   }
4394 };
4395 
4396 /// Dereferenceable attribute for a return value.
4397 struct AADereferenceableReturned final
4398     : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
4399   AADereferenceableReturned(const IRPosition &IRP, Attributor &A)
4400       : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>(
4401             IRP, A) {}
4402 
4403   /// See AbstractAttribute::trackStatistics()
4404   void trackStatistics() const override {
4405     STATS_DECLTRACK_FNRET_ATTR(dereferenceable)
4406   }
4407 };
4408 
4409 /// Dereferenceable attribute for an argument
4410 struct AADereferenceableArgument final
4411     : AAArgumentFromCallSiteArguments<AADereferenceable,
4412                                       AADereferenceableImpl> {
4413   using Base =
4414       AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
4415   AADereferenceableArgument(const IRPosition &IRP, Attributor &A)
4416       : Base(IRP, A) {}
4417 
4418   /// See AbstractAttribute::trackStatistics()
4419   void trackStatistics() const override {
4420     STATS_DECLTRACK_ARG_ATTR(dereferenceable)
4421   }
4422 };
4423 
4424 /// Dereferenceable attribute for a call site argument.
4425 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
4426   AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A)
4427       : AADereferenceableFloating(IRP, A) {}
4428 
4429   /// See AbstractAttribute::trackStatistics()
4430   void trackStatistics() const override {
4431     STATS_DECLTRACK_CSARG_ATTR(dereferenceable)
4432   }
4433 };
4434 
4435 /// Dereferenceable attribute deduction for a call site return value.
4436 struct AADereferenceableCallSiteReturned final
4437     : AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl> {
4438   using Base =
4439       AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl>;
4440   AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A)
4441       : Base(IRP, A) {}
4442 
4443   /// See AbstractAttribute::trackStatistics()
4444   void trackStatistics() const override {
4445     STATS_DECLTRACK_CS_ATTR(dereferenceable);
4446   }
4447 };
4448 } // namespace
4449 
4450 // ------------------------ Align Argument Attribute ------------------------
4451 
4452 namespace {
4453 static unsigned getKnownAlignForUse(Attributor &A, AAAlign &QueryingAA,
4454                                     Value &AssociatedValue, const Use *U,
4455                                     const Instruction *I, bool &TrackUse) {
4456   // We need to follow common pointer manipulation uses to the accesses they
4457   // feed into.
4458   if (isa<CastInst>(I)) {
4459     // Follow all but ptr2int casts.
4460     TrackUse = !isa<PtrToIntInst>(I);
4461     return 0;
4462   }
4463   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
4464     if (GEP->hasAllConstantIndices())
4465       TrackUse = true;
4466     return 0;
4467   }
4468 
4469   MaybeAlign MA;
4470   if (const auto *CB = dyn_cast<CallBase>(I)) {
4471     if (CB->isBundleOperand(U) || CB->isCallee(U))
4472       return 0;
4473 
4474     unsigned ArgNo = CB->getArgOperandNo(U);
4475     IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo);
4476     // As long as we only use known information there is no need to track
4477     // dependences here.
4478     auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP, DepClassTy::NONE);
4479     MA = MaybeAlign(AlignAA.getKnownAlign());
4480   }
4481 
4482   const DataLayout &DL = A.getDataLayout();
4483   const Value *UseV = U->get();
4484   if (auto *SI = dyn_cast<StoreInst>(I)) {
4485     if (SI->getPointerOperand() == UseV)
4486       MA = SI->getAlign();
4487   } else if (auto *LI = dyn_cast<LoadInst>(I)) {
4488     if (LI->getPointerOperand() == UseV)
4489       MA = LI->getAlign();
4490   }
4491 
4492   if (!MA || *MA <= QueryingAA.getKnownAlign())
4493     return 0;
4494 
4495   unsigned Alignment = MA->value();
4496   int64_t Offset;
4497 
4498   if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) {
4499     if (Base == &AssociatedValue) {
4500       // BasePointerAddr + Offset = Alignment * Q for some integer Q.
4501       // So we can say that the maximum power of two which is a divisor of
4502       // gcd(Offset, Alignment) is an alignment.
4503 
4504       uint32_t gcd =
4505           greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment);
4506       Alignment = llvm::PowerOf2Floor(gcd);
4507     }
4508   }
4509 
4510   return Alignment;
4511 }
4512 
4513 struct AAAlignImpl : AAAlign {
4514   AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {}
4515 
4516   /// See AbstractAttribute::initialize(...).
4517   void initialize(Attributor &A) override {
4518     SmallVector<Attribute, 4> Attrs;
4519     getAttrs({Attribute::Alignment}, Attrs);
4520     for (const Attribute &Attr : Attrs)
4521       takeKnownMaximum(Attr.getValueAsInt());
4522 
4523     Value &V = getAssociatedValue();
4524     takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value());
4525 
4526     if (getIRPosition().isFnInterfaceKind() &&
4527         (!getAnchorScope() ||
4528          !A.isFunctionIPOAmendable(*getAssociatedFunction()))) {
4529       indicatePessimisticFixpoint();
4530       return;
4531     }
4532 
4533     if (Instruction *CtxI = getCtxI())
4534       followUsesInMBEC(*this, A, getState(), *CtxI);
4535   }
4536 
4537   /// See AbstractAttribute::manifest(...).
4538   ChangeStatus manifest(Attributor &A) override {
4539     ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED;
4540 
4541     // Check for users that allow alignment annotations.
4542     Value &AssociatedValue = getAssociatedValue();
4543     for (const Use &U : AssociatedValue.uses()) {
4544       if (auto *SI = dyn_cast<StoreInst>(U.getUser())) {
4545         if (SI->getPointerOperand() == &AssociatedValue)
4546           if (SI->getAlignment() < getAssumedAlign()) {
4547             STATS_DECLTRACK(AAAlign, Store,
4548                             "Number of times alignment added to a store");
4549             SI->setAlignment(Align(getAssumedAlign()));
4550             LoadStoreChanged = ChangeStatus::CHANGED;
4551           }
4552       } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) {
4553         if (LI->getPointerOperand() == &AssociatedValue)
4554           if (LI->getAlignment() < getAssumedAlign()) {
4555             LI->setAlignment(Align(getAssumedAlign()));
4556             STATS_DECLTRACK(AAAlign, Load,
4557                             "Number of times alignment added to a load");
4558             LoadStoreChanged = ChangeStatus::CHANGED;
4559           }
4560       }
4561     }
4562 
4563     ChangeStatus Changed = AAAlign::manifest(A);
4564 
4565     Align InheritAlign =
4566         getAssociatedValue().getPointerAlignment(A.getDataLayout());
4567     if (InheritAlign >= getAssumedAlign())
4568       return LoadStoreChanged;
4569     return Changed | LoadStoreChanged;
4570   }
4571 
4572   // TODO: Provide a helper to determine the implied ABI alignment and check in
4573   //       the existing manifest method and a new one for AAAlignImpl that value
4574   //       to avoid making the alignment explicit if it did not improve.
4575 
4576   /// See AbstractAttribute::getDeducedAttributes
4577   virtual void
4578   getDeducedAttributes(LLVMContext &Ctx,
4579                        SmallVectorImpl<Attribute> &Attrs) const override {
4580     if (getAssumedAlign() > 1)
4581       Attrs.emplace_back(
4582           Attribute::getWithAlignment(Ctx, Align(getAssumedAlign())));
4583   }
4584 
4585   /// See followUsesInMBEC
4586   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
4587                        AAAlign::StateType &State) {
4588     bool TrackUse = false;
4589 
4590     unsigned int KnownAlign =
4591         getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse);
4592     State.takeKnownMaximum(KnownAlign);
4593 
4594     return TrackUse;
4595   }
4596 
4597   /// See AbstractAttribute::getAsStr().
4598   const std::string getAsStr() const override {
4599     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
4600                                 "-" + std::to_string(getAssumedAlign()) + ">")
4601                              : "unknown-align";
4602   }
4603 };
4604 
4605 /// Align attribute for a floating value.
4606 struct AAAlignFloating : AAAlignImpl {
4607   AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {}
4608 
4609   /// See AbstractAttribute::updateImpl(...).
4610   ChangeStatus updateImpl(Attributor &A) override {
4611     const DataLayout &DL = A.getDataLayout();
4612 
4613     auto VisitValueCB = [&](Value &V, const Instruction *,
4614                             AAAlign::StateType &T, bool Stripped) -> bool {
4615       if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4616         return true;
4617       const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V),
4618                                            DepClassTy::REQUIRED);
4619       if (!Stripped && this == &AA) {
4620         int64_t Offset;
4621         unsigned Alignment = 1;
4622         if (const Value *Base =
4623                 GetPointerBaseWithConstantOffset(&V, Offset, DL)) {
4624           // TODO: Use AAAlign for the base too.
4625           Align PA = Base->getPointerAlignment(DL);
4626           // BasePointerAddr + Offset = Alignment * Q for some integer Q.
4627           // So we can say that the maximum power of two which is a divisor of
4628           // gcd(Offset, Alignment) is an alignment.
4629 
4630           uint32_t gcd = greatestCommonDivisor(uint32_t(abs((int32_t)Offset)),
4631                                                uint32_t(PA.value()));
4632           Alignment = llvm::PowerOf2Floor(gcd);
4633         } else {
4634           Alignment = V.getPointerAlignment(DL).value();
4635         }
4636         // Use only IR information if we did not strip anything.
4637         T.takeKnownMaximum(Alignment);
4638         T.indicatePessimisticFixpoint();
4639       } else {
4640         // Use abstract attribute information.
4641         const AAAlign::StateType &DS = AA.getState();
4642         T ^= DS;
4643       }
4644       return T.isValidState();
4645     };
4646 
4647     StateType T;
4648     bool UsedAssumedInformation = false;
4649     if (!genericValueTraversal<StateType>(A, getIRPosition(), *this, T,
4650                                           VisitValueCB, getCtxI(),
4651                                           UsedAssumedInformation))
4652       return indicatePessimisticFixpoint();
4653 
4654     // TODO: If we know we visited all incoming values, thus no are assumed
4655     // dead, we can take the known information from the state T.
4656     return clampStateAndIndicateChange(getState(), T);
4657   }
4658 
4659   /// See AbstractAttribute::trackStatistics()
4660   void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) }
4661 };
4662 
4663 /// Align attribute for function return value.
4664 struct AAAlignReturned final
4665     : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
4666   using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
4667   AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
4668 
4669   /// See AbstractAttribute::initialize(...).
4670   void initialize(Attributor &A) override {
4671     Base::initialize(A);
4672     Function *F = getAssociatedFunction();
4673     if (!F || F->isDeclaration())
4674       indicatePessimisticFixpoint();
4675   }
4676 
4677   /// See AbstractAttribute::trackStatistics()
4678   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) }
4679 };
4680 
4681 /// Align attribute for function argument.
4682 struct AAAlignArgument final
4683     : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
4684   using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
4685   AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {}
4686 
4687   /// See AbstractAttribute::manifest(...).
4688   ChangeStatus manifest(Attributor &A) override {
4689     // If the associated argument is involved in a must-tail call we give up
4690     // because we would need to keep the argument alignments of caller and
4691     // callee in-sync. Just does not seem worth the trouble right now.
4692     if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
4693       return ChangeStatus::UNCHANGED;
4694     return Base::manifest(A);
4695   }
4696 
4697   /// See AbstractAttribute::trackStatistics()
4698   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) }
4699 };
4700 
4701 struct AAAlignCallSiteArgument final : AAAlignFloating {
4702   AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A)
4703       : AAAlignFloating(IRP, A) {}
4704 
4705   /// See AbstractAttribute::manifest(...).
4706   ChangeStatus manifest(Attributor &A) override {
4707     // If the associated argument is involved in a must-tail call we give up
4708     // because we would need to keep the argument alignments of caller and
4709     // callee in-sync. Just does not seem worth the trouble right now.
4710     if (Argument *Arg = getAssociatedArgument())
4711       if (A.getInfoCache().isInvolvedInMustTailCall(*Arg))
4712         return ChangeStatus::UNCHANGED;
4713     ChangeStatus Changed = AAAlignImpl::manifest(A);
4714     Align InheritAlign =
4715         getAssociatedValue().getPointerAlignment(A.getDataLayout());
4716     if (InheritAlign >= getAssumedAlign())
4717       Changed = ChangeStatus::UNCHANGED;
4718     return Changed;
4719   }
4720 
4721   /// See AbstractAttribute::updateImpl(Attributor &A).
4722   ChangeStatus updateImpl(Attributor &A) override {
4723     ChangeStatus Changed = AAAlignFloating::updateImpl(A);
4724     if (Argument *Arg = getAssociatedArgument()) {
4725       // We only take known information from the argument
4726       // so we do not need to track a dependence.
4727       const auto &ArgAlignAA = A.getAAFor<AAAlign>(
4728           *this, IRPosition::argument(*Arg), DepClassTy::NONE);
4729       takeKnownMaximum(ArgAlignAA.getKnownAlign());
4730     }
4731     return Changed;
4732   }
4733 
4734   /// See AbstractAttribute::trackStatistics()
4735   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) }
4736 };
4737 
4738 /// Align attribute deduction for a call site return value.
4739 struct AAAlignCallSiteReturned final
4740     : AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl> {
4741   using Base = AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl>;
4742   AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A)
4743       : Base(IRP, A) {}
4744 
4745   /// See AbstractAttribute::initialize(...).
4746   void initialize(Attributor &A) override {
4747     Base::initialize(A);
4748     Function *F = getAssociatedFunction();
4749     if (!F || F->isDeclaration())
4750       indicatePessimisticFixpoint();
4751   }
4752 
4753   /// See AbstractAttribute::trackStatistics()
4754   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); }
4755 };
4756 } // namespace
4757 
4758 /// ------------------ Function No-Return Attribute ----------------------------
4759 namespace {
4760 struct AANoReturnImpl : public AANoReturn {
4761   AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {}
4762 
4763   /// See AbstractAttribute::initialize(...).
4764   void initialize(Attributor &A) override {
4765     AANoReturn::initialize(A);
4766     Function *F = getAssociatedFunction();
4767     if (!F || F->isDeclaration())
4768       indicatePessimisticFixpoint();
4769   }
4770 
4771   /// See AbstractAttribute::getAsStr().
4772   const std::string getAsStr() const override {
4773     return getAssumed() ? "noreturn" : "may-return";
4774   }
4775 
4776   /// See AbstractAttribute::updateImpl(Attributor &A).
4777   virtual ChangeStatus updateImpl(Attributor &A) override {
4778     auto CheckForNoReturn = [](Instruction &) { return false; };
4779     bool UsedAssumedInformation = false;
4780     if (!A.checkForAllInstructions(CheckForNoReturn, *this,
4781                                    {(unsigned)Instruction::Ret},
4782                                    UsedAssumedInformation))
4783       return indicatePessimisticFixpoint();
4784     return ChangeStatus::UNCHANGED;
4785   }
4786 };
4787 
4788 struct AANoReturnFunction final : AANoReturnImpl {
4789   AANoReturnFunction(const IRPosition &IRP, Attributor &A)
4790       : AANoReturnImpl(IRP, A) {}
4791 
4792   /// See AbstractAttribute::trackStatistics()
4793   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) }
4794 };
4795 
4796 /// NoReturn attribute deduction for a call sites.
4797 struct AANoReturnCallSite final : AANoReturnImpl {
4798   AANoReturnCallSite(const IRPosition &IRP, Attributor &A)
4799       : AANoReturnImpl(IRP, A) {}
4800 
4801   /// See AbstractAttribute::initialize(...).
4802   void initialize(Attributor &A) override {
4803     AANoReturnImpl::initialize(A);
4804     if (Function *F = getAssociatedFunction()) {
4805       const IRPosition &FnPos = IRPosition::function(*F);
4806       auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED);
4807       if (!FnAA.isAssumedNoReturn())
4808         indicatePessimisticFixpoint();
4809     }
4810   }
4811 
4812   /// See AbstractAttribute::updateImpl(...).
4813   ChangeStatus updateImpl(Attributor &A) override {
4814     // TODO: Once we have call site specific value information we can provide
4815     //       call site specific liveness information and then it makes
4816     //       sense to specialize attributes for call sites arguments instead of
4817     //       redirecting requests to the callee argument.
4818     Function *F = getAssociatedFunction();
4819     const IRPosition &FnPos = IRPosition::function(*F);
4820     auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED);
4821     return clampStateAndIndicateChange(getState(), FnAA.getState());
4822   }
4823 
4824   /// See AbstractAttribute::trackStatistics()
4825   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); }
4826 };
4827 } // namespace
4828 
4829 /// ----------------------- Instance Info ---------------------------------
4830 
4831 namespace {
4832 /// A class to hold the state of for no-capture attributes.
4833 struct AAInstanceInfoImpl : public AAInstanceInfo {
4834   AAInstanceInfoImpl(const IRPosition &IRP, Attributor &A)
4835       : AAInstanceInfo(IRP, A) {}
4836 
4837   /// See AbstractAttribute::initialize(...).
4838   void initialize(Attributor &A) override {
4839     Value &V = getAssociatedValue();
4840     if (auto *C = dyn_cast<Constant>(&V)) {
4841       if (C->isThreadDependent())
4842         indicatePessimisticFixpoint();
4843       else
4844         indicateOptimisticFixpoint();
4845       return;
4846     }
4847     if (auto *CB = dyn_cast<CallBase>(&V))
4848       if (CB->arg_size() == 0 && !CB->mayHaveSideEffects() &&
4849           !CB->mayReadFromMemory()) {
4850         indicateOptimisticFixpoint();
4851         return;
4852       }
4853   }
4854 
4855   /// See AbstractAttribute::updateImpl(...).
4856   ChangeStatus updateImpl(Attributor &A) override {
4857     ChangeStatus Changed = ChangeStatus::UNCHANGED;
4858 
4859     Value &V = getAssociatedValue();
4860     const Function *Scope = nullptr;
4861     if (auto *I = dyn_cast<Instruction>(&V))
4862       Scope = I->getFunction();
4863     if (auto *A = dyn_cast<Argument>(&V)) {
4864       Scope = A->getParent();
4865       if (!Scope->hasLocalLinkage())
4866         return Changed;
4867     }
4868     if (!Scope)
4869       return indicateOptimisticFixpoint();
4870 
4871     auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
4872         *this, IRPosition::function(*Scope), DepClassTy::OPTIONAL);
4873     if (NoRecurseAA.isAssumedNoRecurse())
4874       return Changed;
4875 
4876     auto UsePred = [&](const Use &U, bool &Follow) {
4877       const Instruction *UserI = dyn_cast<Instruction>(U.getUser());
4878       if (!UserI || isa<GetElementPtrInst>(UserI) || isa<CastInst>(UserI) ||
4879           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
4880         Follow = true;
4881         return true;
4882       }
4883       if (isa<LoadInst>(UserI) || isa<CmpInst>(UserI) ||
4884           (isa<StoreInst>(UserI) &&
4885            cast<StoreInst>(UserI)->getValueOperand() != U.get()))
4886         return true;
4887       if (auto *CB = dyn_cast<CallBase>(UserI)) {
4888         // This check is not guaranteeing uniqueness but for now that we cannot
4889         // end up with two versions of \p U thinking it was one.
4890         if (!CB->getCalledFunction() ||
4891             !CB->getCalledFunction()->hasLocalLinkage())
4892           return true;
4893         if (!CB->isArgOperand(&U))
4894           return false;
4895         const auto &ArgInstanceInfoAA = A.getAAFor<AAInstanceInfo>(
4896             *this, IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)),
4897             DepClassTy::OPTIONAL);
4898         if (ArgInstanceInfoAA.isAssumedUniqueForAnalysis())
4899           return true;
4900       }
4901       return false;
4902     };
4903 
4904     auto EquivalentUseCB = [&](const Use &OldU, const Use &NewU) {
4905       if (auto *SI = dyn_cast<StoreInst>(OldU.getUser())) {
4906         auto *Ptr = SI->getPointerOperand()->stripPointerCasts();
4907         if (isa<AllocaInst>(Ptr) && AA::isDynamicallyUnique(A, *this, *Ptr))
4908           return true;
4909         auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(
4910             *SI->getFunction());
4911         if (isAllocationFn(Ptr, TLI) && AA::isDynamicallyUnique(A, *this, *Ptr))
4912           return true;
4913       }
4914       return false;
4915     };
4916 
4917     if (!A.checkForAllUses(UsePred, *this, V, /* CheckBBLivenessOnly */ true,
4918                            DepClassTy::OPTIONAL,
4919                            /* IgnoreDroppableUses */ true, EquivalentUseCB))
4920       return indicatePessimisticFixpoint();
4921 
4922     return Changed;
4923   }
4924 
4925   /// See AbstractState::getAsStr().
4926   const std::string getAsStr() const override {
4927     return isAssumedUniqueForAnalysis() ? "<unique [fAa]>" : "<unknown>";
4928   }
4929 
4930   /// See AbstractAttribute::trackStatistics()
4931   void trackStatistics() const override {}
4932 };
4933 
4934 /// InstanceInfo attribute for floating values.
4935 struct AAInstanceInfoFloating : AAInstanceInfoImpl {
4936   AAInstanceInfoFloating(const IRPosition &IRP, Attributor &A)
4937       : AAInstanceInfoImpl(IRP, A) {}
4938 };
4939 
4940 /// NoCapture attribute for function arguments.
4941 struct AAInstanceInfoArgument final : AAInstanceInfoFloating {
4942   AAInstanceInfoArgument(const IRPosition &IRP, Attributor &A)
4943       : AAInstanceInfoFloating(IRP, A) {}
4944 };
4945 
4946 /// InstanceInfo attribute for call site arguments.
4947 struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl {
4948   AAInstanceInfoCallSiteArgument(const IRPosition &IRP, Attributor &A)
4949       : AAInstanceInfoImpl(IRP, A) {}
4950 
4951   /// See AbstractAttribute::updateImpl(...).
4952   ChangeStatus updateImpl(Attributor &A) override {
4953     // TODO: Once we have call site specific value information we can provide
4954     //       call site specific liveness information and then it makes
4955     //       sense to specialize attributes for call sites arguments instead of
4956     //       redirecting requests to the callee argument.
4957     Argument *Arg = getAssociatedArgument();
4958     if (!Arg)
4959       return indicatePessimisticFixpoint();
4960     const IRPosition &ArgPos = IRPosition::argument(*Arg);
4961     auto &ArgAA =
4962         A.getAAFor<AAInstanceInfo>(*this, ArgPos, DepClassTy::REQUIRED);
4963     return clampStateAndIndicateChange(getState(), ArgAA.getState());
4964   }
4965 };
4966 
4967 /// InstanceInfo attribute for function return value.
4968 struct AAInstanceInfoReturned final : AAInstanceInfoImpl {
4969   AAInstanceInfoReturned(const IRPosition &IRP, Attributor &A)
4970       : AAInstanceInfoImpl(IRP, A) {
4971     llvm_unreachable("InstanceInfo is not applicable to function returns!");
4972   }
4973 
4974   /// See AbstractAttribute::initialize(...).
4975   void initialize(Attributor &A) override {
4976     llvm_unreachable("InstanceInfo is not applicable to function returns!");
4977   }
4978 
4979   /// See AbstractAttribute::updateImpl(...).
4980   ChangeStatus updateImpl(Attributor &A) override {
4981     llvm_unreachable("InstanceInfo is not applicable to function returns!");
4982   }
4983 };
4984 
4985 /// InstanceInfo attribute deduction for a call site return value.
4986 struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating {
4987   AAInstanceInfoCallSiteReturned(const IRPosition &IRP, Attributor &A)
4988       : AAInstanceInfoFloating(IRP, A) {}
4989 };
4990 } // namespace
4991 
4992 /// ----------------------- Variable Capturing ---------------------------------
4993 
4994 namespace {
4995 /// A class to hold the state of for no-capture attributes.
4996 struct AANoCaptureImpl : public AANoCapture {
4997   AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {}
4998 
4999   /// See AbstractAttribute::initialize(...).
5000   void initialize(Attributor &A) override {
5001     if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) {
5002       indicateOptimisticFixpoint();
5003       return;
5004     }
5005     Function *AnchorScope = getAnchorScope();
5006     if (isFnInterfaceKind() &&
5007         (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) {
5008       indicatePessimisticFixpoint();
5009       return;
5010     }
5011 
5012     // You cannot "capture" null in the default address space.
5013     if (isa<ConstantPointerNull>(getAssociatedValue()) &&
5014         getAssociatedValue().getType()->getPointerAddressSpace() == 0) {
5015       indicateOptimisticFixpoint();
5016       return;
5017     }
5018 
5019     const Function *F =
5020         isArgumentPosition() ? getAssociatedFunction() : AnchorScope;
5021 
5022     // Check what state the associated function can actually capture.
5023     if (F)
5024       determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
5025     else
5026       indicatePessimisticFixpoint();
5027   }
5028 
5029   /// See AbstractAttribute::updateImpl(...).
5030   ChangeStatus updateImpl(Attributor &A) override;
5031 
5032   /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...).
5033   virtual void
5034   getDeducedAttributes(LLVMContext &Ctx,
5035                        SmallVectorImpl<Attribute> &Attrs) const override {
5036     if (!isAssumedNoCaptureMaybeReturned())
5037       return;
5038 
5039     if (isArgumentPosition()) {
5040       if (isAssumedNoCapture())
5041         Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture));
5042       else if (ManifestInternal)
5043         Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned"));
5044     }
5045   }
5046 
5047   /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known
5048   /// depending on the ability of the function associated with \p IRP to capture
5049   /// state in memory and through "returning/throwing", respectively.
5050   static void determineFunctionCaptureCapabilities(const IRPosition &IRP,
5051                                                    const Function &F,
5052                                                    BitIntegerState &State) {
5053     // TODO: Once we have memory behavior attributes we should use them here.
5054 
5055     // If we know we cannot communicate or write to memory, we do not care about
5056     // ptr2int anymore.
5057     if (F.onlyReadsMemory() && F.doesNotThrow() &&
5058         F.getReturnType()->isVoidTy()) {
5059       State.addKnownBits(NO_CAPTURE);
5060       return;
5061     }
5062 
5063     // A function cannot capture state in memory if it only reads memory, it can
5064     // however return/throw state and the state might be influenced by the
5065     // pointer value, e.g., loading from a returned pointer might reveal a bit.
5066     if (F.onlyReadsMemory())
5067       State.addKnownBits(NOT_CAPTURED_IN_MEM);
5068 
5069     // A function cannot communicate state back if it does not through
5070     // exceptions and doesn not return values.
5071     if (F.doesNotThrow() && F.getReturnType()->isVoidTy())
5072       State.addKnownBits(NOT_CAPTURED_IN_RET);
5073 
5074     // Check existing "returned" attributes.
5075     int ArgNo = IRP.getCalleeArgNo();
5076     if (F.doesNotThrow() && ArgNo >= 0) {
5077       for (unsigned u = 0, e = F.arg_size(); u < e; ++u)
5078         if (F.hasParamAttribute(u, Attribute::Returned)) {
5079           if (u == unsigned(ArgNo))
5080             State.removeAssumedBits(NOT_CAPTURED_IN_RET);
5081           else if (F.onlyReadsMemory())
5082             State.addKnownBits(NO_CAPTURE);
5083           else
5084             State.addKnownBits(NOT_CAPTURED_IN_RET);
5085           break;
5086         }
5087     }
5088   }
5089 
5090   /// See AbstractState::getAsStr().
5091   const std::string getAsStr() const override {
5092     if (isKnownNoCapture())
5093       return "known not-captured";
5094     if (isAssumedNoCapture())
5095       return "assumed not-captured";
5096     if (isKnownNoCaptureMaybeReturned())
5097       return "known not-captured-maybe-returned";
5098     if (isAssumedNoCaptureMaybeReturned())
5099       return "assumed not-captured-maybe-returned";
5100     return "assumed-captured";
5101   }
5102 
5103   /// Check the use \p U and update \p State accordingly. Return true if we
5104   /// should continue to update the state.
5105   bool checkUse(Attributor &A, AANoCapture::StateType &State, const Use &U,
5106                 bool &Follow) {
5107     Instruction *UInst = cast<Instruction>(U.getUser());
5108     LLVM_DEBUG(dbgs() << "[AANoCapture] Check use: " << *U.get() << " in "
5109                       << *UInst << "\n");
5110 
5111     // Deal with ptr2int by following uses.
5112     if (isa<PtrToIntInst>(UInst)) {
5113       LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n");
5114       return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5115                           /* Return */ true);
5116     }
5117 
5118     // For stores we already checked if we can follow them, if they make it
5119     // here we give up.
5120     if (isa<StoreInst>(UInst))
5121       return isCapturedIn(State, /* Memory */ true, /* Integer */ false,
5122                           /* Return */ false);
5123 
5124     // Explicitly catch return instructions.
5125     if (isa<ReturnInst>(UInst)) {
5126       if (UInst->getFunction() == getAnchorScope())
5127         return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5128                             /* Return */ true);
5129       return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5130                           /* Return */ true);
5131     }
5132 
5133     // For now we only use special logic for call sites. However, the tracker
5134     // itself knows about a lot of other non-capturing cases already.
5135     auto *CB = dyn_cast<CallBase>(UInst);
5136     if (!CB || !CB->isArgOperand(&U))
5137       return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5138                           /* Return */ true);
5139 
5140     unsigned ArgNo = CB->getArgOperandNo(&U);
5141     const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo);
5142     // If we have a abstract no-capture attribute for the argument we can use
5143     // it to justify a non-capture attribute here. This allows recursion!
5144     auto &ArgNoCaptureAA =
5145         A.getAAFor<AANoCapture>(*this, CSArgPos, DepClassTy::REQUIRED);
5146     if (ArgNoCaptureAA.isAssumedNoCapture())
5147       return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5148                           /* Return */ false);
5149     if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
5150       Follow = true;
5151       return isCapturedIn(State, /* Memory */ false, /* Integer */ false,
5152                           /* Return */ false);
5153     }
5154 
5155     // Lastly, we could not find a reason no-capture can be assumed so we don't.
5156     return isCapturedIn(State, /* Memory */ true, /* Integer */ true,
5157                         /* Return */ true);
5158   }
5159 
5160   /// Update \p State according to \p CapturedInMem, \p CapturedInInt, and
5161   /// \p CapturedInRet, then return true if we should continue updating the
5162   /// state.
5163   static bool isCapturedIn(AANoCapture::StateType &State, bool CapturedInMem,
5164                            bool CapturedInInt, bool CapturedInRet) {
5165     LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int "
5166                       << CapturedInInt << "|Ret " << CapturedInRet << "]\n");
5167     if (CapturedInMem)
5168       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM);
5169     if (CapturedInInt)
5170       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT);
5171     if (CapturedInRet)
5172       State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET);
5173     return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED);
5174   }
5175 };
5176 
5177 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) {
5178   const IRPosition &IRP = getIRPosition();
5179   Value *V = isArgumentPosition() ? IRP.getAssociatedArgument()
5180                                   : &IRP.getAssociatedValue();
5181   if (!V)
5182     return indicatePessimisticFixpoint();
5183 
5184   const Function *F =
5185       isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope();
5186   assert(F && "Expected a function!");
5187   const IRPosition &FnPos = IRPosition::function(*F);
5188 
5189   AANoCapture::StateType T;
5190 
5191   // Readonly means we cannot capture through memory.
5192   bool IsKnown;
5193   if (AA::isAssumedReadOnly(A, FnPos, *this, IsKnown)) {
5194     T.addKnownBits(NOT_CAPTURED_IN_MEM);
5195     if (IsKnown)
5196       addKnownBits(NOT_CAPTURED_IN_MEM);
5197   }
5198 
5199   // Make sure all returned values are different than the underlying value.
5200   // TODO: we could do this in a more sophisticated way inside
5201   //       AAReturnedValues, e.g., track all values that escape through returns
5202   //       directly somehow.
5203   auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) {
5204     bool SeenConstant = false;
5205     for (auto &It : RVAA.returned_values()) {
5206       if (isa<Constant>(It.first)) {
5207         if (SeenConstant)
5208           return false;
5209         SeenConstant = true;
5210       } else if (!isa<Argument>(It.first) ||
5211                  It.first == getAssociatedArgument())
5212         return false;
5213     }
5214     return true;
5215   };
5216 
5217   const auto &NoUnwindAA =
5218       A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::OPTIONAL);
5219   if (NoUnwindAA.isAssumedNoUnwind()) {
5220     bool IsVoidTy = F->getReturnType()->isVoidTy();
5221     const AAReturnedValues *RVAA =
5222         IsVoidTy ? nullptr
5223                  : &A.getAAFor<AAReturnedValues>(*this, FnPos,
5224 
5225                                                  DepClassTy::OPTIONAL);
5226     if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
5227       T.addKnownBits(NOT_CAPTURED_IN_RET);
5228       if (T.isKnown(NOT_CAPTURED_IN_MEM))
5229         return ChangeStatus::UNCHANGED;
5230       if (NoUnwindAA.isKnownNoUnwind() &&
5231           (IsVoidTy || RVAA->getState().isAtFixpoint())) {
5232         addKnownBits(NOT_CAPTURED_IN_RET);
5233         if (isKnown(NOT_CAPTURED_IN_MEM))
5234           return indicateOptimisticFixpoint();
5235       }
5236     }
5237   }
5238 
5239   auto IsDereferenceableOrNull = [&](Value *O, const DataLayout &DL) {
5240     const auto &DerefAA = A.getAAFor<AADereferenceable>(
5241         *this, IRPosition::value(*O), DepClassTy::OPTIONAL);
5242     return DerefAA.getAssumedDereferenceableBytes();
5243   };
5244 
5245   auto UseCheck = [&](const Use &U, bool &Follow) -> bool {
5246     switch (DetermineUseCaptureKind(U, IsDereferenceableOrNull)) {
5247     case UseCaptureKind::NO_CAPTURE:
5248       return true;
5249     case UseCaptureKind::MAY_CAPTURE:
5250       return checkUse(A, T, U, Follow);
5251     case UseCaptureKind::PASSTHROUGH:
5252       Follow = true;
5253       return true;
5254     }
5255     llvm_unreachable("Unexpected use capture kind!");
5256   };
5257 
5258   if (!A.checkForAllUses(UseCheck, *this, *V))
5259     return indicatePessimisticFixpoint();
5260 
5261   AANoCapture::StateType &S = getState();
5262   auto Assumed = S.getAssumed();
5263   S.intersectAssumedBits(T.getAssumed());
5264   if (!isAssumedNoCaptureMaybeReturned())
5265     return indicatePessimisticFixpoint();
5266   return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED
5267                                    : ChangeStatus::CHANGED;
5268 }
5269 
5270 /// NoCapture attribute for function arguments.
5271 struct AANoCaptureArgument final : AANoCaptureImpl {
5272   AANoCaptureArgument(const IRPosition &IRP, Attributor &A)
5273       : AANoCaptureImpl(IRP, A) {}
5274 
5275   /// See AbstractAttribute::trackStatistics()
5276   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) }
5277 };
5278 
5279 /// NoCapture attribute for call site arguments.
5280 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
5281   AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A)
5282       : AANoCaptureImpl(IRP, A) {}
5283 
5284   /// See AbstractAttribute::initialize(...).
5285   void initialize(Attributor &A) override {
5286     if (Argument *Arg = getAssociatedArgument())
5287       if (Arg->hasByValAttr())
5288         indicateOptimisticFixpoint();
5289     AANoCaptureImpl::initialize(A);
5290   }
5291 
5292   /// See AbstractAttribute::updateImpl(...).
5293   ChangeStatus updateImpl(Attributor &A) override {
5294     // TODO: Once we have call site specific value information we can provide
5295     //       call site specific liveness information and then it makes
5296     //       sense to specialize attributes for call sites arguments instead of
5297     //       redirecting requests to the callee argument.
5298     Argument *Arg = getAssociatedArgument();
5299     if (!Arg)
5300       return indicatePessimisticFixpoint();
5301     const IRPosition &ArgPos = IRPosition::argument(*Arg);
5302     auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos, DepClassTy::REQUIRED);
5303     return clampStateAndIndicateChange(getState(), ArgAA.getState());
5304   }
5305 
5306   /// See AbstractAttribute::trackStatistics()
5307   void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)};
5308 };
5309 
5310 /// NoCapture attribute for floating values.
5311 struct AANoCaptureFloating final : AANoCaptureImpl {
5312   AANoCaptureFloating(const IRPosition &IRP, Attributor &A)
5313       : AANoCaptureImpl(IRP, A) {}
5314 
5315   /// See AbstractAttribute::trackStatistics()
5316   void trackStatistics() const override {
5317     STATS_DECLTRACK_FLOATING_ATTR(nocapture)
5318   }
5319 };
5320 
5321 /// NoCapture attribute for function return value.
5322 struct AANoCaptureReturned final : AANoCaptureImpl {
5323   AANoCaptureReturned(const IRPosition &IRP, Attributor &A)
5324       : AANoCaptureImpl(IRP, A) {
5325     llvm_unreachable("NoCapture is not applicable to function returns!");
5326   }
5327 
5328   /// See AbstractAttribute::initialize(...).
5329   void initialize(Attributor &A) override {
5330     llvm_unreachable("NoCapture is not applicable to function returns!");
5331   }
5332 
5333   /// See AbstractAttribute::updateImpl(...).
5334   ChangeStatus updateImpl(Attributor &A) override {
5335     llvm_unreachable("NoCapture is not applicable to function returns!");
5336   }
5337 
5338   /// See AbstractAttribute::trackStatistics()
5339   void trackStatistics() const override {}
5340 };
5341 
5342 /// NoCapture attribute deduction for a call site return value.
5343 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
5344   AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A)
5345       : AANoCaptureImpl(IRP, A) {}
5346 
5347   /// See AbstractAttribute::initialize(...).
5348   void initialize(Attributor &A) override {
5349     const Function *F = getAnchorScope();
5350     // Check what state the associated function can actually capture.
5351     determineFunctionCaptureCapabilities(getIRPosition(), *F, *this);
5352   }
5353 
5354   /// See AbstractAttribute::trackStatistics()
5355   void trackStatistics() const override {
5356     STATS_DECLTRACK_CSRET_ATTR(nocapture)
5357   }
5358 };
5359 } // namespace
5360 
5361 /// ------------------ Value Simplify Attribute ----------------------------
5362 
5363 bool ValueSimplifyStateType::unionAssumed(Optional<Value *> Other) {
5364   // FIXME: Add a typecast support.
5365   SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice(
5366       SimplifiedAssociatedValue, Other, Ty);
5367   if (SimplifiedAssociatedValue == Optional<Value *>(nullptr))
5368     return false;
5369 
5370   LLVM_DEBUG({
5371     if (SimplifiedAssociatedValue.hasValue())
5372       dbgs() << "[ValueSimplify] is assumed to be "
5373              << **SimplifiedAssociatedValue << "\n";
5374     else
5375       dbgs() << "[ValueSimplify] is assumed to be <none>\n";
5376   });
5377   return true;
5378 }
5379 
5380 namespace {
5381 struct AAValueSimplifyImpl : AAValueSimplify {
5382   AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A)
5383       : AAValueSimplify(IRP, A) {}
5384 
5385   /// See AbstractAttribute::initialize(...).
5386   void initialize(Attributor &A) override {
5387     if (getAssociatedValue().getType()->isVoidTy())
5388       indicatePessimisticFixpoint();
5389     if (A.hasSimplificationCallback(getIRPosition()))
5390       indicatePessimisticFixpoint();
5391   }
5392 
5393   /// See AbstractAttribute::getAsStr().
5394   const std::string getAsStr() const override {
5395     LLVM_DEBUG({
5396       errs() << "SAV: " << (bool)SimplifiedAssociatedValue << " ";
5397       if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue)
5398         errs() << "SAV: " << **SimplifiedAssociatedValue << " ";
5399     });
5400     return isValidState() ? (isAtFixpoint() ? "simplified" : "maybe-simple")
5401                           : "not-simple";
5402   }
5403 
5404   /// See AbstractAttribute::trackStatistics()
5405   void trackStatistics() const override {}
5406 
5407   /// See AAValueSimplify::getAssumedSimplifiedValue()
5408   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
5409     return SimplifiedAssociatedValue;
5410   }
5411 
5412   /// Ensure the return value is \p V with type \p Ty, if not possible return
5413   /// nullptr. If \p Check is true we will only verify such an operation would
5414   /// suceed and return a non-nullptr value if that is the case. No IR is
5415   /// generated or modified.
5416   static Value *ensureType(Attributor &A, Value &V, Type &Ty, Instruction *CtxI,
5417                            bool Check) {
5418     if (auto *TypedV = AA::getWithType(V, Ty))
5419       return TypedV;
5420     if (CtxI && V.getType()->canLosslesslyBitCastTo(&Ty))
5421       return Check ? &V
5422                    : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(&V, &Ty,
5423                                                                       "", CtxI);
5424     return nullptr;
5425   }
5426 
5427   /// Reproduce \p I with type \p Ty or return nullptr if that is not posisble.
5428   /// If \p Check is true we will only verify such an operation would suceed and
5429   /// return a non-nullptr value if that is the case. No IR is generated or
5430   /// modified.
5431   static Value *reproduceInst(Attributor &A,
5432                               const AbstractAttribute &QueryingAA,
5433                               Instruction &I, Type &Ty, Instruction *CtxI,
5434                               bool Check, ValueToValueMapTy &VMap) {
5435     assert(CtxI && "Cannot reproduce an instruction without context!");
5436     if (Check && (I.mayReadFromMemory() ||
5437                   !isSafeToSpeculativelyExecute(&I, CtxI, /* DT */ nullptr,
5438                                                 /* TLI */ nullptr)))
5439       return nullptr;
5440     for (Value *Op : I.operands()) {
5441       Value *NewOp = reproduceValue(A, QueryingAA, *Op, Ty, CtxI, Check, VMap);
5442       if (!NewOp) {
5443         assert(Check && "Manifest of new value unexpectedly failed!");
5444         return nullptr;
5445       }
5446       if (!Check)
5447         VMap[Op] = NewOp;
5448     }
5449     if (Check)
5450       return &I;
5451 
5452     Instruction *CloneI = I.clone();
5453     // TODO: Try to salvage debug information here.
5454     CloneI->setDebugLoc(DebugLoc());
5455     VMap[&I] = CloneI;
5456     CloneI->insertBefore(CtxI);
5457     RemapInstruction(CloneI, VMap);
5458     return CloneI;
5459   }
5460 
5461   /// Reproduce \p V with type \p Ty or return nullptr if that is not posisble.
5462   /// If \p Check is true we will only verify such an operation would suceed and
5463   /// return a non-nullptr value if that is the case. No IR is generated or
5464   /// modified.
5465   static Value *reproduceValue(Attributor &A,
5466                                const AbstractAttribute &QueryingAA, Value &V,
5467                                Type &Ty, Instruction *CtxI, bool Check,
5468                                ValueToValueMapTy &VMap) {
5469     if (const auto &NewV = VMap.lookup(&V))
5470       return NewV;
5471     bool UsedAssumedInformation = false;
5472     Optional<Value *> SimpleV =
5473         A.getAssumedSimplified(V, QueryingAA, UsedAssumedInformation);
5474     if (!SimpleV.hasValue())
5475       return PoisonValue::get(&Ty);
5476     Value *EffectiveV = &V;
5477     if (SimpleV.getValue())
5478       EffectiveV = SimpleV.getValue();
5479     if (auto *C = dyn_cast<Constant>(EffectiveV))
5480       if (!C->canTrap())
5481         return C;
5482     if (CtxI && AA::isValidAtPosition(AA::ValueAndContext(*EffectiveV, *CtxI),
5483                                       A.getInfoCache()))
5484       return ensureType(A, *EffectiveV, Ty, CtxI, Check);
5485     if (auto *I = dyn_cast<Instruction>(EffectiveV))
5486       if (Value *NewV = reproduceInst(A, QueryingAA, *I, Ty, CtxI, Check, VMap))
5487         return ensureType(A, *NewV, Ty, CtxI, Check);
5488     return nullptr;
5489   }
5490 
5491   /// Return a value we can use as replacement for the associated one, or
5492   /// nullptr if we don't have one that makes sense.
5493   Value *manifestReplacementValue(Attributor &A, Instruction *CtxI) const {
5494     Value *NewV = SimplifiedAssociatedValue.hasValue()
5495                       ? SimplifiedAssociatedValue.getValue()
5496                       : UndefValue::get(getAssociatedType());
5497     if (NewV && NewV != &getAssociatedValue()) {
5498       ValueToValueMapTy VMap;
5499       // First verify we can reprduce the value with the required type at the
5500       // context location before we actually start modifying the IR.
5501       if (reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
5502                          /* CheckOnly */ true, VMap))
5503         return reproduceValue(A, *this, *NewV, *getAssociatedType(), CtxI,
5504                               /* CheckOnly */ false, VMap);
5505     }
5506     return nullptr;
5507   }
5508 
5509   /// Helper function for querying AAValueSimplify and updating candicate.
5510   /// \param IRP The value position we are trying to unify with SimplifiedValue
5511   bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA,
5512                       const IRPosition &IRP, bool Simplify = true) {
5513     bool UsedAssumedInformation = false;
5514     Optional<Value *> QueryingValueSimplified = &IRP.getAssociatedValue();
5515     if (Simplify)
5516       QueryingValueSimplified =
5517           A.getAssumedSimplified(IRP, QueryingAA, UsedAssumedInformation);
5518     return unionAssumed(QueryingValueSimplified);
5519   }
5520 
5521   /// Returns a candidate is found or not
5522   template <typename AAType> bool askSimplifiedValueFor(Attributor &A) {
5523     if (!getAssociatedValue().getType()->isIntegerTy())
5524       return false;
5525 
5526     // This will also pass the call base context.
5527     const auto &AA =
5528         A.getAAFor<AAType>(*this, getIRPosition(), DepClassTy::NONE);
5529 
5530     Optional<Constant *> COpt = AA.getAssumedConstant(A);
5531 
5532     if (!COpt.hasValue()) {
5533       SimplifiedAssociatedValue = llvm::None;
5534       A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
5535       return true;
5536     }
5537     if (auto *C = COpt.getValue()) {
5538       SimplifiedAssociatedValue = C;
5539       A.recordDependence(AA, *this, DepClassTy::OPTIONAL);
5540       return true;
5541     }
5542     return false;
5543   }
5544 
5545   bool askSimplifiedValueForOtherAAs(Attributor &A) {
5546     if (askSimplifiedValueFor<AAValueConstantRange>(A))
5547       return true;
5548     if (askSimplifiedValueFor<AAPotentialConstantValues>(A))
5549       return true;
5550     return false;
5551   }
5552 
5553   /// See AbstractAttribute::manifest(...).
5554   ChangeStatus manifest(Attributor &A) override {
5555     ChangeStatus Changed = ChangeStatus::UNCHANGED;
5556     for (auto &U : getAssociatedValue().uses()) {
5557       // Check if we need to adjust the insertion point to make sure the IR is
5558       // valid.
5559       Instruction *IP = dyn_cast<Instruction>(U.getUser());
5560       if (auto *PHI = dyn_cast_or_null<PHINode>(IP))
5561         IP = PHI->getIncomingBlock(U)->getTerminator();
5562       if (auto *NewV = manifestReplacementValue(A, IP)) {
5563         LLVM_DEBUG(dbgs() << "[ValueSimplify] " << getAssociatedValue()
5564                           << " -> " << *NewV << " :: " << *this << "\n");
5565         if (A.changeUseAfterManifest(U, *NewV))
5566           Changed = ChangeStatus::CHANGED;
5567       }
5568     }
5569 
5570     return Changed | AAValueSimplify::manifest(A);
5571   }
5572 
5573   /// See AbstractState::indicatePessimisticFixpoint(...).
5574   ChangeStatus indicatePessimisticFixpoint() override {
5575     SimplifiedAssociatedValue = &getAssociatedValue();
5576     return AAValueSimplify::indicatePessimisticFixpoint();
5577   }
5578 };
5579 
5580 struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
5581   AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A)
5582       : AAValueSimplifyImpl(IRP, A) {}
5583 
5584   void initialize(Attributor &A) override {
5585     AAValueSimplifyImpl::initialize(A);
5586     if (!getAnchorScope() || getAnchorScope()->isDeclaration())
5587       indicatePessimisticFixpoint();
5588     if (hasAttr({Attribute::InAlloca, Attribute::Preallocated,
5589                  Attribute::StructRet, Attribute::Nest, Attribute::ByVal},
5590                 /* IgnoreSubsumingPositions */ true))
5591       indicatePessimisticFixpoint();
5592   }
5593 
5594   /// See AbstractAttribute::updateImpl(...).
5595   ChangeStatus updateImpl(Attributor &A) override {
5596     // Byval is only replacable if it is readonly otherwise we would write into
5597     // the replaced value and not the copy that byval creates implicitly.
5598     Argument *Arg = getAssociatedArgument();
5599     if (Arg->hasByValAttr()) {
5600       // TODO: We probably need to verify synchronization is not an issue, e.g.,
5601       //       there is no race by not copying a constant byval.
5602       bool IsKnown;
5603       if (!AA::isAssumedReadOnly(A, getIRPosition(), *this, IsKnown))
5604         return indicatePessimisticFixpoint();
5605     }
5606 
5607     auto Before = SimplifiedAssociatedValue;
5608 
5609     auto PredForCallSite = [&](AbstractCallSite ACS) {
5610       const IRPosition &ACSArgPos =
5611           IRPosition::callsite_argument(ACS, getCallSiteArgNo());
5612       // Check if a coresponding argument was found or if it is on not
5613       // associated (which can happen for callback calls).
5614       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
5615         return false;
5616 
5617       // Simplify the argument operand explicitly and check if the result is
5618       // valid in the current scope. This avoids refering to simplified values
5619       // in other functions, e.g., we don't want to say a an argument in a
5620       // static function is actually an argument in a different function.
5621       bool UsedAssumedInformation = false;
5622       Optional<Constant *> SimpleArgOp =
5623           A.getAssumedConstant(ACSArgPos, *this, UsedAssumedInformation);
5624       if (!SimpleArgOp.hasValue())
5625         return true;
5626       if (!SimpleArgOp.getValue())
5627         return false;
5628       if (!AA::isDynamicallyUnique(A, *this, **SimpleArgOp))
5629         return false;
5630       return unionAssumed(*SimpleArgOp);
5631     };
5632 
5633     // Generate a answer specific to a call site context.
5634     bool Success;
5635     bool UsedAssumedInformation = false;
5636     if (hasCallBaseContext() &&
5637         getCallBaseContext()->getCalledFunction() == Arg->getParent())
5638       Success = PredForCallSite(
5639           AbstractCallSite(&getCallBaseContext()->getCalledOperandUse()));
5640     else
5641       Success = A.checkForAllCallSites(PredForCallSite, *this, true,
5642                                        UsedAssumedInformation);
5643 
5644     if (!Success)
5645       if (!askSimplifiedValueForOtherAAs(A))
5646         return indicatePessimisticFixpoint();
5647 
5648     // If a candicate was found in this update, return CHANGED.
5649     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5650                                                : ChangeStatus ::CHANGED;
5651   }
5652 
5653   /// See AbstractAttribute::trackStatistics()
5654   void trackStatistics() const override {
5655     STATS_DECLTRACK_ARG_ATTR(value_simplify)
5656   }
5657 };
5658 
5659 struct AAValueSimplifyReturned : AAValueSimplifyImpl {
5660   AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A)
5661       : AAValueSimplifyImpl(IRP, A) {}
5662 
5663   /// See AAValueSimplify::getAssumedSimplifiedValue()
5664   Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override {
5665     if (!isValidState())
5666       return nullptr;
5667     return SimplifiedAssociatedValue;
5668   }
5669 
5670   /// See AbstractAttribute::updateImpl(...).
5671   ChangeStatus updateImpl(Attributor &A) override {
5672     auto Before = SimplifiedAssociatedValue;
5673 
5674     auto ReturnInstCB = [&](Instruction &I) {
5675       auto &RI = cast<ReturnInst>(I);
5676       return checkAndUpdate(
5677           A, *this,
5678           IRPosition::value(*RI.getReturnValue(), getCallBaseContext()));
5679     };
5680 
5681     bool UsedAssumedInformation = false;
5682     if (!A.checkForAllInstructions(ReturnInstCB, *this, {Instruction::Ret},
5683                                    UsedAssumedInformation))
5684       if (!askSimplifiedValueForOtherAAs(A))
5685         return indicatePessimisticFixpoint();
5686 
5687     // If a candicate was found in this update, return CHANGED.
5688     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5689                                                : ChangeStatus ::CHANGED;
5690   }
5691 
5692   ChangeStatus manifest(Attributor &A) override {
5693     // We queried AAValueSimplify for the returned values so they will be
5694     // replaced if a simplified form was found. Nothing to do here.
5695     return ChangeStatus::UNCHANGED;
5696   }
5697 
5698   /// See AbstractAttribute::trackStatistics()
5699   void trackStatistics() const override {
5700     STATS_DECLTRACK_FNRET_ATTR(value_simplify)
5701   }
5702 };
5703 
5704 struct AAValueSimplifyFloating : AAValueSimplifyImpl {
5705   AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A)
5706       : AAValueSimplifyImpl(IRP, A) {}
5707 
5708   /// See AbstractAttribute::initialize(...).
5709   void initialize(Attributor &A) override {
5710     AAValueSimplifyImpl::initialize(A);
5711     Value &V = getAnchorValue();
5712 
5713     // TODO: add other stuffs
5714     if (isa<Constant>(V))
5715       indicatePessimisticFixpoint();
5716   }
5717 
5718   /// Check if \p Cmp is a comparison we can simplify.
5719   ///
5720   /// We handle multiple cases, one in which at least one operand is an
5721   /// (assumed) nullptr. If so, try to simplify it using AANonNull on the other
5722   /// operand. Return true if successful, in that case SimplifiedAssociatedValue
5723   /// will be updated.
5724   bool handleCmp(Attributor &A, CmpInst &Cmp) {
5725     auto Union = [&](Value &V) {
5726       SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice(
5727           SimplifiedAssociatedValue, &V, V.getType());
5728       return SimplifiedAssociatedValue != Optional<Value *>(nullptr);
5729     };
5730 
5731     Value *LHS = Cmp.getOperand(0);
5732     Value *RHS = Cmp.getOperand(1);
5733 
5734     // Simplify the operands first.
5735     bool UsedAssumedInformation = false;
5736     const auto &SimplifiedLHS =
5737         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
5738                                *this, UsedAssumedInformation);
5739     if (!SimplifiedLHS.hasValue())
5740       return true;
5741     if (!SimplifiedLHS.getValue())
5742       return false;
5743     LHS = *SimplifiedLHS;
5744 
5745     const auto &SimplifiedRHS =
5746         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
5747                                *this, UsedAssumedInformation);
5748     if (!SimplifiedRHS.hasValue())
5749       return true;
5750     if (!SimplifiedRHS.getValue())
5751       return false;
5752     RHS = *SimplifiedRHS;
5753 
5754     LLVMContext &Ctx = Cmp.getContext();
5755     // Handle the trivial case first in which we don't even need to think about
5756     // null or non-null.
5757     if (LHS == RHS && (Cmp.isTrueWhenEqual() || Cmp.isFalseWhenEqual())) {
5758       Constant *NewVal =
5759           ConstantInt::get(Type::getInt1Ty(Ctx), Cmp.isTrueWhenEqual());
5760       if (!Union(*NewVal))
5761         return false;
5762       if (!UsedAssumedInformation)
5763         indicateOptimisticFixpoint();
5764       return true;
5765     }
5766 
5767     // From now on we only handle equalities (==, !=).
5768     ICmpInst *ICmp = dyn_cast<ICmpInst>(&Cmp);
5769     if (!ICmp || !ICmp->isEquality())
5770       return false;
5771 
5772     bool LHSIsNull = isa<ConstantPointerNull>(LHS);
5773     bool RHSIsNull = isa<ConstantPointerNull>(RHS);
5774     if (!LHSIsNull && !RHSIsNull)
5775       return false;
5776 
5777     // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the
5778     // non-nullptr operand and if we assume it's non-null we can conclude the
5779     // result of the comparison.
5780     assert((LHSIsNull || RHSIsNull) &&
5781            "Expected nullptr versus non-nullptr comparison at this point");
5782 
5783     // The index is the operand that we assume is not null.
5784     unsigned PtrIdx = LHSIsNull;
5785     auto &PtrNonNullAA = A.getAAFor<AANonNull>(
5786         *this, IRPosition::value(*ICmp->getOperand(PtrIdx)),
5787         DepClassTy::REQUIRED);
5788     if (!PtrNonNullAA.isAssumedNonNull())
5789       return false;
5790     UsedAssumedInformation |= !PtrNonNullAA.isKnownNonNull();
5791 
5792     // The new value depends on the predicate, true for != and false for ==.
5793     Constant *NewVal = ConstantInt::get(
5794         Type::getInt1Ty(Ctx), ICmp->getPredicate() == CmpInst::ICMP_NE);
5795     if (!Union(*NewVal))
5796       return false;
5797 
5798     if (!UsedAssumedInformation)
5799       indicateOptimisticFixpoint();
5800 
5801     return true;
5802   }
5803 
5804   /// Use the generic, non-optimistic InstSimplfy functionality if we managed to
5805   /// simplify any operand of the instruction \p I. Return true if successful,
5806   /// in that case SimplifiedAssociatedValue will be updated.
5807   bool handleGenericInst(Attributor &A, Instruction &I) {
5808     bool SomeSimplified = false;
5809     bool UsedAssumedInformation = false;
5810 
5811     SmallVector<Value *, 8> NewOps(I.getNumOperands());
5812     int Idx = 0;
5813     for (Value *Op : I.operands()) {
5814       const auto &SimplifiedOp =
5815           A.getAssumedSimplified(IRPosition::value(*Op, getCallBaseContext()),
5816                                  *this, UsedAssumedInformation);
5817       // If we are not sure about any operand we are not sure about the entire
5818       // instruction, we'll wait.
5819       if (!SimplifiedOp.hasValue())
5820         return true;
5821 
5822       if (SimplifiedOp.getValue())
5823         NewOps[Idx] = SimplifiedOp.getValue();
5824       else
5825         NewOps[Idx] = Op;
5826 
5827       SomeSimplified |= (NewOps[Idx] != Op);
5828       ++Idx;
5829     }
5830 
5831     // We won't bother with the InstSimplify interface if we didn't simplify any
5832     // operand ourselves.
5833     if (!SomeSimplified)
5834       return false;
5835 
5836     InformationCache &InfoCache = A.getInfoCache();
5837     Function *F = I.getFunction();
5838     const auto *DT =
5839         InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
5840     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
5841     auto *AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
5842     OptimizationRemarkEmitter *ORE = nullptr;
5843 
5844     const DataLayout &DL = I.getModule()->getDataLayout();
5845     SimplifyQuery Q(DL, TLI, DT, AC, &I);
5846     if (Value *SimplifiedI =
5847             SimplifyInstructionWithOperands(&I, NewOps, Q, ORE)) {
5848       SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice(
5849           SimplifiedAssociatedValue, SimplifiedI, I.getType());
5850       return SimplifiedAssociatedValue != Optional<Value *>(nullptr);
5851     }
5852     return false;
5853   }
5854 
5855   /// See AbstractAttribute::updateImpl(...).
5856   ChangeStatus updateImpl(Attributor &A) override {
5857     auto Before = SimplifiedAssociatedValue;
5858 
5859     // Do not simplify loads that are only used in llvm.assume if we cannot also
5860     // remove all stores that may feed into the load. The reason is that the
5861     // assume is probably worth something as long as the stores are around.
5862     if (auto *LI = dyn_cast<LoadInst>(&getAssociatedValue())) {
5863       InformationCache &InfoCache = A.getInfoCache();
5864       if (InfoCache.isOnlyUsedByAssume(*LI)) {
5865         SmallSetVector<Value *, 4> PotentialCopies;
5866         SmallSetVector<Instruction *, 4> PotentialValueOrigins;
5867         bool UsedAssumedInformation = false;
5868         if (AA::getPotentiallyLoadedValues(A, *LI, PotentialCopies,
5869                                            PotentialValueOrigins, *this,
5870                                            UsedAssumedInformation,
5871                                            /* OnlyExact */ true)) {
5872           if (!llvm::all_of(PotentialValueOrigins, [&](Instruction *I) {
5873                 if (!I)
5874                   return true;
5875                 if (auto *SI = dyn_cast<StoreInst>(I))
5876                   return A.isAssumedDead(SI->getOperandUse(0), this,
5877                                          /* LivenessAA */ nullptr,
5878                                          UsedAssumedInformation,
5879                                          /* CheckBBLivenessOnly */ false);
5880                 return A.isAssumedDead(*I, this, /* LivenessAA */ nullptr,
5881                                        UsedAssumedInformation,
5882                                        /* CheckBBLivenessOnly */ false);
5883               }))
5884             return indicatePessimisticFixpoint();
5885         }
5886       }
5887     }
5888 
5889     auto VisitValueCB = [&](Value &V, const Instruction *CtxI, bool &,
5890                             bool Stripped) -> bool {
5891       auto &AA = A.getAAFor<AAValueSimplify>(
5892           *this, IRPosition::value(V, getCallBaseContext()),
5893           DepClassTy::REQUIRED);
5894       if (!Stripped && this == &AA) {
5895 
5896         if (auto *I = dyn_cast<Instruction>(&V)) {
5897           if (auto *Cmp = dyn_cast<CmpInst>(&V))
5898             if (handleCmp(A, *Cmp))
5899               return true;
5900           if (handleGenericInst(A, *I))
5901             return true;
5902         }
5903         // TODO: Look the instruction and check recursively.
5904 
5905         LLVM_DEBUG(dbgs() << "[ValueSimplify] Can't be stripped more : " << V
5906                           << "\n");
5907         return false;
5908       }
5909       return checkAndUpdate(A, *this,
5910                             IRPosition::value(V, getCallBaseContext()));
5911     };
5912 
5913     bool Dummy = false;
5914     bool UsedAssumedInformation = false;
5915     if (!genericValueTraversal<bool>(A, getIRPosition(), *this, Dummy,
5916                                      VisitValueCB, getCtxI(),
5917                                      UsedAssumedInformation,
5918                                      /* UseValueSimplify */ false))
5919       if (!askSimplifiedValueForOtherAAs(A))
5920         return indicatePessimisticFixpoint();
5921 
5922     // If a candicate was found in this update, return CHANGED.
5923     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
5924                                                : ChangeStatus ::CHANGED;
5925   }
5926 
5927   /// See AbstractAttribute::trackStatistics()
5928   void trackStatistics() const override {
5929     STATS_DECLTRACK_FLOATING_ATTR(value_simplify)
5930   }
5931 };
5932 
5933 struct AAValueSimplifyFunction : AAValueSimplifyImpl {
5934   AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A)
5935       : AAValueSimplifyImpl(IRP, A) {}
5936 
5937   /// See AbstractAttribute::initialize(...).
5938   void initialize(Attributor &A) override {
5939     SimplifiedAssociatedValue = nullptr;
5940     indicateOptimisticFixpoint();
5941   }
5942   /// See AbstractAttribute::initialize(...).
5943   ChangeStatus updateImpl(Attributor &A) override {
5944     llvm_unreachable(
5945         "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
5946   }
5947   /// See AbstractAttribute::trackStatistics()
5948   void trackStatistics() const override {
5949     STATS_DECLTRACK_FN_ATTR(value_simplify)
5950   }
5951 };
5952 
5953 struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
5954   AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A)
5955       : AAValueSimplifyFunction(IRP, A) {}
5956   /// See AbstractAttribute::trackStatistics()
5957   void trackStatistics() const override {
5958     STATS_DECLTRACK_CS_ATTR(value_simplify)
5959   }
5960 };
5961 
5962 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl {
5963   AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A)
5964       : AAValueSimplifyImpl(IRP, A) {}
5965 
5966   void initialize(Attributor &A) override {
5967     AAValueSimplifyImpl::initialize(A);
5968     Function *Fn = getAssociatedFunction();
5969     if (!Fn) {
5970       indicatePessimisticFixpoint();
5971       return;
5972     }
5973     for (Argument &Arg : Fn->args()) {
5974       if (Arg.hasReturnedAttr()) {
5975         auto IRP = IRPosition::callsite_argument(*cast<CallBase>(getCtxI()),
5976                                                  Arg.getArgNo());
5977         if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_ARGUMENT &&
5978             checkAndUpdate(A, *this, IRP))
5979           indicateOptimisticFixpoint();
5980         else
5981           indicatePessimisticFixpoint();
5982         return;
5983       }
5984     }
5985   }
5986 
5987   /// See AbstractAttribute::updateImpl(...).
5988   ChangeStatus updateImpl(Attributor &A) override {
5989     auto Before = SimplifiedAssociatedValue;
5990     auto &RetAA = A.getAAFor<AAReturnedValues>(
5991         *this, IRPosition::function(*getAssociatedFunction()),
5992         DepClassTy::REQUIRED);
5993     auto PredForReturned =
5994         [&](Value &RetVal, const SmallSetVector<ReturnInst *, 4> &RetInsts) {
5995           bool UsedAssumedInformation = false;
5996           Optional<Value *> CSRetVal = A.translateArgumentToCallSiteContent(
5997               &RetVal, *cast<CallBase>(getCtxI()), *this,
5998               UsedAssumedInformation);
5999           SimplifiedAssociatedValue = AA::combineOptionalValuesInAAValueLatice(
6000               SimplifiedAssociatedValue, CSRetVal, getAssociatedType());
6001           return SimplifiedAssociatedValue != Optional<Value *>(nullptr);
6002         };
6003     if (!RetAA.checkForAllReturnedValuesAndReturnInsts(PredForReturned))
6004       if (!askSimplifiedValueForOtherAAs(A))
6005         return indicatePessimisticFixpoint();
6006     return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6007                                                : ChangeStatus ::CHANGED;
6008   }
6009 
6010   void trackStatistics() const override {
6011     STATS_DECLTRACK_CSRET_ATTR(value_simplify)
6012   }
6013 };
6014 
6015 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
6016   AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A)
6017       : AAValueSimplifyFloating(IRP, A) {}
6018 
6019   /// See AbstractAttribute::manifest(...).
6020   ChangeStatus manifest(Attributor &A) override {
6021     ChangeStatus Changed = ChangeStatus::UNCHANGED;
6022     // TODO: We should avoid simplification duplication to begin with.
6023     auto *FloatAA = A.lookupAAFor<AAValueSimplify>(
6024         IRPosition::value(getAssociatedValue()), this, DepClassTy::NONE);
6025     if (FloatAA && FloatAA->getState().isValidState())
6026       return Changed;
6027 
6028     if (auto *NewV = manifestReplacementValue(A, getCtxI())) {
6029       Use &U = cast<CallBase>(&getAnchorValue())
6030                    ->getArgOperandUse(getCallSiteArgNo());
6031       if (A.changeUseAfterManifest(U, *NewV))
6032         Changed = ChangeStatus::CHANGED;
6033     }
6034 
6035     return Changed | AAValueSimplify::manifest(A);
6036   }
6037 
6038   void trackStatistics() const override {
6039     STATS_DECLTRACK_CSARG_ATTR(value_simplify)
6040   }
6041 };
6042 } // namespace
6043 
6044 /// ----------------------- Heap-To-Stack Conversion ---------------------------
6045 namespace {
6046 struct AAHeapToStackFunction final : public AAHeapToStack {
6047 
6048   struct AllocationInfo {
6049     /// The call that allocates the memory.
6050     CallBase *const CB;
6051 
6052     /// The library function id for the allocation.
6053     LibFunc LibraryFunctionId = NotLibFunc;
6054 
6055     /// The status wrt. a rewrite.
6056     enum {
6057       STACK_DUE_TO_USE,
6058       STACK_DUE_TO_FREE,
6059       INVALID,
6060     } Status = STACK_DUE_TO_USE;
6061 
6062     /// Flag to indicate if we encountered a use that might free this allocation
6063     /// but which is not in the deallocation infos.
6064     bool HasPotentiallyFreeingUnknownUses = false;
6065 
6066     /// The set of free calls that use this allocation.
6067     SmallSetVector<CallBase *, 1> PotentialFreeCalls{};
6068   };
6069 
6070   struct DeallocationInfo {
6071     /// The call that deallocates the memory.
6072     CallBase *const CB;
6073 
6074     /// Flag to indicate if we don't know all objects this deallocation might
6075     /// free.
6076     bool MightFreeUnknownObjects = false;
6077 
6078     /// The set of allocation calls that are potentially freed.
6079     SmallSetVector<CallBase *, 1> PotentialAllocationCalls{};
6080   };
6081 
6082   AAHeapToStackFunction(const IRPosition &IRP, Attributor &A)
6083       : AAHeapToStack(IRP, A) {}
6084 
6085   ~AAHeapToStackFunction() {
6086     // Ensure we call the destructor so we release any memory allocated in the
6087     // sets.
6088     for (auto &It : AllocationInfos)
6089       It.second->~AllocationInfo();
6090     for (auto &It : DeallocationInfos)
6091       It.second->~DeallocationInfo();
6092   }
6093 
6094   void initialize(Attributor &A) override {
6095     AAHeapToStack::initialize(A);
6096 
6097     const Function *F = getAnchorScope();
6098     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6099 
6100     auto AllocationIdentifierCB = [&](Instruction &I) {
6101       CallBase *CB = dyn_cast<CallBase>(&I);
6102       if (!CB)
6103         return true;
6104       if (isFreeCall(CB, TLI)) {
6105         DeallocationInfos[CB] = new (A.Allocator) DeallocationInfo{CB};
6106         return true;
6107       }
6108       // To do heap to stack, we need to know that the allocation itself is
6109       // removable once uses are rewritten, and that we can initialize the
6110       // alloca to the same pattern as the original allocation result.
6111       if (isAllocationFn(CB, TLI) && isAllocRemovable(CB, TLI)) {
6112         auto *I8Ty = Type::getInt8Ty(CB->getParent()->getContext());
6113         if (nullptr != getInitialValueOfAllocation(CB, TLI, I8Ty)) {
6114           AllocationInfo *AI = new (A.Allocator) AllocationInfo{CB};
6115           AllocationInfos[CB] = AI;
6116           if (TLI)
6117             TLI->getLibFunc(*CB, AI->LibraryFunctionId);
6118         }
6119       }
6120       return true;
6121     };
6122 
6123     bool UsedAssumedInformation = false;
6124     bool Success = A.checkForAllCallLikeInstructions(
6125         AllocationIdentifierCB, *this, UsedAssumedInformation,
6126         /* CheckBBLivenessOnly */ false,
6127         /* CheckPotentiallyDead */ true);
6128     (void)Success;
6129     assert(Success && "Did not expect the call base visit callback to fail!");
6130 
6131     Attributor::SimplifictionCallbackTy SCB =
6132         [](const IRPosition &, const AbstractAttribute *,
6133            bool &) -> Optional<Value *> { return nullptr; };
6134     for (const auto &It : AllocationInfos)
6135       A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
6136                                        SCB);
6137     for (const auto &It : DeallocationInfos)
6138       A.registerSimplificationCallback(IRPosition::callsite_returned(*It.first),
6139                                        SCB);
6140   }
6141 
6142   const std::string getAsStr() const override {
6143     unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0;
6144     for (const auto &It : AllocationInfos) {
6145       if (It.second->Status == AllocationInfo::INVALID)
6146         ++NumInvalidMallocs;
6147       else
6148         ++NumH2SMallocs;
6149     }
6150     return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) + "/" +
6151            std::to_string(NumInvalidMallocs);
6152   }
6153 
6154   /// See AbstractAttribute::trackStatistics().
6155   void trackStatistics() const override {
6156     STATS_DECL(
6157         MallocCalls, Function,
6158         "Number of malloc/calloc/aligned_alloc calls converted to allocas");
6159     for (auto &It : AllocationInfos)
6160       if (It.second->Status != AllocationInfo::INVALID)
6161         ++BUILD_STAT_NAME(MallocCalls, Function);
6162   }
6163 
6164   bool isAssumedHeapToStack(const CallBase &CB) const override {
6165     if (isValidState())
6166       if (AllocationInfo *AI =
6167               AllocationInfos.lookup(const_cast<CallBase *>(&CB)))
6168         return AI->Status != AllocationInfo::INVALID;
6169     return false;
6170   }
6171 
6172   bool isAssumedHeapToStackRemovedFree(CallBase &CB) const override {
6173     if (!isValidState())
6174       return false;
6175 
6176     for (auto &It : AllocationInfos) {
6177       AllocationInfo &AI = *It.second;
6178       if (AI.Status == AllocationInfo::INVALID)
6179         continue;
6180 
6181       if (AI.PotentialFreeCalls.count(&CB))
6182         return true;
6183     }
6184 
6185     return false;
6186   }
6187 
6188   ChangeStatus manifest(Attributor &A) override {
6189     assert(getState().isValidState() &&
6190            "Attempted to manifest an invalid state!");
6191 
6192     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
6193     Function *F = getAnchorScope();
6194     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6195 
6196     for (auto &It : AllocationInfos) {
6197       AllocationInfo &AI = *It.second;
6198       if (AI.Status == AllocationInfo::INVALID)
6199         continue;
6200 
6201       for (CallBase *FreeCall : AI.PotentialFreeCalls) {
6202         LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n");
6203         A.deleteAfterManifest(*FreeCall);
6204         HasChanged = ChangeStatus::CHANGED;
6205       }
6206 
6207       LLVM_DEBUG(dbgs() << "H2S: Removing malloc-like call: " << *AI.CB
6208                         << "\n");
6209 
6210       auto Remark = [&](OptimizationRemark OR) {
6211         LibFunc IsAllocShared;
6212         if (TLI->getLibFunc(*AI.CB, IsAllocShared))
6213           if (IsAllocShared == LibFunc___kmpc_alloc_shared)
6214             return OR << "Moving globalized variable to the stack.";
6215         return OR << "Moving memory allocation from the heap to the stack.";
6216       };
6217       if (AI.LibraryFunctionId == LibFunc___kmpc_alloc_shared)
6218         A.emitRemark<OptimizationRemark>(AI.CB, "OMP110", Remark);
6219       else
6220         A.emitRemark<OptimizationRemark>(AI.CB, "HeapToStack", Remark);
6221 
6222       const DataLayout &DL = A.getInfoCache().getDL();
6223       Value *Size;
6224       Optional<APInt> SizeAPI = getSize(A, *this, AI);
6225       if (SizeAPI.hasValue()) {
6226         Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
6227       } else {
6228         LLVMContext &Ctx = AI.CB->getContext();
6229         ObjectSizeOpts Opts;
6230         ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, Opts);
6231         SizeOffsetEvalType SizeOffsetPair = Eval.compute(AI.CB);
6232         assert(SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown() &&
6233                cast<ConstantInt>(SizeOffsetPair.second)->isZero());
6234         Size = SizeOffsetPair.first;
6235       }
6236 
6237       Align Alignment(1);
6238       if (MaybeAlign RetAlign = AI.CB->getRetAlign())
6239         Alignment = max(Alignment, RetAlign);
6240       if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
6241         Optional<APInt> AlignmentAPI = getAPInt(A, *this, *Align);
6242         assert(AlignmentAPI.hasValue() &&
6243                "Expected an alignment during manifest!");
6244         Alignment =
6245             max(Alignment, MaybeAlign(AlignmentAPI.getValue().getZExtValue()));
6246       }
6247 
6248       // TODO: Hoist the alloca towards the function entry.
6249       unsigned AS = DL.getAllocaAddrSpace();
6250       Instruction *Alloca = new AllocaInst(Type::getInt8Ty(F->getContext()), AS,
6251                                            Size, Alignment, "", AI.CB);
6252 
6253       if (Alloca->getType() != AI.CB->getType())
6254         Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6255             Alloca, AI.CB->getType(), "malloc_cast", AI.CB);
6256 
6257       auto *I8Ty = Type::getInt8Ty(F->getContext());
6258       auto *InitVal = getInitialValueOfAllocation(AI.CB, TLI, I8Ty);
6259       assert(InitVal &&
6260              "Must be able to materialize initial memory state of allocation");
6261 
6262       A.changeAfterManifest(IRPosition::inst(*AI.CB), *Alloca);
6263 
6264       if (auto *II = dyn_cast<InvokeInst>(AI.CB)) {
6265         auto *NBB = II->getNormalDest();
6266         BranchInst::Create(NBB, AI.CB->getParent());
6267         A.deleteAfterManifest(*AI.CB);
6268       } else {
6269         A.deleteAfterManifest(*AI.CB);
6270       }
6271 
6272       // Initialize the alloca with the same value as used by the allocation
6273       // function.  We can skip undef as the initial value of an alloc is
6274       // undef, and the memset would simply end up being DSEd.
6275       if (!isa<UndefValue>(InitVal)) {
6276         IRBuilder<> Builder(Alloca->getNextNode());
6277         // TODO: Use alignment above if align!=1
6278         Builder.CreateMemSet(Alloca, InitVal, Size, None);
6279       }
6280       HasChanged = ChangeStatus::CHANGED;
6281     }
6282 
6283     return HasChanged;
6284   }
6285 
6286   Optional<APInt> getAPInt(Attributor &A, const AbstractAttribute &AA,
6287                            Value &V) {
6288     bool UsedAssumedInformation = false;
6289     Optional<Constant *> SimpleV =
6290         A.getAssumedConstant(V, AA, UsedAssumedInformation);
6291     if (!SimpleV.hasValue())
6292       return APInt(64, 0);
6293     if (auto *CI = dyn_cast_or_null<ConstantInt>(SimpleV.getValue()))
6294       return CI->getValue();
6295     return llvm::None;
6296   }
6297 
6298   Optional<APInt> getSize(Attributor &A, const AbstractAttribute &AA,
6299                           AllocationInfo &AI) {
6300     auto Mapper = [&](const Value *V) -> const Value * {
6301       bool UsedAssumedInformation = false;
6302       if (Optional<Constant *> SimpleV =
6303               A.getAssumedConstant(*V, AA, UsedAssumedInformation))
6304         if (*SimpleV)
6305           return *SimpleV;
6306       return V;
6307     };
6308 
6309     const Function *F = getAnchorScope();
6310     const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6311     return getAllocSize(AI.CB, TLI, Mapper);
6312   }
6313 
6314   /// Collection of all malloc-like calls in a function with associated
6315   /// information.
6316   MapVector<CallBase *, AllocationInfo *> AllocationInfos;
6317 
6318   /// Collection of all free-like calls in a function with associated
6319   /// information.
6320   MapVector<CallBase *, DeallocationInfo *> DeallocationInfos;
6321 
6322   ChangeStatus updateImpl(Attributor &A) override;
6323 };
6324 
6325 ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &A) {
6326   ChangeStatus Changed = ChangeStatus::UNCHANGED;
6327   const Function *F = getAnchorScope();
6328   const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F);
6329 
6330   const auto &LivenessAA =
6331       A.getAAFor<AAIsDead>(*this, IRPosition::function(*F), DepClassTy::NONE);
6332 
6333   MustBeExecutedContextExplorer &Explorer =
6334       A.getInfoCache().getMustBeExecutedContextExplorer();
6335 
6336   bool StackIsAccessibleByOtherThreads =
6337       A.getInfoCache().stackIsAccessibleByOtherThreads();
6338 
6339   // Flag to ensure we update our deallocation information at most once per
6340   // updateImpl call and only if we use the free check reasoning.
6341   bool HasUpdatedFrees = false;
6342 
6343   auto UpdateFrees = [&]() {
6344     HasUpdatedFrees = true;
6345 
6346     for (auto &It : DeallocationInfos) {
6347       DeallocationInfo &DI = *It.second;
6348       // For now we cannot use deallocations that have unknown inputs, skip
6349       // them.
6350       if (DI.MightFreeUnknownObjects)
6351         continue;
6352 
6353       // No need to analyze dead calls, ignore them instead.
6354       bool UsedAssumedInformation = false;
6355       if (A.isAssumedDead(*DI.CB, this, &LivenessAA, UsedAssumedInformation,
6356                           /* CheckBBLivenessOnly */ true))
6357         continue;
6358 
6359       // Use the optimistic version to get the freed objects, ignoring dead
6360       // branches etc.
6361       SmallVector<Value *, 8> Objects;
6362       if (!AA::getAssumedUnderlyingObjects(A, *DI.CB->getArgOperand(0), Objects,
6363                                            *this, DI.CB,
6364                                            UsedAssumedInformation)) {
6365         LLVM_DEBUG(
6366             dbgs()
6367             << "[H2S] Unexpected failure in getAssumedUnderlyingObjects!\n");
6368         DI.MightFreeUnknownObjects = true;
6369         continue;
6370       }
6371 
6372       // Check each object explicitly.
6373       for (auto *Obj : Objects) {
6374         // Free of null and undef can be ignored as no-ops (or UB in the latter
6375         // case).
6376         if (isa<ConstantPointerNull>(Obj) || isa<UndefValue>(Obj))
6377           continue;
6378 
6379         CallBase *ObjCB = dyn_cast<CallBase>(Obj);
6380         if (!ObjCB) {
6381           LLVM_DEBUG(dbgs()
6382                      << "[H2S] Free of a non-call object: " << *Obj << "\n");
6383           DI.MightFreeUnknownObjects = true;
6384           continue;
6385         }
6386 
6387         AllocationInfo *AI = AllocationInfos.lookup(ObjCB);
6388         if (!AI) {
6389           LLVM_DEBUG(dbgs() << "[H2S] Free of a non-allocation object: " << *Obj
6390                             << "\n");
6391           DI.MightFreeUnknownObjects = true;
6392           continue;
6393         }
6394 
6395         DI.PotentialAllocationCalls.insert(ObjCB);
6396       }
6397     }
6398   };
6399 
6400   auto FreeCheck = [&](AllocationInfo &AI) {
6401     // If the stack is not accessible by other threads, the "must-free" logic
6402     // doesn't apply as the pointer could be shared and needs to be places in
6403     // "shareable" memory.
6404     if (!StackIsAccessibleByOtherThreads) {
6405       auto &NoSyncAA =
6406           A.getAAFor<AANoSync>(*this, getIRPosition(), DepClassTy::OPTIONAL);
6407       if (!NoSyncAA.isAssumedNoSync()) {
6408         LLVM_DEBUG(
6409             dbgs() << "[H2S] found an escaping use, stack is not accessible by "
6410                       "other threads and function is not nosync:\n");
6411         return false;
6412       }
6413     }
6414     if (!HasUpdatedFrees)
6415       UpdateFrees();
6416 
6417     // TODO: Allow multi exit functions that have different free calls.
6418     if (AI.PotentialFreeCalls.size() != 1) {
6419       LLVM_DEBUG(dbgs() << "[H2S] did not find one free call but "
6420                         << AI.PotentialFreeCalls.size() << "\n");
6421       return false;
6422     }
6423     CallBase *UniqueFree = *AI.PotentialFreeCalls.begin();
6424     DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree);
6425     if (!DI) {
6426       LLVM_DEBUG(
6427           dbgs() << "[H2S] unique free call was not known as deallocation call "
6428                  << *UniqueFree << "\n");
6429       return false;
6430     }
6431     if (DI->MightFreeUnknownObjects) {
6432       LLVM_DEBUG(
6433           dbgs() << "[H2S] unique free call might free unknown allocations\n");
6434       return false;
6435     }
6436     if (DI->PotentialAllocationCalls.size() > 1) {
6437       LLVM_DEBUG(dbgs() << "[H2S] unique free call might free "
6438                         << DI->PotentialAllocationCalls.size()
6439                         << " different allocations\n");
6440       return false;
6441     }
6442     if (*DI->PotentialAllocationCalls.begin() != AI.CB) {
6443       LLVM_DEBUG(
6444           dbgs()
6445           << "[H2S] unique free call not known to free this allocation but "
6446           << **DI->PotentialAllocationCalls.begin() << "\n");
6447       return false;
6448     }
6449     Instruction *CtxI = isa<InvokeInst>(AI.CB) ? AI.CB : AI.CB->getNextNode();
6450     if (!Explorer.findInContextOf(UniqueFree, CtxI)) {
6451       LLVM_DEBUG(
6452           dbgs()
6453           << "[H2S] unique free call might not be executed with the allocation "
6454           << *UniqueFree << "\n");
6455       return false;
6456     }
6457     return true;
6458   };
6459 
6460   auto UsesCheck = [&](AllocationInfo &AI) {
6461     bool ValidUsesOnly = true;
6462 
6463     auto Pred = [&](const Use &U, bool &Follow) -> bool {
6464       Instruction *UserI = cast<Instruction>(U.getUser());
6465       if (isa<LoadInst>(UserI))
6466         return true;
6467       if (auto *SI = dyn_cast<StoreInst>(UserI)) {
6468         if (SI->getValueOperand() == U.get()) {
6469           LLVM_DEBUG(dbgs()
6470                      << "[H2S] escaping store to memory: " << *UserI << "\n");
6471           ValidUsesOnly = false;
6472         } else {
6473           // A store into the malloc'ed memory is fine.
6474         }
6475         return true;
6476       }
6477       if (auto *CB = dyn_cast<CallBase>(UserI)) {
6478         if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd())
6479           return true;
6480         if (DeallocationInfos.count(CB)) {
6481           AI.PotentialFreeCalls.insert(CB);
6482           return true;
6483         }
6484 
6485         unsigned ArgNo = CB->getArgOperandNo(&U);
6486 
6487         const auto &NoCaptureAA = A.getAAFor<AANoCapture>(
6488             *this, IRPosition::callsite_argument(*CB, ArgNo),
6489             DepClassTy::OPTIONAL);
6490 
6491         // If a call site argument use is nofree, we are fine.
6492         const auto &ArgNoFreeAA = A.getAAFor<AANoFree>(
6493             *this, IRPosition::callsite_argument(*CB, ArgNo),
6494             DepClassTy::OPTIONAL);
6495 
6496         bool MaybeCaptured = !NoCaptureAA.isAssumedNoCapture();
6497         bool MaybeFreed = !ArgNoFreeAA.isAssumedNoFree();
6498         if (MaybeCaptured ||
6499             (AI.LibraryFunctionId != LibFunc___kmpc_alloc_shared &&
6500              MaybeFreed)) {
6501           AI.HasPotentiallyFreeingUnknownUses |= MaybeFreed;
6502 
6503           // Emit a missed remark if this is missed OpenMP globalization.
6504           auto Remark = [&](OptimizationRemarkMissed ORM) {
6505             return ORM
6506                    << "Could not move globalized variable to the stack. "
6507                       "Variable is potentially captured in call. Mark "
6508                       "parameter as `__attribute__((noescape))` to override.";
6509           };
6510 
6511           if (ValidUsesOnly &&
6512               AI.LibraryFunctionId == LibFunc___kmpc_alloc_shared)
6513             A.emitRemark<OptimizationRemarkMissed>(CB, "OMP113", Remark);
6514 
6515           LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n");
6516           ValidUsesOnly = false;
6517         }
6518         return true;
6519       }
6520 
6521       if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
6522           isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
6523         Follow = true;
6524         return true;
6525       }
6526       // Unknown user for which we can not track uses further (in a way that
6527       // makes sense).
6528       LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n");
6529       ValidUsesOnly = false;
6530       return true;
6531     };
6532     if (!A.checkForAllUses(Pred, *this, *AI.CB))
6533       return false;
6534     return ValidUsesOnly;
6535   };
6536 
6537   // The actual update starts here. We look at all allocations and depending on
6538   // their status perform the appropriate check(s).
6539   for (auto &It : AllocationInfos) {
6540     AllocationInfo &AI = *It.second;
6541     if (AI.Status == AllocationInfo::INVALID)
6542       continue;
6543 
6544     if (Value *Align = getAllocAlignment(AI.CB, TLI)) {
6545       Optional<APInt> APAlign = getAPInt(A, *this, *Align);
6546       if (!APAlign) {
6547         // Can't generate an alloca which respects the required alignment
6548         // on the allocation.
6549         LLVM_DEBUG(dbgs() << "[H2S] Unknown allocation alignment: " << *AI.CB
6550                           << "\n");
6551         AI.Status = AllocationInfo::INVALID;
6552         Changed = ChangeStatus::CHANGED;
6553         continue;
6554       } else {
6555         if (APAlign->ugt(llvm::Value::MaximumAlignment) ||
6556             !APAlign->isPowerOf2()) {
6557           LLVM_DEBUG(dbgs() << "[H2S] Invalid allocation alignment: " << APAlign
6558                             << "\n");
6559           AI.Status = AllocationInfo::INVALID;
6560           Changed = ChangeStatus::CHANGED;
6561           continue;
6562         }
6563       }
6564     }
6565 
6566     if (MaxHeapToStackSize != -1) {
6567       Optional<APInt> Size = getSize(A, *this, AI);
6568       if (!Size.hasValue() || Size.getValue().ugt(MaxHeapToStackSize)) {
6569         LLVM_DEBUG({
6570           if (!Size.hasValue())
6571             dbgs() << "[H2S] Unknown allocation size: " << *AI.CB << "\n";
6572           else
6573             dbgs() << "[H2S] Allocation size too large: " << *AI.CB << " vs. "
6574                    << MaxHeapToStackSize << "\n";
6575         });
6576 
6577         AI.Status = AllocationInfo::INVALID;
6578         Changed = ChangeStatus::CHANGED;
6579         continue;
6580       }
6581     }
6582 
6583     switch (AI.Status) {
6584     case AllocationInfo::STACK_DUE_TO_USE:
6585       if (UsesCheck(AI))
6586         continue;
6587       AI.Status = AllocationInfo::STACK_DUE_TO_FREE;
6588       LLVM_FALLTHROUGH;
6589     case AllocationInfo::STACK_DUE_TO_FREE:
6590       if (FreeCheck(AI))
6591         continue;
6592       AI.Status = AllocationInfo::INVALID;
6593       Changed = ChangeStatus::CHANGED;
6594       continue;
6595     case AllocationInfo::INVALID:
6596       llvm_unreachable("Invalid allocations should never reach this point!");
6597     };
6598   }
6599 
6600   return Changed;
6601 }
6602 } // namespace
6603 
6604 /// ----------------------- Privatizable Pointers ------------------------------
6605 namespace {
6606 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr {
6607   AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A)
6608       : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {}
6609 
6610   ChangeStatus indicatePessimisticFixpoint() override {
6611     AAPrivatizablePtr::indicatePessimisticFixpoint();
6612     PrivatizableType = nullptr;
6613     return ChangeStatus::CHANGED;
6614   }
6615 
6616   /// Identify the type we can chose for a private copy of the underlying
6617   /// argument. None means it is not clear yet, nullptr means there is none.
6618   virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0;
6619 
6620   /// Return a privatizable type that encloses both T0 and T1.
6621   /// TODO: This is merely a stub for now as we should manage a mapping as well.
6622   Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) {
6623     if (!T0.hasValue())
6624       return T1;
6625     if (!T1.hasValue())
6626       return T0;
6627     if (T0 == T1)
6628       return T0;
6629     return nullptr;
6630   }
6631 
6632   Optional<Type *> getPrivatizableType() const override {
6633     return PrivatizableType;
6634   }
6635 
6636   const std::string getAsStr() const override {
6637     return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]";
6638   }
6639 
6640 protected:
6641   Optional<Type *> PrivatizableType;
6642 };
6643 
6644 // TODO: Do this for call site arguments (probably also other values) as well.
6645 
6646 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl {
6647   AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A)
6648       : AAPrivatizablePtrImpl(IRP, A) {}
6649 
6650   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
6651   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
6652     // If this is a byval argument and we know all the call sites (so we can
6653     // rewrite them), there is no need to check them explicitly.
6654     bool UsedAssumedInformation = false;
6655     SmallVector<Attribute, 1> Attrs;
6656     getAttrs({Attribute::ByVal}, Attrs, /* IgnoreSubsumingPositions */ true);
6657     if (!Attrs.empty() &&
6658         A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this,
6659                                true, UsedAssumedInformation))
6660       return Attrs[0].getValueAsType();
6661 
6662     Optional<Type *> Ty;
6663     unsigned ArgNo = getIRPosition().getCallSiteArgNo();
6664 
6665     // Make sure the associated call site argument has the same type at all call
6666     // sites and it is an allocation we know is safe to privatize, for now that
6667     // means we only allow alloca instructions.
6668     // TODO: We can additionally analyze the accesses in the callee to  create
6669     //       the type from that information instead. That is a little more
6670     //       involved and will be done in a follow up patch.
6671     auto CallSiteCheck = [&](AbstractCallSite ACS) {
6672       IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo);
6673       // Check if a coresponding argument was found or if it is one not
6674       // associated (which can happen for callback calls).
6675       if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID)
6676         return false;
6677 
6678       // Check that all call sites agree on a type.
6679       auto &PrivCSArgAA =
6680           A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos, DepClassTy::REQUIRED);
6681       Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType();
6682 
6683       LLVM_DEBUG({
6684         dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: ";
6685         if (CSTy.hasValue() && CSTy.getValue())
6686           CSTy.getValue()->print(dbgs());
6687         else if (CSTy.hasValue())
6688           dbgs() << "<nullptr>";
6689         else
6690           dbgs() << "<none>";
6691       });
6692 
6693       Ty = combineTypes(Ty, CSTy);
6694 
6695       LLVM_DEBUG({
6696         dbgs() << " : New Type: ";
6697         if (Ty.hasValue() && Ty.getValue())
6698           Ty.getValue()->print(dbgs());
6699         else if (Ty.hasValue())
6700           dbgs() << "<nullptr>";
6701         else
6702           dbgs() << "<none>";
6703         dbgs() << "\n";
6704       });
6705 
6706       return !Ty.hasValue() || Ty.getValue();
6707     };
6708 
6709     if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
6710                                 UsedAssumedInformation))
6711       return nullptr;
6712     return Ty;
6713   }
6714 
6715   /// See AbstractAttribute::updateImpl(...).
6716   ChangeStatus updateImpl(Attributor &A) override {
6717     PrivatizableType = identifyPrivatizableType(A);
6718     if (!PrivatizableType.hasValue())
6719       return ChangeStatus::UNCHANGED;
6720     if (!PrivatizableType.getValue())
6721       return indicatePessimisticFixpoint();
6722 
6723     // The dependence is optional so we don't give up once we give up on the
6724     // alignment.
6725     A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()),
6726                         DepClassTy::OPTIONAL);
6727 
6728     // Avoid arguments with padding for now.
6729     if (!getIRPosition().hasAttr(Attribute::ByVal) &&
6730         !ArgumentPromotionPass::isDenselyPacked(PrivatizableType.getValue(),
6731                                                 A.getInfoCache().getDL())) {
6732       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n");
6733       return indicatePessimisticFixpoint();
6734     }
6735 
6736     // Collect the types that will replace the privatizable type in the function
6737     // signature.
6738     SmallVector<Type *, 16> ReplacementTypes;
6739     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
6740 
6741     // Verify callee and caller agree on how the promoted argument would be
6742     // passed.
6743     Function &Fn = *getIRPosition().getAnchorScope();
6744     const auto *TTI =
6745         A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
6746     if (!TTI) {
6747       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Missing TTI for function "
6748                         << Fn.getName() << "\n");
6749       return indicatePessimisticFixpoint();
6750     }
6751 
6752     auto CallSiteCheck = [&](AbstractCallSite ACS) {
6753       CallBase *CB = ACS.getInstruction();
6754       return TTI->areTypesABICompatible(
6755           CB->getCaller(), CB->getCalledFunction(), ReplacementTypes);
6756     };
6757     bool UsedAssumedInformation = false;
6758     if (!A.checkForAllCallSites(CallSiteCheck, *this, true,
6759                                 UsedAssumedInformation)) {
6760       LLVM_DEBUG(
6761           dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for "
6762                  << Fn.getName() << "\n");
6763       return indicatePessimisticFixpoint();
6764     }
6765 
6766     // Register a rewrite of the argument.
6767     Argument *Arg = getAssociatedArgument();
6768     if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
6769       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n");
6770       return indicatePessimisticFixpoint();
6771     }
6772 
6773     unsigned ArgNo = Arg->getArgNo();
6774 
6775     // Helper to check if for the given call site the associated argument is
6776     // passed to a callback where the privatization would be different.
6777     auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
6778       SmallVector<const Use *, 4> CallbackUses;
6779       AbstractCallSite::getCallbackUses(CB, CallbackUses);
6780       for (const Use *U : CallbackUses) {
6781         AbstractCallSite CBACS(U);
6782         assert(CBACS && CBACS.isCallbackCall());
6783         for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
6784           int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
6785 
6786           LLVM_DEBUG({
6787             dbgs()
6788                 << "[AAPrivatizablePtr] Argument " << *Arg
6789                 << "check if can be privatized in the context of its parent ("
6790                 << Arg->getParent()->getName()
6791                 << ")\n[AAPrivatizablePtr] because it is an argument in a "
6792                    "callback ("
6793                 << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
6794                 << ")\n[AAPrivatizablePtr] " << CBArg << " : "
6795                 << CBACS.getCallArgOperand(CBArg) << " vs "
6796                 << CB.getArgOperand(ArgNo) << "\n"
6797                 << "[AAPrivatizablePtr] " << CBArg << " : "
6798                 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n";
6799           });
6800 
6801           if (CBArgNo != int(ArgNo))
6802             continue;
6803           const auto &CBArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
6804               *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED);
6805           if (CBArgPrivAA.isValidState()) {
6806             auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType();
6807             if (!CBArgPrivTy.hasValue())
6808               continue;
6809             if (CBArgPrivTy.getValue() == PrivatizableType)
6810               continue;
6811           }
6812 
6813           LLVM_DEBUG({
6814             dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
6815                    << " cannot be privatized in the context of its parent ("
6816                    << Arg->getParent()->getName()
6817                    << ")\n[AAPrivatizablePtr] because it is an argument in a "
6818                       "callback ("
6819                    << CBArgNo << "@" << CBACS.getCalledFunction()->getName()
6820                    << ").\n[AAPrivatizablePtr] for which the argument "
6821                       "privatization is not compatible.\n";
6822           });
6823           return false;
6824         }
6825       }
6826       return true;
6827     };
6828 
6829     // Helper to check if for the given call site the associated argument is
6830     // passed to a direct call where the privatization would be different.
6831     auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
6832       CallBase *DC = cast<CallBase>(ACS.getInstruction());
6833       int DCArgNo = ACS.getCallArgOperandNo(ArgNo);
6834       assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->arg_size() &&
6835              "Expected a direct call operand for callback call operand");
6836 
6837       LLVM_DEBUG({
6838         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
6839                << " check if be privatized in the context of its parent ("
6840                << Arg->getParent()->getName()
6841                << ")\n[AAPrivatizablePtr] because it is an argument in a "
6842                   "direct call of ("
6843                << DCArgNo << "@" << DC->getCalledFunction()->getName()
6844                << ").\n";
6845       });
6846 
6847       Function *DCCallee = DC->getCalledFunction();
6848       if (unsigned(DCArgNo) < DCCallee->arg_size()) {
6849         const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>(
6850             *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)),
6851             DepClassTy::REQUIRED);
6852         if (DCArgPrivAA.isValidState()) {
6853           auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType();
6854           if (!DCArgPrivTy.hasValue())
6855             return true;
6856           if (DCArgPrivTy.getValue() == PrivatizableType)
6857             return true;
6858         }
6859       }
6860 
6861       LLVM_DEBUG({
6862         dbgs() << "[AAPrivatizablePtr] Argument " << *Arg
6863                << " cannot be privatized in the context of its parent ("
6864                << Arg->getParent()->getName()
6865                << ")\n[AAPrivatizablePtr] because it is an argument in a "
6866                   "direct call of ("
6867                << ACS.getInstruction()->getCalledFunction()->getName()
6868                << ").\n[AAPrivatizablePtr] for which the argument "
6869                   "privatization is not compatible.\n";
6870       });
6871       return false;
6872     };
6873 
6874     // Helper to check if the associated argument is used at the given abstract
6875     // call site in a way that is incompatible with the privatization assumed
6876     // here.
6877     auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
6878       if (ACS.isDirectCall())
6879         return IsCompatiblePrivArgOfCallback(*ACS.getInstruction());
6880       if (ACS.isCallbackCall())
6881         return IsCompatiblePrivArgOfDirectCS(ACS);
6882       return false;
6883     };
6884 
6885     if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true,
6886                                 UsedAssumedInformation))
6887       return indicatePessimisticFixpoint();
6888 
6889     return ChangeStatus::UNCHANGED;
6890   }
6891 
6892   /// Given a type to private \p PrivType, collect the constituates (which are
6893   /// used) in \p ReplacementTypes.
6894   static void
6895   identifyReplacementTypes(Type *PrivType,
6896                            SmallVectorImpl<Type *> &ReplacementTypes) {
6897     // TODO: For now we expand the privatization type to the fullest which can
6898     //       lead to dead arguments that need to be removed later.
6899     assert(PrivType && "Expected privatizable type!");
6900 
6901     // Traverse the type, extract constituate types on the outermost level.
6902     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
6903       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
6904         ReplacementTypes.push_back(PrivStructType->getElementType(u));
6905     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
6906       ReplacementTypes.append(PrivArrayType->getNumElements(),
6907                               PrivArrayType->getElementType());
6908     } else {
6909       ReplacementTypes.push_back(PrivType);
6910     }
6911   }
6912 
6913   /// Initialize \p Base according to the type \p PrivType at position \p IP.
6914   /// The values needed are taken from the arguments of \p F starting at
6915   /// position \p ArgNo.
6916   static void createInitialization(Type *PrivType, Value &Base, Function &F,
6917                                    unsigned ArgNo, Instruction &IP) {
6918     assert(PrivType && "Expected privatizable type!");
6919 
6920     IRBuilder<NoFolder> IRB(&IP);
6921     const DataLayout &DL = F.getParent()->getDataLayout();
6922 
6923     // Traverse the type, build GEPs and stores.
6924     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
6925       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
6926       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
6927         Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo();
6928         Value *Ptr =
6929             constructPointer(PointeeTy, PrivType, &Base,
6930                              PrivStructLayout->getElementOffset(u), IRB, DL);
6931         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
6932       }
6933     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
6934       Type *PointeeTy = PrivArrayType->getElementType();
6935       Type *PointeePtrTy = PointeeTy->getPointerTo();
6936       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
6937       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
6938         Value *Ptr = constructPointer(PointeePtrTy, PrivType, &Base,
6939                                       u * PointeeTySize, IRB, DL);
6940         new StoreInst(F.getArg(ArgNo + u), Ptr, &IP);
6941       }
6942     } else {
6943       new StoreInst(F.getArg(ArgNo), &Base, &IP);
6944     }
6945   }
6946 
6947   /// Extract values from \p Base according to the type \p PrivType at the
6948   /// call position \p ACS. The values are appended to \p ReplacementValues.
6949   void createReplacementValues(Align Alignment, Type *PrivType,
6950                                AbstractCallSite ACS, Value *Base,
6951                                SmallVectorImpl<Value *> &ReplacementValues) {
6952     assert(Base && "Expected base value!");
6953     assert(PrivType && "Expected privatizable type!");
6954     Instruction *IP = ACS.getInstruction();
6955 
6956     IRBuilder<NoFolder> IRB(IP);
6957     const DataLayout &DL = IP->getModule()->getDataLayout();
6958 
6959     Type *PrivPtrType = PrivType->getPointerTo();
6960     if (Base->getType() != PrivPtrType)
6961       Base = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6962           Base, PrivPtrType, "", ACS.getInstruction());
6963 
6964     // Traverse the type, build GEPs and loads.
6965     if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) {
6966       const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType);
6967       for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
6968         Type *PointeeTy = PrivStructType->getElementType(u);
6969         Value *Ptr =
6970             constructPointer(PointeeTy->getPointerTo(), PrivType, Base,
6971                              PrivStructLayout->getElementOffset(u), IRB, DL);
6972         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
6973         L->setAlignment(Alignment);
6974         ReplacementValues.push_back(L);
6975       }
6976     } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) {
6977       Type *PointeeTy = PrivArrayType->getElementType();
6978       uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy);
6979       Type *PointeePtrTy = PointeeTy->getPointerTo();
6980       for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
6981         Value *Ptr = constructPointer(PointeePtrTy, PrivType, Base,
6982                                       u * PointeeTySize, IRB, DL);
6983         LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP);
6984         L->setAlignment(Alignment);
6985         ReplacementValues.push_back(L);
6986       }
6987     } else {
6988       LoadInst *L = new LoadInst(PrivType, Base, "", IP);
6989       L->setAlignment(Alignment);
6990       ReplacementValues.push_back(L);
6991     }
6992   }
6993 
6994   /// See AbstractAttribute::manifest(...)
6995   ChangeStatus manifest(Attributor &A) override {
6996     if (!PrivatizableType.hasValue())
6997       return ChangeStatus::UNCHANGED;
6998     assert(PrivatizableType.getValue() && "Expected privatizable type!");
6999 
7000     // Collect all tail calls in the function as we cannot allow new allocas to
7001     // escape into tail recursion.
7002     // TODO: Be smarter about new allocas escaping into tail calls.
7003     SmallVector<CallInst *, 16> TailCalls;
7004     bool UsedAssumedInformation = false;
7005     if (!A.checkForAllInstructions(
7006             [&](Instruction &I) {
7007               CallInst &CI = cast<CallInst>(I);
7008               if (CI.isTailCall())
7009                 TailCalls.push_back(&CI);
7010               return true;
7011             },
7012             *this, {Instruction::Call}, UsedAssumedInformation))
7013       return ChangeStatus::UNCHANGED;
7014 
7015     Argument *Arg = getAssociatedArgument();
7016     // Query AAAlign attribute for alignment of associated argument to
7017     // determine the best alignment of loads.
7018     const auto &AlignAA =
7019         A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg), DepClassTy::NONE);
7020 
7021     // Callback to repair the associated function. A new alloca is placed at the
7022     // beginning and initialized with the values passed through arguments. The
7023     // new alloca replaces the use of the old pointer argument.
7024     Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB =
7025         [=](const Attributor::ArgumentReplacementInfo &ARI,
7026             Function &ReplacementFn, Function::arg_iterator ArgIt) {
7027           BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
7028           Instruction *IP = &*EntryBB.getFirstInsertionPt();
7029           const DataLayout &DL = IP->getModule()->getDataLayout();
7030           unsigned AS = DL.getAllocaAddrSpace();
7031           Instruction *AI = new AllocaInst(PrivatizableType.getValue(), AS,
7032                                            Arg->getName() + ".priv", IP);
7033           createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn,
7034                                ArgIt->getArgNo(), *IP);
7035 
7036           if (AI->getType() != Arg->getType())
7037             AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
7038                 AI, Arg->getType(), "", IP);
7039           Arg->replaceAllUsesWith(AI);
7040 
7041           for (CallInst *CI : TailCalls)
7042             CI->setTailCall(false);
7043         };
7044 
7045     // Callback to repair a call site of the associated function. The elements
7046     // of the privatizable type are loaded prior to the call and passed to the
7047     // new function version.
7048     Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB =
7049         [=, &AlignAA](const Attributor::ArgumentReplacementInfo &ARI,
7050                       AbstractCallSite ACS,
7051                       SmallVectorImpl<Value *> &NewArgOperands) {
7052           // When no alignment is specified for the load instruction,
7053           // natural alignment is assumed.
7054           createReplacementValues(
7055               assumeAligned(AlignAA.getAssumedAlign()),
7056               PrivatizableType.getValue(), ACS,
7057               ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()),
7058               NewArgOperands);
7059         };
7060 
7061     // Collect the types that will replace the privatizable type in the function
7062     // signature.
7063     SmallVector<Type *, 16> ReplacementTypes;
7064     identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes);
7065 
7066     // Register a rewrite of the argument.
7067     if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
7068                                            std::move(FnRepairCB),
7069                                            std::move(ACSRepairCB)))
7070       return ChangeStatus::CHANGED;
7071     return ChangeStatus::UNCHANGED;
7072   }
7073 
7074   /// See AbstractAttribute::trackStatistics()
7075   void trackStatistics() const override {
7076     STATS_DECLTRACK_ARG_ATTR(privatizable_ptr);
7077   }
7078 };
7079 
7080 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl {
7081   AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A)
7082       : AAPrivatizablePtrImpl(IRP, A) {}
7083 
7084   /// See AbstractAttribute::initialize(...).
7085   virtual void initialize(Attributor &A) override {
7086     // TODO: We can privatize more than arguments.
7087     indicatePessimisticFixpoint();
7088   }
7089 
7090   ChangeStatus updateImpl(Attributor &A) override {
7091     llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::"
7092                      "updateImpl will not be called");
7093   }
7094 
7095   /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...)
7096   Optional<Type *> identifyPrivatizableType(Attributor &A) override {
7097     Value *Obj = getUnderlyingObject(&getAssociatedValue());
7098     if (!Obj) {
7099       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n");
7100       return nullptr;
7101     }
7102 
7103     if (auto *AI = dyn_cast<AllocaInst>(Obj))
7104       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
7105         if (CI->isOne())
7106           return AI->getAllocatedType();
7107     if (auto *Arg = dyn_cast<Argument>(Obj)) {
7108       auto &PrivArgAA = A.getAAFor<AAPrivatizablePtr>(
7109           *this, IRPosition::argument(*Arg), DepClassTy::REQUIRED);
7110       if (PrivArgAA.isAssumedPrivatizablePtr())
7111         return PrivArgAA.getPrivatizableType();
7112     }
7113 
7114     LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid "
7115                          "alloca nor privatizable argument: "
7116                       << *Obj << "!\n");
7117     return nullptr;
7118   }
7119 
7120   /// See AbstractAttribute::trackStatistics()
7121   void trackStatistics() const override {
7122     STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr);
7123   }
7124 };
7125 
7126 struct AAPrivatizablePtrCallSiteArgument final
7127     : public AAPrivatizablePtrFloating {
7128   AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A)
7129       : AAPrivatizablePtrFloating(IRP, A) {}
7130 
7131   /// See AbstractAttribute::initialize(...).
7132   void initialize(Attributor &A) override {
7133     if (getIRPosition().hasAttr(Attribute::ByVal))
7134       indicateOptimisticFixpoint();
7135   }
7136 
7137   /// See AbstractAttribute::updateImpl(...).
7138   ChangeStatus updateImpl(Attributor &A) override {
7139     PrivatizableType = identifyPrivatizableType(A);
7140     if (!PrivatizableType.hasValue())
7141       return ChangeStatus::UNCHANGED;
7142     if (!PrivatizableType.getValue())
7143       return indicatePessimisticFixpoint();
7144 
7145     const IRPosition &IRP = getIRPosition();
7146     auto &NoCaptureAA =
7147         A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::REQUIRED);
7148     if (!NoCaptureAA.isAssumedNoCapture()) {
7149       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n");
7150       return indicatePessimisticFixpoint();
7151     }
7152 
7153     auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP, DepClassTy::REQUIRED);
7154     if (!NoAliasAA.isAssumedNoAlias()) {
7155       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n");
7156       return indicatePessimisticFixpoint();
7157     }
7158 
7159     bool IsKnown;
7160     if (!AA::isAssumedReadOnly(A, IRP, *this, IsKnown)) {
7161       LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n");
7162       return indicatePessimisticFixpoint();
7163     }
7164 
7165     return ChangeStatus::UNCHANGED;
7166   }
7167 
7168   /// See AbstractAttribute::trackStatistics()
7169   void trackStatistics() const override {
7170     STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr);
7171   }
7172 };
7173 
7174 struct AAPrivatizablePtrCallSiteReturned final
7175     : public AAPrivatizablePtrFloating {
7176   AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A)
7177       : AAPrivatizablePtrFloating(IRP, A) {}
7178 
7179   /// See AbstractAttribute::initialize(...).
7180   void initialize(Attributor &A) override {
7181     // TODO: We can privatize more than arguments.
7182     indicatePessimisticFixpoint();
7183   }
7184 
7185   /// See AbstractAttribute::trackStatistics()
7186   void trackStatistics() const override {
7187     STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr);
7188   }
7189 };
7190 
7191 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating {
7192   AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A)
7193       : AAPrivatizablePtrFloating(IRP, A) {}
7194 
7195   /// See AbstractAttribute::initialize(...).
7196   void initialize(Attributor &A) override {
7197     // TODO: We can privatize more than arguments.
7198     indicatePessimisticFixpoint();
7199   }
7200 
7201   /// See AbstractAttribute::trackStatistics()
7202   void trackStatistics() const override {
7203     STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr);
7204   }
7205 };
7206 } // namespace
7207 
7208 /// -------------------- Memory Behavior Attributes ----------------------------
7209 /// Includes read-none, read-only, and write-only.
7210 /// ----------------------------------------------------------------------------
7211 namespace {
7212 struct AAMemoryBehaviorImpl : public AAMemoryBehavior {
7213   AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A)
7214       : AAMemoryBehavior(IRP, A) {}
7215 
7216   /// See AbstractAttribute::initialize(...).
7217   void initialize(Attributor &A) override {
7218     intersectAssumedBits(BEST_STATE);
7219     getKnownStateFromValue(getIRPosition(), getState());
7220     AAMemoryBehavior::initialize(A);
7221   }
7222 
7223   /// Return the memory behavior information encoded in the IR for \p IRP.
7224   static void getKnownStateFromValue(const IRPosition &IRP,
7225                                      BitIntegerState &State,
7226                                      bool IgnoreSubsumingPositions = false) {
7227     SmallVector<Attribute, 2> Attrs;
7228     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
7229     for (const Attribute &Attr : Attrs) {
7230       switch (Attr.getKindAsEnum()) {
7231       case Attribute::ReadNone:
7232         State.addKnownBits(NO_ACCESSES);
7233         break;
7234       case Attribute::ReadOnly:
7235         State.addKnownBits(NO_WRITES);
7236         break;
7237       case Attribute::WriteOnly:
7238         State.addKnownBits(NO_READS);
7239         break;
7240       default:
7241         llvm_unreachable("Unexpected attribute!");
7242       }
7243     }
7244 
7245     if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) {
7246       if (!I->mayReadFromMemory())
7247         State.addKnownBits(NO_READS);
7248       if (!I->mayWriteToMemory())
7249         State.addKnownBits(NO_WRITES);
7250     }
7251   }
7252 
7253   /// See AbstractAttribute::getDeducedAttributes(...).
7254   void getDeducedAttributes(LLVMContext &Ctx,
7255                             SmallVectorImpl<Attribute> &Attrs) const override {
7256     assert(Attrs.size() == 0);
7257     if (isAssumedReadNone())
7258       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7259     else if (isAssumedReadOnly())
7260       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
7261     else if (isAssumedWriteOnly())
7262       Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
7263     assert(Attrs.size() <= 1);
7264   }
7265 
7266   /// See AbstractAttribute::manifest(...).
7267   ChangeStatus manifest(Attributor &A) override {
7268     if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true))
7269       return ChangeStatus::UNCHANGED;
7270 
7271     const IRPosition &IRP = getIRPosition();
7272 
7273     // Check if we would improve the existing attributes first.
7274     SmallVector<Attribute, 4> DeducedAttrs;
7275     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
7276     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
7277           return IRP.hasAttr(Attr.getKindAsEnum(),
7278                              /* IgnoreSubsumingPositions */ true);
7279         }))
7280       return ChangeStatus::UNCHANGED;
7281 
7282     // Clear existing attributes.
7283     IRP.removeAttrs(AttrKinds);
7284 
7285     // Use the generic manifest method.
7286     return IRAttribute::manifest(A);
7287   }
7288 
7289   /// See AbstractState::getAsStr().
7290   const std::string getAsStr() const override {
7291     if (isAssumedReadNone())
7292       return "readnone";
7293     if (isAssumedReadOnly())
7294       return "readonly";
7295     if (isAssumedWriteOnly())
7296       return "writeonly";
7297     return "may-read/write";
7298   }
7299 
7300   /// The set of IR attributes AAMemoryBehavior deals with.
7301   static const Attribute::AttrKind AttrKinds[3];
7302 };
7303 
7304 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = {
7305     Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
7306 
7307 /// Memory behavior attribute for a floating value.
7308 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
7309   AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A)
7310       : AAMemoryBehaviorImpl(IRP, A) {}
7311 
7312   /// See AbstractAttribute::updateImpl(...).
7313   ChangeStatus updateImpl(Attributor &A) override;
7314 
7315   /// See AbstractAttribute::trackStatistics()
7316   void trackStatistics() const override {
7317     if (isAssumedReadNone())
7318       STATS_DECLTRACK_FLOATING_ATTR(readnone)
7319     else if (isAssumedReadOnly())
7320       STATS_DECLTRACK_FLOATING_ATTR(readonly)
7321     else if (isAssumedWriteOnly())
7322       STATS_DECLTRACK_FLOATING_ATTR(writeonly)
7323   }
7324 
7325 private:
7326   /// Return true if users of \p UserI might access the underlying
7327   /// variable/location described by \p U and should therefore be analyzed.
7328   bool followUsersOfUseIn(Attributor &A, const Use &U,
7329                           const Instruction *UserI);
7330 
7331   /// Update the state according to the effect of use \p U in \p UserI.
7332   void analyzeUseIn(Attributor &A, const Use &U, const Instruction *UserI);
7333 };
7334 
7335 /// Memory behavior attribute for function argument.
7336 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
7337   AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A)
7338       : AAMemoryBehaviorFloating(IRP, A) {}
7339 
7340   /// See AbstractAttribute::initialize(...).
7341   void initialize(Attributor &A) override {
7342     intersectAssumedBits(BEST_STATE);
7343     const IRPosition &IRP = getIRPosition();
7344     // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we
7345     // can query it when we use has/getAttr. That would allow us to reuse the
7346     // initialize of the base class here.
7347     bool HasByVal =
7348         IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true);
7349     getKnownStateFromValue(IRP, getState(),
7350                            /* IgnoreSubsumingPositions */ HasByVal);
7351 
7352     // Initialize the use vector with all direct uses of the associated value.
7353     Argument *Arg = getAssociatedArgument();
7354     if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent())))
7355       indicatePessimisticFixpoint();
7356   }
7357 
7358   ChangeStatus manifest(Attributor &A) override {
7359     // TODO: Pointer arguments are not supported on vectors of pointers yet.
7360     if (!getAssociatedValue().getType()->isPointerTy())
7361       return ChangeStatus::UNCHANGED;
7362 
7363     // TODO: From readattrs.ll: "inalloca parameters are always
7364     //                           considered written"
7365     if (hasAttr({Attribute::InAlloca, Attribute::Preallocated})) {
7366       removeKnownBits(NO_WRITES);
7367       removeAssumedBits(NO_WRITES);
7368     }
7369     return AAMemoryBehaviorFloating::manifest(A);
7370   }
7371 
7372   /// See AbstractAttribute::trackStatistics()
7373   void trackStatistics() const override {
7374     if (isAssumedReadNone())
7375       STATS_DECLTRACK_ARG_ATTR(readnone)
7376     else if (isAssumedReadOnly())
7377       STATS_DECLTRACK_ARG_ATTR(readonly)
7378     else if (isAssumedWriteOnly())
7379       STATS_DECLTRACK_ARG_ATTR(writeonly)
7380   }
7381 };
7382 
7383 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
7384   AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A)
7385       : AAMemoryBehaviorArgument(IRP, A) {}
7386 
7387   /// See AbstractAttribute::initialize(...).
7388   void initialize(Attributor &A) override {
7389     // If we don't have an associated attribute this is either a variadic call
7390     // or an indirect call, either way, nothing to do here.
7391     Argument *Arg = getAssociatedArgument();
7392     if (!Arg) {
7393       indicatePessimisticFixpoint();
7394       return;
7395     }
7396     if (Arg->hasByValAttr()) {
7397       addKnownBits(NO_WRITES);
7398       removeKnownBits(NO_READS);
7399       removeAssumedBits(NO_READS);
7400     }
7401     AAMemoryBehaviorArgument::initialize(A);
7402     if (getAssociatedFunction()->isDeclaration())
7403       indicatePessimisticFixpoint();
7404   }
7405 
7406   /// See AbstractAttribute::updateImpl(...).
7407   ChangeStatus updateImpl(Attributor &A) override {
7408     // TODO: Once we have call site specific value information we can provide
7409     //       call site specific liveness liveness information and then it makes
7410     //       sense to specialize attributes for call sites arguments instead of
7411     //       redirecting requests to the callee argument.
7412     Argument *Arg = getAssociatedArgument();
7413     const IRPosition &ArgPos = IRPosition::argument(*Arg);
7414     auto &ArgAA =
7415         A.getAAFor<AAMemoryBehavior>(*this, ArgPos, DepClassTy::REQUIRED);
7416     return clampStateAndIndicateChange(getState(), ArgAA.getState());
7417   }
7418 
7419   /// See AbstractAttribute::trackStatistics()
7420   void trackStatistics() const override {
7421     if (isAssumedReadNone())
7422       STATS_DECLTRACK_CSARG_ATTR(readnone)
7423     else if (isAssumedReadOnly())
7424       STATS_DECLTRACK_CSARG_ATTR(readonly)
7425     else if (isAssumedWriteOnly())
7426       STATS_DECLTRACK_CSARG_ATTR(writeonly)
7427   }
7428 };
7429 
7430 /// Memory behavior attribute for a call site return position.
7431 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
7432   AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A)
7433       : AAMemoryBehaviorFloating(IRP, A) {}
7434 
7435   /// See AbstractAttribute::initialize(...).
7436   void initialize(Attributor &A) override {
7437     AAMemoryBehaviorImpl::initialize(A);
7438     Function *F = getAssociatedFunction();
7439     if (!F || F->isDeclaration())
7440       indicatePessimisticFixpoint();
7441   }
7442 
7443   /// See AbstractAttribute::manifest(...).
7444   ChangeStatus manifest(Attributor &A) override {
7445     // We do not annotate returned values.
7446     return ChangeStatus::UNCHANGED;
7447   }
7448 
7449   /// See AbstractAttribute::trackStatistics()
7450   void trackStatistics() const override {}
7451 };
7452 
7453 /// An AA to represent the memory behavior function attributes.
7454 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl {
7455   AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A)
7456       : AAMemoryBehaviorImpl(IRP, A) {}
7457 
7458   /// See AbstractAttribute::updateImpl(Attributor &A).
7459   virtual ChangeStatus updateImpl(Attributor &A) override;
7460 
7461   /// See AbstractAttribute::manifest(...).
7462   ChangeStatus manifest(Attributor &A) override {
7463     Function &F = cast<Function>(getAnchorValue());
7464     if (isAssumedReadNone()) {
7465       F.removeFnAttr(Attribute::ArgMemOnly);
7466       F.removeFnAttr(Attribute::InaccessibleMemOnly);
7467       F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
7468     }
7469     return AAMemoryBehaviorImpl::manifest(A);
7470   }
7471 
7472   /// See AbstractAttribute::trackStatistics()
7473   void trackStatistics() const override {
7474     if (isAssumedReadNone())
7475       STATS_DECLTRACK_FN_ATTR(readnone)
7476     else if (isAssumedReadOnly())
7477       STATS_DECLTRACK_FN_ATTR(readonly)
7478     else if (isAssumedWriteOnly())
7479       STATS_DECLTRACK_FN_ATTR(writeonly)
7480   }
7481 };
7482 
7483 /// AAMemoryBehavior attribute for call sites.
7484 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
7485   AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A)
7486       : AAMemoryBehaviorImpl(IRP, A) {}
7487 
7488   /// See AbstractAttribute::initialize(...).
7489   void initialize(Attributor &A) override {
7490     AAMemoryBehaviorImpl::initialize(A);
7491     Function *F = getAssociatedFunction();
7492     if (!F || F->isDeclaration())
7493       indicatePessimisticFixpoint();
7494   }
7495 
7496   /// See AbstractAttribute::updateImpl(...).
7497   ChangeStatus updateImpl(Attributor &A) override {
7498     // TODO: Once we have call site specific value information we can provide
7499     //       call site specific liveness liveness information and then it makes
7500     //       sense to specialize attributes for call sites arguments instead of
7501     //       redirecting requests to the callee argument.
7502     Function *F = getAssociatedFunction();
7503     const IRPosition &FnPos = IRPosition::function(*F);
7504     auto &FnAA =
7505         A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::REQUIRED);
7506     return clampStateAndIndicateChange(getState(), FnAA.getState());
7507   }
7508 
7509   /// See AbstractAttribute::trackStatistics()
7510   void trackStatistics() const override {
7511     if (isAssumedReadNone())
7512       STATS_DECLTRACK_CS_ATTR(readnone)
7513     else if (isAssumedReadOnly())
7514       STATS_DECLTRACK_CS_ATTR(readonly)
7515     else if (isAssumedWriteOnly())
7516       STATS_DECLTRACK_CS_ATTR(writeonly)
7517   }
7518 };
7519 
7520 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) {
7521 
7522   // The current assumed state used to determine a change.
7523   auto AssumedState = getAssumed();
7524 
7525   auto CheckRWInst = [&](Instruction &I) {
7526     // If the instruction has an own memory behavior state, use it to restrict
7527     // the local state. No further analysis is required as the other memory
7528     // state is as optimistic as it gets.
7529     if (const auto *CB = dyn_cast<CallBase>(&I)) {
7530       const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>(
7531           *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED);
7532       intersectAssumedBits(MemBehaviorAA.getAssumed());
7533       return !isAtFixpoint();
7534     }
7535 
7536     // Remove access kind modifiers if necessary.
7537     if (I.mayReadFromMemory())
7538       removeAssumedBits(NO_READS);
7539     if (I.mayWriteToMemory())
7540       removeAssumedBits(NO_WRITES);
7541     return !isAtFixpoint();
7542   };
7543 
7544   bool UsedAssumedInformation = false;
7545   if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
7546                                           UsedAssumedInformation))
7547     return indicatePessimisticFixpoint();
7548 
7549   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
7550                                         : ChangeStatus::UNCHANGED;
7551 }
7552 
7553 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) {
7554 
7555   const IRPosition &IRP = getIRPosition();
7556   const IRPosition &FnPos = IRPosition::function_scope(IRP);
7557   AAMemoryBehavior::StateType &S = getState();
7558 
7559   // First, check the function scope. We take the known information and we avoid
7560   // work if the assumed information implies the current assumed information for
7561   // this attribute. This is a valid for all but byval arguments.
7562   Argument *Arg = IRP.getAssociatedArgument();
7563   AAMemoryBehavior::base_t FnMemAssumedState =
7564       AAMemoryBehavior::StateType::getWorstState();
7565   if (!Arg || !Arg->hasByValAttr()) {
7566     const auto &FnMemAA =
7567         A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::OPTIONAL);
7568     FnMemAssumedState = FnMemAA.getAssumed();
7569     S.addKnownBits(FnMemAA.getKnown());
7570     if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
7571       return ChangeStatus::UNCHANGED;
7572   }
7573 
7574   // The current assumed state used to determine a change.
7575   auto AssumedState = S.getAssumed();
7576 
7577   // Make sure the value is not captured (except through "return"), if
7578   // it is, any information derived would be irrelevant anyway as we cannot
7579   // check the potential aliases introduced by the capture. However, no need
7580   // to fall back to anythign less optimistic than the function state.
7581   const auto &ArgNoCaptureAA =
7582       A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::OPTIONAL);
7583   if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
7584     S.intersectAssumedBits(FnMemAssumedState);
7585     return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
7586                                           : ChangeStatus::UNCHANGED;
7587   }
7588 
7589   // Visit and expand uses until all are analyzed or a fixpoint is reached.
7590   auto UsePred = [&](const Use &U, bool &Follow) -> bool {
7591     Instruction *UserI = cast<Instruction>(U.getUser());
7592     LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << *U << " in " << *UserI
7593                       << " \n");
7594 
7595     // Droppable users, e.g., llvm::assume does not actually perform any action.
7596     if (UserI->isDroppable())
7597       return true;
7598 
7599     // Check if the users of UserI should also be visited.
7600     Follow = followUsersOfUseIn(A, U, UserI);
7601 
7602     // If UserI might touch memory we analyze the use in detail.
7603     if (UserI->mayReadOrWriteMemory())
7604       analyzeUseIn(A, U, UserI);
7605 
7606     return !isAtFixpoint();
7607   };
7608 
7609   if (!A.checkForAllUses(UsePred, *this, getAssociatedValue()))
7610     return indicatePessimisticFixpoint();
7611 
7612   return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED
7613                                         : ChangeStatus::UNCHANGED;
7614 }
7615 
7616 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use &U,
7617                                                   const Instruction *UserI) {
7618   // The loaded value is unrelated to the pointer argument, no need to
7619   // follow the users of the load.
7620   if (isa<LoadInst>(UserI))
7621     return false;
7622 
7623   // By default we follow all uses assuming UserI might leak information on U,
7624   // we have special handling for call sites operands though.
7625   const auto *CB = dyn_cast<CallBase>(UserI);
7626   if (!CB || !CB->isArgOperand(&U))
7627     return true;
7628 
7629   // If the use is a call argument known not to be captured, the users of
7630   // the call do not need to be visited because they have to be unrelated to
7631   // the input. Note that this check is not trivial even though we disallow
7632   // general capturing of the underlying argument. The reason is that the
7633   // call might the argument "through return", which we allow and for which we
7634   // need to check call users.
7635   if (U.get()->getType()->isPointerTy()) {
7636     unsigned ArgNo = CB->getArgOperandNo(&U);
7637     const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>(
7638         *this, IRPosition::callsite_argument(*CB, ArgNo), DepClassTy::OPTIONAL);
7639     return !ArgNoCaptureAA.isAssumedNoCapture();
7640   }
7641 
7642   return true;
7643 }
7644 
7645 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use &U,
7646                                             const Instruction *UserI) {
7647   assert(UserI->mayReadOrWriteMemory());
7648 
7649   switch (UserI->getOpcode()) {
7650   default:
7651     // TODO: Handle all atomics and other side-effect operations we know of.
7652     break;
7653   case Instruction::Load:
7654     // Loads cause the NO_READS property to disappear.
7655     removeAssumedBits(NO_READS);
7656     return;
7657 
7658   case Instruction::Store:
7659     // Stores cause the NO_WRITES property to disappear if the use is the
7660     // pointer operand. Note that while capturing was taken care of somewhere
7661     // else we need to deal with stores of the value that is not looked through.
7662     if (cast<StoreInst>(UserI)->getPointerOperand() == U.get())
7663       removeAssumedBits(NO_WRITES);
7664     else
7665       indicatePessimisticFixpoint();
7666     return;
7667 
7668   case Instruction::Call:
7669   case Instruction::CallBr:
7670   case Instruction::Invoke: {
7671     // For call sites we look at the argument memory behavior attribute (this
7672     // could be recursive!) in order to restrict our own state.
7673     const auto *CB = cast<CallBase>(UserI);
7674 
7675     // Give up on operand bundles.
7676     if (CB->isBundleOperand(&U)) {
7677       indicatePessimisticFixpoint();
7678       return;
7679     }
7680 
7681     // Calling a function does read the function pointer, maybe write it if the
7682     // function is self-modifying.
7683     if (CB->isCallee(&U)) {
7684       removeAssumedBits(NO_READS);
7685       break;
7686     }
7687 
7688     // Adjust the possible access behavior based on the information on the
7689     // argument.
7690     IRPosition Pos;
7691     if (U.get()->getType()->isPointerTy())
7692       Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
7693     else
7694       Pos = IRPosition::callsite_function(*CB);
7695     const auto &MemBehaviorAA =
7696         A.getAAFor<AAMemoryBehavior>(*this, Pos, DepClassTy::OPTIONAL);
7697     // "assumed" has at most the same bits as the MemBehaviorAA assumed
7698     // and at least "known".
7699     intersectAssumedBits(MemBehaviorAA.getAssumed());
7700     return;
7701   }
7702   };
7703 
7704   // Generally, look at the "may-properties" and adjust the assumed state if we
7705   // did not trigger special handling before.
7706   if (UserI->mayReadFromMemory())
7707     removeAssumedBits(NO_READS);
7708   if (UserI->mayWriteToMemory())
7709     removeAssumedBits(NO_WRITES);
7710 }
7711 } // namespace
7712 
7713 /// -------------------- Memory Locations Attributes ---------------------------
7714 /// Includes read-none, argmemonly, inaccessiblememonly,
7715 /// inaccessiblememorargmemonly
7716 /// ----------------------------------------------------------------------------
7717 
7718 std::string AAMemoryLocation::getMemoryLocationsAsStr(
7719     AAMemoryLocation::MemoryLocationsKind MLK) {
7720   if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS))
7721     return "all memory";
7722   if (MLK == AAMemoryLocation::NO_LOCATIONS)
7723     return "no memory";
7724   std::string S = "memory:";
7725   if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM))
7726     S += "stack,";
7727   if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM))
7728     S += "constant,";
7729   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM))
7730     S += "internal global,";
7731   if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM))
7732     S += "external global,";
7733   if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM))
7734     S += "argument,";
7735   if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM))
7736     S += "inaccessible,";
7737   if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM))
7738     S += "malloced,";
7739   if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM))
7740     S += "unknown,";
7741   S.pop_back();
7742   return S;
7743 }
7744 
7745 namespace {
7746 struct AAMemoryLocationImpl : public AAMemoryLocation {
7747 
7748   AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A)
7749       : AAMemoryLocation(IRP, A), Allocator(A.Allocator) {
7750     for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
7751       AccessKind2Accesses[u] = nullptr;
7752   }
7753 
7754   ~AAMemoryLocationImpl() {
7755     // The AccessSets are allocated via a BumpPtrAllocator, we call
7756     // the destructor manually.
7757     for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u)
7758       if (AccessKind2Accesses[u])
7759         AccessKind2Accesses[u]->~AccessSet();
7760   }
7761 
7762   /// See AbstractAttribute::initialize(...).
7763   void initialize(Attributor &A) override {
7764     intersectAssumedBits(BEST_STATE);
7765     getKnownStateFromValue(A, getIRPosition(), getState());
7766     AAMemoryLocation::initialize(A);
7767   }
7768 
7769   /// Return the memory behavior information encoded in the IR for \p IRP.
7770   static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP,
7771                                      BitIntegerState &State,
7772                                      bool IgnoreSubsumingPositions = false) {
7773     // For internal functions we ignore `argmemonly` and
7774     // `inaccessiblememorargmemonly` as we might break it via interprocedural
7775     // constant propagation. It is unclear if this is the best way but it is
7776     // unlikely this will cause real performance problems. If we are deriving
7777     // attributes for the anchor function we even remove the attribute in
7778     // addition to ignoring it.
7779     bool UseArgMemOnly = true;
7780     Function *AnchorFn = IRP.getAnchorScope();
7781     if (AnchorFn && A.isRunOn(*AnchorFn))
7782       UseArgMemOnly = !AnchorFn->hasLocalLinkage();
7783 
7784     SmallVector<Attribute, 2> Attrs;
7785     IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
7786     for (const Attribute &Attr : Attrs) {
7787       switch (Attr.getKindAsEnum()) {
7788       case Attribute::ReadNone:
7789         State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM);
7790         break;
7791       case Attribute::InaccessibleMemOnly:
7792         State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true));
7793         break;
7794       case Attribute::ArgMemOnly:
7795         if (UseArgMemOnly)
7796           State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true));
7797         else
7798           IRP.removeAttrs({Attribute::ArgMemOnly});
7799         break;
7800       case Attribute::InaccessibleMemOrArgMemOnly:
7801         if (UseArgMemOnly)
7802           State.addKnownBits(inverseLocation(
7803               NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true));
7804         else
7805           IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly});
7806         break;
7807       default:
7808         llvm_unreachable("Unexpected attribute!");
7809       }
7810     }
7811   }
7812 
7813   /// See AbstractAttribute::getDeducedAttributes(...).
7814   void getDeducedAttributes(LLVMContext &Ctx,
7815                             SmallVectorImpl<Attribute> &Attrs) const override {
7816     assert(Attrs.size() == 0);
7817     if (isAssumedReadNone()) {
7818       Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7819     } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) {
7820       if (isAssumedInaccessibleMemOnly())
7821         Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly));
7822       else if (isAssumedArgMemOnly())
7823         Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly));
7824       else if (isAssumedInaccessibleOrArgMemOnly())
7825         Attrs.push_back(
7826             Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly));
7827     }
7828     assert(Attrs.size() <= 1);
7829   }
7830 
7831   /// See AbstractAttribute::manifest(...).
7832   ChangeStatus manifest(Attributor &A) override {
7833     const IRPosition &IRP = getIRPosition();
7834 
7835     // Check if we would improve the existing attributes first.
7836     SmallVector<Attribute, 4> DeducedAttrs;
7837     getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs);
7838     if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) {
7839           return IRP.hasAttr(Attr.getKindAsEnum(),
7840                              /* IgnoreSubsumingPositions */ true);
7841         }))
7842       return ChangeStatus::UNCHANGED;
7843 
7844     // Clear existing attributes.
7845     IRP.removeAttrs(AttrKinds);
7846     if (isAssumedReadNone())
7847       IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds);
7848 
7849     // Use the generic manifest method.
7850     return IRAttribute::manifest(A);
7851   }
7852 
7853   /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...).
7854   bool checkForAllAccessesToMemoryKind(
7855       function_ref<bool(const Instruction *, const Value *, AccessKind,
7856                         MemoryLocationsKind)>
7857           Pred,
7858       MemoryLocationsKind RequestedMLK) const override {
7859     if (!isValidState())
7860       return false;
7861 
7862     MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
7863     if (AssumedMLK == NO_LOCATIONS)
7864       return true;
7865 
7866     unsigned Idx = 0;
7867     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
7868          CurMLK *= 2, ++Idx) {
7869       if (CurMLK & RequestedMLK)
7870         continue;
7871 
7872       if (const AccessSet *Accesses = AccessKind2Accesses[Idx])
7873         for (const AccessInfo &AI : *Accesses)
7874           if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
7875             return false;
7876     }
7877 
7878     return true;
7879   }
7880 
7881   ChangeStatus indicatePessimisticFixpoint() override {
7882     // If we give up and indicate a pessimistic fixpoint this instruction will
7883     // become an access for all potential access kinds:
7884     // TODO: Add pointers for argmemonly and globals to improve the results of
7885     //       checkForAllAccessesToMemoryKind.
7886     bool Changed = false;
7887     MemoryLocationsKind KnownMLK = getKnown();
7888     Instruction *I = dyn_cast<Instruction>(&getAssociatedValue());
7889     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
7890       if (!(CurMLK & KnownMLK))
7891         updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed,
7892                                   getAccessKindFromInst(I));
7893     return AAMemoryLocation::indicatePessimisticFixpoint();
7894   }
7895 
7896 protected:
7897   /// Helper struct to tie together an instruction that has a read or write
7898   /// effect with the pointer it accesses (if any).
7899   struct AccessInfo {
7900 
7901     /// The instruction that caused the access.
7902     const Instruction *I;
7903 
7904     /// The base pointer that is accessed, or null if unknown.
7905     const Value *Ptr;
7906 
7907     /// The kind of access (read/write/read+write).
7908     AccessKind Kind;
7909 
7910     bool operator==(const AccessInfo &RHS) const {
7911       return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind;
7912     }
7913     bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const {
7914       if (LHS.I != RHS.I)
7915         return LHS.I < RHS.I;
7916       if (LHS.Ptr != RHS.Ptr)
7917         return LHS.Ptr < RHS.Ptr;
7918       if (LHS.Kind != RHS.Kind)
7919         return LHS.Kind < RHS.Kind;
7920       return false;
7921     }
7922   };
7923 
7924   /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the
7925   /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind.
7926   using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
7927   AccessSet *AccessKind2Accesses[llvm::CTLog2<VALID_STATE>()];
7928 
7929   /// Categorize the pointer arguments of CB that might access memory in
7930   /// AccessedLoc and update the state and access map accordingly.
7931   void
7932   categorizeArgumentPointerLocations(Attributor &A, CallBase &CB,
7933                                      AAMemoryLocation::StateType &AccessedLocs,
7934                                      bool &Changed);
7935 
7936   /// Return the kind(s) of location that may be accessed by \p V.
7937   AAMemoryLocation::MemoryLocationsKind
7938   categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed);
7939 
7940   /// Return the access kind as determined by \p I.
7941   AccessKind getAccessKindFromInst(const Instruction *I) {
7942     AccessKind AK = READ_WRITE;
7943     if (I) {
7944       AK = I->mayReadFromMemory() ? READ : NONE;
7945       AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE));
7946     }
7947     return AK;
7948   }
7949 
7950   /// Update the state \p State and the AccessKind2Accesses given that \p I is
7951   /// an access of kind \p AK to a \p MLK memory location with the access
7952   /// pointer \p Ptr.
7953   void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
7954                                  MemoryLocationsKind MLK, const Instruction *I,
7955                                  const Value *Ptr, bool &Changed,
7956                                  AccessKind AK = READ_WRITE) {
7957 
7958     assert(isPowerOf2_32(MLK) && "Expected a single location set!");
7959     auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)];
7960     if (!Accesses)
7961       Accesses = new (Allocator) AccessSet();
7962     Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second;
7963     State.removeAssumedBits(MLK);
7964   }
7965 
7966   /// Determine the underlying locations kinds for \p Ptr, e.g., globals or
7967   /// arguments, and update the state and access map accordingly.
7968   void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr,
7969                           AAMemoryLocation::StateType &State, bool &Changed);
7970 
7971   /// Used to allocate access sets.
7972   BumpPtrAllocator &Allocator;
7973 
7974   /// The set of IR attributes AAMemoryLocation deals with.
7975   static const Attribute::AttrKind AttrKinds[4];
7976 };
7977 
7978 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = {
7979     Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly,
7980     Attribute::InaccessibleMemOrArgMemOnly};
7981 
7982 void AAMemoryLocationImpl::categorizePtrValue(
7983     Attributor &A, const Instruction &I, const Value &Ptr,
7984     AAMemoryLocation::StateType &State, bool &Changed) {
7985   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for "
7986                     << Ptr << " ["
7987                     << getMemoryLocationsAsStr(State.getAssumed()) << "]\n");
7988 
7989   SmallVector<Value *, 8> Objects;
7990   bool UsedAssumedInformation = false;
7991   if (!AA::getAssumedUnderlyingObjects(A, Ptr, Objects, *this, &I,
7992                                        UsedAssumedInformation,
7993                                        AA::Intraprocedural)) {
7994     LLVM_DEBUG(
7995         dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n");
7996     updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed,
7997                               getAccessKindFromInst(&I));
7998     return;
7999   }
8000 
8001   for (Value *Obj : Objects) {
8002     // TODO: recognize the TBAA used for constant accesses.
8003     MemoryLocationsKind MLK = NO_LOCATIONS;
8004     if (isa<UndefValue>(Obj))
8005       continue;
8006     if (isa<Argument>(Obj)) {
8007       // TODO: For now we do not treat byval arguments as local copies performed
8008       // on the call edge, though, we should. To make that happen we need to
8009       // teach various passes, e.g., DSE, about the copy effect of a byval. That
8010       // would also allow us to mark functions only accessing byval arguments as
8011       // readnone again, atguably their acceses have no effect outside of the
8012       // function, like accesses to allocas.
8013       MLK = NO_ARGUMENT_MEM;
8014     } else if (auto *GV = dyn_cast<GlobalValue>(Obj)) {
8015       // Reading constant memory is not treated as a read "effect" by the
8016       // function attr pass so we won't neither. Constants defined by TBAA are
8017       // similar. (We know we do not write it because it is constant.)
8018       if (auto *GVar = dyn_cast<GlobalVariable>(GV))
8019         if (GVar->isConstant())
8020           continue;
8021 
8022       if (GV->hasLocalLinkage())
8023         MLK = NO_GLOBAL_INTERNAL_MEM;
8024       else
8025         MLK = NO_GLOBAL_EXTERNAL_MEM;
8026     } else if (isa<ConstantPointerNull>(Obj) &&
8027                !NullPointerIsDefined(getAssociatedFunction(),
8028                                      Ptr.getType()->getPointerAddressSpace())) {
8029       continue;
8030     } else if (isa<AllocaInst>(Obj)) {
8031       MLK = NO_LOCAL_MEM;
8032     } else if (const auto *CB = dyn_cast<CallBase>(Obj)) {
8033       const auto &NoAliasAA = A.getAAFor<AANoAlias>(
8034           *this, IRPosition::callsite_returned(*CB), DepClassTy::OPTIONAL);
8035       if (NoAliasAA.isAssumedNoAlias())
8036         MLK = NO_MALLOCED_MEM;
8037       else
8038         MLK = NO_UNKOWN_MEM;
8039     } else {
8040       MLK = NO_UNKOWN_MEM;
8041     }
8042 
8043     assert(MLK != NO_LOCATIONS && "No location specified!");
8044     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value can be categorized: "
8045                       << *Obj << " -> " << getMemoryLocationsAsStr(MLK)
8046                       << "\n");
8047     updateStateAndAccessesMap(getState(), MLK, &I, Obj, Changed,
8048                               getAccessKindFromInst(&I));
8049   }
8050 
8051   LLVM_DEBUG(
8052       dbgs() << "[AAMemoryLocation] Accessed locations with pointer locations: "
8053              << getMemoryLocationsAsStr(State.getAssumed()) << "\n");
8054 }
8055 
8056 void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
8057     Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs,
8058     bool &Changed) {
8059   for (unsigned ArgNo = 0, E = CB.arg_size(); ArgNo < E; ++ArgNo) {
8060 
8061     // Skip non-pointer arguments.
8062     const Value *ArgOp = CB.getArgOperand(ArgNo);
8063     if (!ArgOp->getType()->isPtrOrPtrVectorTy())
8064       continue;
8065 
8066     // Skip readnone arguments.
8067     const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo);
8068     const auto &ArgOpMemLocationAA =
8069         A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL);
8070 
8071     if (ArgOpMemLocationAA.isAssumedReadNone())
8072       continue;
8073 
8074     // Categorize potentially accessed pointer arguments as if there was an
8075     // access instruction with them as pointer.
8076     categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed);
8077   }
8078 }
8079 
8080 AAMemoryLocation::MemoryLocationsKind
8081 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I,
8082                                                   bool &Changed) {
8083   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for "
8084                     << I << "\n");
8085 
8086   AAMemoryLocation::StateType AccessedLocs;
8087   AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
8088 
8089   if (auto *CB = dyn_cast<CallBase>(&I)) {
8090 
8091     // First check if we assume any memory is access is visible.
8092     const auto &CBMemLocationAA = A.getAAFor<AAMemoryLocation>(
8093         *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
8094     LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I
8095                       << " [" << CBMemLocationAA << "]\n");
8096 
8097     if (CBMemLocationAA.isAssumedReadNone())
8098       return NO_LOCATIONS;
8099 
8100     if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) {
8101       updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr,
8102                                 Changed, getAccessKindFromInst(&I));
8103       return AccessedLocs.getAssumed();
8104     }
8105 
8106     uint32_t CBAssumedNotAccessedLocs =
8107         CBMemLocationAA.getAssumedNotAccessedLocation();
8108 
8109     // Set the argmemonly and global bit as we handle them separately below.
8110     uint32_t CBAssumedNotAccessedLocsNoArgMem =
8111         CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
8112 
8113     for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
8114       if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
8115         continue;
8116       updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed,
8117                                 getAccessKindFromInst(&I));
8118     }
8119 
8120     // Now handle global memory if it might be accessed. This is slightly tricky
8121     // as NO_GLOBAL_MEM has multiple bits set.
8122     bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
8123     if (HasGlobalAccesses) {
8124       auto AccessPred = [&](const Instruction *, const Value *Ptr,
8125                             AccessKind Kind, MemoryLocationsKind MLK) {
8126         updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed,
8127                                   getAccessKindFromInst(&I));
8128         return true;
8129       };
8130       if (!CBMemLocationAA.checkForAllAccessesToMemoryKind(
8131               AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false)))
8132         return AccessedLocs.getWorstState();
8133     }
8134 
8135     LLVM_DEBUG(
8136         dbgs() << "[AAMemoryLocation] Accessed state before argument handling: "
8137                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
8138 
8139     // Now handle argument memory if it might be accessed.
8140     bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
8141     if (HasArgAccesses)
8142       categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed);
8143 
8144     LLVM_DEBUG(
8145         dbgs() << "[AAMemoryLocation] Accessed state after argument handling: "
8146                << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n");
8147 
8148     return AccessedLocs.getAssumed();
8149   }
8150 
8151   if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) {
8152     LLVM_DEBUG(
8153         dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: "
8154                << I << " [" << *Ptr << "]\n");
8155     categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed);
8156     return AccessedLocs.getAssumed();
8157   }
8158 
8159   LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: "
8160                     << I << "\n");
8161   updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed,
8162                             getAccessKindFromInst(&I));
8163   return AccessedLocs.getAssumed();
8164 }
8165 
8166 /// An AA to represent the memory behavior function attributes.
8167 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl {
8168   AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A)
8169       : AAMemoryLocationImpl(IRP, A) {}
8170 
8171   /// See AbstractAttribute::updateImpl(Attributor &A).
8172   virtual ChangeStatus updateImpl(Attributor &A) override {
8173 
8174     const auto &MemBehaviorAA =
8175         A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE);
8176     if (MemBehaviorAA.isAssumedReadNone()) {
8177       if (MemBehaviorAA.isKnownReadNone())
8178         return indicateOptimisticFixpoint();
8179       assert(isAssumedReadNone() &&
8180              "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
8181       A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL);
8182       return ChangeStatus::UNCHANGED;
8183     }
8184 
8185     // The current assumed state used to determine a change.
8186     auto AssumedState = getAssumed();
8187     bool Changed = false;
8188 
8189     auto CheckRWInst = [&](Instruction &I) {
8190       MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed);
8191       LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I
8192                         << ": " << getMemoryLocationsAsStr(MLK) << "\n");
8193       removeAssumedBits(inverseLocation(MLK, false, false));
8194       // Stop once only the valid bit set in the *not assumed location*, thus
8195       // once we don't actually exclude any memory locations in the state.
8196       return getAssumedNotAccessedLocation() != VALID_STATE;
8197     };
8198 
8199     bool UsedAssumedInformation = false;
8200     if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this,
8201                                             UsedAssumedInformation))
8202       return indicatePessimisticFixpoint();
8203 
8204     Changed |= AssumedState != getAssumed();
8205     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8206   }
8207 
8208   /// See AbstractAttribute::trackStatistics()
8209   void trackStatistics() const override {
8210     if (isAssumedReadNone())
8211       STATS_DECLTRACK_FN_ATTR(readnone)
8212     else if (isAssumedArgMemOnly())
8213       STATS_DECLTRACK_FN_ATTR(argmemonly)
8214     else if (isAssumedInaccessibleMemOnly())
8215       STATS_DECLTRACK_FN_ATTR(inaccessiblememonly)
8216     else if (isAssumedInaccessibleOrArgMemOnly())
8217       STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly)
8218   }
8219 };
8220 
8221 /// AAMemoryLocation attribute for call sites.
8222 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
8223   AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A)
8224       : AAMemoryLocationImpl(IRP, A) {}
8225 
8226   /// See AbstractAttribute::initialize(...).
8227   void initialize(Attributor &A) override {
8228     AAMemoryLocationImpl::initialize(A);
8229     Function *F = getAssociatedFunction();
8230     if (!F || F->isDeclaration())
8231       indicatePessimisticFixpoint();
8232   }
8233 
8234   /// See AbstractAttribute::updateImpl(...).
8235   ChangeStatus updateImpl(Attributor &A) override {
8236     // TODO: Once we have call site specific value information we can provide
8237     //       call site specific liveness liveness information and then it makes
8238     //       sense to specialize attributes for call sites arguments instead of
8239     //       redirecting requests to the callee argument.
8240     Function *F = getAssociatedFunction();
8241     const IRPosition &FnPos = IRPosition::function(*F);
8242     auto &FnAA =
8243         A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED);
8244     bool Changed = false;
8245     auto AccessPred = [&](const Instruction *I, const Value *Ptr,
8246                           AccessKind Kind, MemoryLocationsKind MLK) {
8247       updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed,
8248                                 getAccessKindFromInst(I));
8249       return true;
8250     };
8251     if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
8252       return indicatePessimisticFixpoint();
8253     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8254   }
8255 
8256   /// See AbstractAttribute::trackStatistics()
8257   void trackStatistics() const override {
8258     if (isAssumedReadNone())
8259       STATS_DECLTRACK_CS_ATTR(readnone)
8260   }
8261 };
8262 } // namespace
8263 
8264 /// ------------------ Value Constant Range Attribute -------------------------
8265 
8266 namespace {
8267 struct AAValueConstantRangeImpl : AAValueConstantRange {
8268   using StateType = IntegerRangeState;
8269   AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A)
8270       : AAValueConstantRange(IRP, A) {}
8271 
8272   /// See AbstractAttribute::initialize(..).
8273   void initialize(Attributor &A) override {
8274     if (A.hasSimplificationCallback(getIRPosition())) {
8275       indicatePessimisticFixpoint();
8276       return;
8277     }
8278 
8279     // Intersect a range given by SCEV.
8280     intersectKnown(getConstantRangeFromSCEV(A, getCtxI()));
8281 
8282     // Intersect a range given by LVI.
8283     intersectKnown(getConstantRangeFromLVI(A, getCtxI()));
8284   }
8285 
8286   /// See AbstractAttribute::getAsStr().
8287   const std::string getAsStr() const override {
8288     std::string Str;
8289     llvm::raw_string_ostream OS(Str);
8290     OS << "range(" << getBitWidth() << ")<";
8291     getKnown().print(OS);
8292     OS << " / ";
8293     getAssumed().print(OS);
8294     OS << ">";
8295     return OS.str();
8296   }
8297 
8298   /// Helper function to get a SCEV expr for the associated value at program
8299   /// point \p I.
8300   const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const {
8301     if (!getAnchorScope())
8302       return nullptr;
8303 
8304     ScalarEvolution *SE =
8305         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8306             *getAnchorScope());
8307 
8308     LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
8309         *getAnchorScope());
8310 
8311     if (!SE || !LI)
8312       return nullptr;
8313 
8314     const SCEV *S = SE->getSCEV(&getAssociatedValue());
8315     if (!I)
8316       return S;
8317 
8318     return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent()));
8319   }
8320 
8321   /// Helper function to get a range from SCEV for the associated value at
8322   /// program point \p I.
8323   ConstantRange getConstantRangeFromSCEV(Attributor &A,
8324                                          const Instruction *I = nullptr) const {
8325     if (!getAnchorScope())
8326       return getWorstState(getBitWidth());
8327 
8328     ScalarEvolution *SE =
8329         A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8330             *getAnchorScope());
8331 
8332     const SCEV *S = getSCEV(A, I);
8333     if (!SE || !S)
8334       return getWorstState(getBitWidth());
8335 
8336     return SE->getUnsignedRange(S);
8337   }
8338 
8339   /// Helper function to get a range from LVI for the associated value at
8340   /// program point \p I.
8341   ConstantRange
8342   getConstantRangeFromLVI(Attributor &A,
8343                           const Instruction *CtxI = nullptr) const {
8344     if (!getAnchorScope())
8345       return getWorstState(getBitWidth());
8346 
8347     LazyValueInfo *LVI =
8348         A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
8349             *getAnchorScope());
8350 
8351     if (!LVI || !CtxI)
8352       return getWorstState(getBitWidth());
8353     return LVI->getConstantRange(&getAssociatedValue(),
8354                                  const_cast<Instruction *>(CtxI));
8355   }
8356 
8357   /// Return true if \p CtxI is valid for querying outside analyses.
8358   /// This basically makes sure we do not ask intra-procedural analysis
8359   /// about a context in the wrong function or a context that violates
8360   /// dominance assumptions they might have. The \p AllowAACtxI flag indicates
8361   /// if the original context of this AA is OK or should be considered invalid.
8362   bool isValidCtxInstructionForOutsideAnalysis(Attributor &A,
8363                                                const Instruction *CtxI,
8364                                                bool AllowAACtxI) const {
8365     if (!CtxI || (!AllowAACtxI && CtxI == getCtxI()))
8366       return false;
8367 
8368     // Our context might be in a different function, neither intra-procedural
8369     // analysis (ScalarEvolution nor LazyValueInfo) can handle that.
8370     if (!AA::isValidInScope(getAssociatedValue(), CtxI->getFunction()))
8371       return false;
8372 
8373     // If the context is not dominated by the value there are paths to the
8374     // context that do not define the value. This cannot be handled by
8375     // LazyValueInfo so we need to bail.
8376     if (auto *I = dyn_cast<Instruction>(&getAssociatedValue())) {
8377       InformationCache &InfoCache = A.getInfoCache();
8378       const DominatorTree *DT =
8379           InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
8380               *I->getFunction());
8381       return DT && DT->dominates(I, CtxI);
8382     }
8383 
8384     return true;
8385   }
8386 
8387   /// See AAValueConstantRange::getKnownConstantRange(..).
8388   ConstantRange
8389   getKnownConstantRange(Attributor &A,
8390                         const Instruction *CtxI = nullptr) const override {
8391     if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI,
8392                                                  /* AllowAACtxI */ false))
8393       return getKnown();
8394 
8395     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
8396     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
8397     return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
8398   }
8399 
8400   /// See AAValueConstantRange::getAssumedConstantRange(..).
8401   ConstantRange
8402   getAssumedConstantRange(Attributor &A,
8403                           const Instruction *CtxI = nullptr) const override {
8404     // TODO: Make SCEV use Attributor assumption.
8405     //       We may be able to bound a variable range via assumptions in
8406     //       Attributor. ex.) If x is assumed to be in [1, 3] and y is known to
8407     //       evolve to x^2 + x, then we can say that y is in [2, 12].
8408     if (!isValidCtxInstructionForOutsideAnalysis(A, CtxI,
8409                                                  /* AllowAACtxI */ false))
8410       return getAssumed();
8411 
8412     ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI);
8413     ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI);
8414     return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
8415   }
8416 
8417   /// Helper function to create MDNode for range metadata.
8418   static MDNode *
8419   getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx,
8420                             const ConstantRange &AssumedConstantRange) {
8421     Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get(
8422                                   Ty, AssumedConstantRange.getLower())),
8423                               ConstantAsMetadata::get(ConstantInt::get(
8424                                   Ty, AssumedConstantRange.getUpper()))};
8425     return MDNode::get(Ctx, LowAndHigh);
8426   }
8427 
8428   /// Return true if \p Assumed is included in \p KnownRanges.
8429   static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) {
8430 
8431     if (Assumed.isFullSet())
8432       return false;
8433 
8434     if (!KnownRanges)
8435       return true;
8436 
8437     // If multiple ranges are annotated in IR, we give up to annotate assumed
8438     // range for now.
8439 
8440     // TODO:  If there exists a known range which containts assumed range, we
8441     // can say assumed range is better.
8442     if (KnownRanges->getNumOperands() > 2)
8443       return false;
8444 
8445     ConstantInt *Lower =
8446         mdconst::extract<ConstantInt>(KnownRanges->getOperand(0));
8447     ConstantInt *Upper =
8448         mdconst::extract<ConstantInt>(KnownRanges->getOperand(1));
8449 
8450     ConstantRange Known(Lower->getValue(), Upper->getValue());
8451     return Known.contains(Assumed) && Known != Assumed;
8452   }
8453 
8454   /// Helper function to set range metadata.
8455   static bool
8456   setRangeMetadataIfisBetterRange(Instruction *I,
8457                                   const ConstantRange &AssumedConstantRange) {
8458     auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range);
8459     if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
8460       if (!AssumedConstantRange.isEmptySet()) {
8461         I->setMetadata(LLVMContext::MD_range,
8462                        getMDNodeForConstantRange(I->getType(), I->getContext(),
8463                                                  AssumedConstantRange));
8464         return true;
8465       }
8466     }
8467     return false;
8468   }
8469 
8470   /// See AbstractAttribute::manifest()
8471   ChangeStatus manifest(Attributor &A) override {
8472     ChangeStatus Changed = ChangeStatus::UNCHANGED;
8473     ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
8474     assert(!AssumedConstantRange.isFullSet() && "Invalid state");
8475 
8476     auto &V = getAssociatedValue();
8477     if (!AssumedConstantRange.isEmptySet() &&
8478         !AssumedConstantRange.isSingleElement()) {
8479       if (Instruction *I = dyn_cast<Instruction>(&V)) {
8480         assert(I == getCtxI() && "Should not annotate an instruction which is "
8481                                  "not the context instruction");
8482         if (isa<CallInst>(I) || isa<LoadInst>(I))
8483           if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange))
8484             Changed = ChangeStatus::CHANGED;
8485       }
8486     }
8487 
8488     return Changed;
8489   }
8490 };
8491 
8492 struct AAValueConstantRangeArgument final
8493     : AAArgumentFromCallSiteArguments<
8494           AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
8495           true /* BridgeCallBaseContext */> {
8496   using Base = AAArgumentFromCallSiteArguments<
8497       AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
8498       true /* BridgeCallBaseContext */>;
8499   AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A)
8500       : Base(IRP, A) {}
8501 
8502   /// See AbstractAttribute::initialize(..).
8503   void initialize(Attributor &A) override {
8504     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
8505       indicatePessimisticFixpoint();
8506     } else {
8507       Base::initialize(A);
8508     }
8509   }
8510 
8511   /// See AbstractAttribute::trackStatistics()
8512   void trackStatistics() const override {
8513     STATS_DECLTRACK_ARG_ATTR(value_range)
8514   }
8515 };
8516 
8517 struct AAValueConstantRangeReturned
8518     : AAReturnedFromReturnedValues<AAValueConstantRange,
8519                                    AAValueConstantRangeImpl,
8520                                    AAValueConstantRangeImpl::StateType,
8521                                    /* PropogateCallBaseContext */ true> {
8522   using Base =
8523       AAReturnedFromReturnedValues<AAValueConstantRange,
8524                                    AAValueConstantRangeImpl,
8525                                    AAValueConstantRangeImpl::StateType,
8526                                    /* PropogateCallBaseContext */ true>;
8527   AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A)
8528       : Base(IRP, A) {}
8529 
8530   /// See AbstractAttribute::initialize(...).
8531   void initialize(Attributor &A) override {}
8532 
8533   /// See AbstractAttribute::trackStatistics()
8534   void trackStatistics() const override {
8535     STATS_DECLTRACK_FNRET_ATTR(value_range)
8536   }
8537 };
8538 
8539 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
8540   AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A)
8541       : AAValueConstantRangeImpl(IRP, A) {}
8542 
8543   /// See AbstractAttribute::initialize(...).
8544   void initialize(Attributor &A) override {
8545     AAValueConstantRangeImpl::initialize(A);
8546     if (isAtFixpoint())
8547       return;
8548 
8549     Value &V = getAssociatedValue();
8550 
8551     if (auto *C = dyn_cast<ConstantInt>(&V)) {
8552       unionAssumed(ConstantRange(C->getValue()));
8553       indicateOptimisticFixpoint();
8554       return;
8555     }
8556 
8557     if (isa<UndefValue>(&V)) {
8558       // Collapse the undef state to 0.
8559       unionAssumed(ConstantRange(APInt(getBitWidth(), 0)));
8560       indicateOptimisticFixpoint();
8561       return;
8562     }
8563 
8564     if (isa<CallBase>(&V))
8565       return;
8566 
8567     if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V))
8568       return;
8569 
8570     // If it is a load instruction with range metadata, use it.
8571     if (LoadInst *LI = dyn_cast<LoadInst>(&V))
8572       if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
8573         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
8574         return;
8575       }
8576 
8577     // We can work with PHI and select instruction as we traverse their operands
8578     // during update.
8579     if (isa<SelectInst>(V) || isa<PHINode>(V))
8580       return;
8581 
8582     // Otherwise we give up.
8583     indicatePessimisticFixpoint();
8584 
8585     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: "
8586                       << getAssociatedValue() << "\n");
8587   }
8588 
8589   bool calculateBinaryOperator(
8590       Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T,
8591       const Instruction *CtxI,
8592       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
8593     Value *LHS = BinOp->getOperand(0);
8594     Value *RHS = BinOp->getOperand(1);
8595 
8596     // Simplify the operands first.
8597     bool UsedAssumedInformation = false;
8598     const auto &SimplifiedLHS =
8599         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
8600                                *this, UsedAssumedInformation);
8601     if (!SimplifiedLHS.hasValue())
8602       return true;
8603     if (!SimplifiedLHS.getValue())
8604       return false;
8605     LHS = *SimplifiedLHS;
8606 
8607     const auto &SimplifiedRHS =
8608         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
8609                                *this, UsedAssumedInformation);
8610     if (!SimplifiedRHS.hasValue())
8611       return true;
8612     if (!SimplifiedRHS.getValue())
8613       return false;
8614     RHS = *SimplifiedRHS;
8615 
8616     // TODO: Allow non integers as well.
8617     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
8618       return false;
8619 
8620     auto &LHSAA = A.getAAFor<AAValueConstantRange>(
8621         *this, IRPosition::value(*LHS, getCallBaseContext()),
8622         DepClassTy::REQUIRED);
8623     QuerriedAAs.push_back(&LHSAA);
8624     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
8625 
8626     auto &RHSAA = A.getAAFor<AAValueConstantRange>(
8627         *this, IRPosition::value(*RHS, getCallBaseContext()),
8628         DepClassTy::REQUIRED);
8629     QuerriedAAs.push_back(&RHSAA);
8630     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
8631 
8632     auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange);
8633 
8634     T.unionAssumed(AssumedRange);
8635 
8636     // TODO: Track a known state too.
8637 
8638     return T.isValidState();
8639   }
8640 
8641   bool calculateCastInst(
8642       Attributor &A, CastInst *CastI, IntegerRangeState &T,
8643       const Instruction *CtxI,
8644       SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
8645     assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!");
8646     // TODO: Allow non integers as well.
8647     Value *OpV = CastI->getOperand(0);
8648 
8649     // Simplify the operand first.
8650     bool UsedAssumedInformation = false;
8651     const auto &SimplifiedOpV =
8652         A.getAssumedSimplified(IRPosition::value(*OpV, getCallBaseContext()),
8653                                *this, UsedAssumedInformation);
8654     if (!SimplifiedOpV.hasValue())
8655       return true;
8656     if (!SimplifiedOpV.getValue())
8657       return false;
8658     OpV = *SimplifiedOpV;
8659 
8660     if (!OpV->getType()->isIntegerTy())
8661       return false;
8662 
8663     auto &OpAA = A.getAAFor<AAValueConstantRange>(
8664         *this, IRPosition::value(*OpV, getCallBaseContext()),
8665         DepClassTy::REQUIRED);
8666     QuerriedAAs.push_back(&OpAA);
8667     T.unionAssumed(
8668         OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth()));
8669     return T.isValidState();
8670   }
8671 
8672   bool
8673   calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T,
8674                    const Instruction *CtxI,
8675                    SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
8676     Value *LHS = CmpI->getOperand(0);
8677     Value *RHS = CmpI->getOperand(1);
8678 
8679     // Simplify the operands first.
8680     bool UsedAssumedInformation = false;
8681     const auto &SimplifiedLHS =
8682         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
8683                                *this, UsedAssumedInformation);
8684     if (!SimplifiedLHS.hasValue())
8685       return true;
8686     if (!SimplifiedLHS.getValue())
8687       return false;
8688     LHS = *SimplifiedLHS;
8689 
8690     const auto &SimplifiedRHS =
8691         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
8692                                *this, UsedAssumedInformation);
8693     if (!SimplifiedRHS.hasValue())
8694       return true;
8695     if (!SimplifiedRHS.getValue())
8696       return false;
8697     RHS = *SimplifiedRHS;
8698 
8699     // TODO: Allow non integers as well.
8700     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
8701       return false;
8702 
8703     auto &LHSAA = A.getAAFor<AAValueConstantRange>(
8704         *this, IRPosition::value(*LHS, getCallBaseContext()),
8705         DepClassTy::REQUIRED);
8706     QuerriedAAs.push_back(&LHSAA);
8707     auto &RHSAA = A.getAAFor<AAValueConstantRange>(
8708         *this, IRPosition::value(*RHS, getCallBaseContext()),
8709         DepClassTy::REQUIRED);
8710     QuerriedAAs.push_back(&RHSAA);
8711     auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI);
8712     auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI);
8713 
8714     // If one of them is empty set, we can't decide.
8715     if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
8716       return true;
8717 
8718     bool MustTrue = false, MustFalse = false;
8719 
8720     auto AllowedRegion =
8721         ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange);
8722 
8723     if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
8724       MustFalse = true;
8725 
8726     if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange))
8727       MustTrue = true;
8728 
8729     assert((!MustTrue || !MustFalse) &&
8730            "Either MustTrue or MustFalse should be false!");
8731 
8732     if (MustTrue)
8733       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1)));
8734     else if (MustFalse)
8735       T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0)));
8736     else
8737       T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true));
8738 
8739     LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA
8740                       << " " << RHSAA << "\n");
8741 
8742     // TODO: Track a known state too.
8743     return T.isValidState();
8744   }
8745 
8746   /// See AbstractAttribute::updateImpl(...).
8747   ChangeStatus updateImpl(Attributor &A) override {
8748     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
8749                             IntegerRangeState &T, bool Stripped) -> bool {
8750       Instruction *I = dyn_cast<Instruction>(&V);
8751       if (!I || isa<CallBase>(I)) {
8752 
8753         // Simplify the operand first.
8754         bool UsedAssumedInformation = false;
8755         const auto &SimplifiedOpV =
8756             A.getAssumedSimplified(IRPosition::value(V, getCallBaseContext()),
8757                                    *this, UsedAssumedInformation);
8758         if (!SimplifiedOpV.hasValue())
8759           return true;
8760         if (!SimplifiedOpV.getValue())
8761           return false;
8762         Value *VPtr = *SimplifiedOpV;
8763 
8764         // If the value is not instruction, we query AA to Attributor.
8765         const auto &AA = A.getAAFor<AAValueConstantRange>(
8766             *this, IRPosition::value(*VPtr, getCallBaseContext()),
8767             DepClassTy::REQUIRED);
8768 
8769         // Clamp operator is not used to utilize a program point CtxI.
8770         T.unionAssumed(AA.getAssumedConstantRange(A, CtxI));
8771 
8772         return T.isValidState();
8773       }
8774 
8775       SmallVector<const AAValueConstantRange *, 4> QuerriedAAs;
8776       if (auto *BinOp = dyn_cast<BinaryOperator>(I)) {
8777         if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs))
8778           return false;
8779       } else if (auto *CmpI = dyn_cast<CmpInst>(I)) {
8780         if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs))
8781           return false;
8782       } else if (auto *CastI = dyn_cast<CastInst>(I)) {
8783         if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs))
8784           return false;
8785       } else {
8786         // Give up with other instructions.
8787         // TODO: Add other instructions
8788 
8789         T.indicatePessimisticFixpoint();
8790         return false;
8791       }
8792 
8793       // Catch circular reasoning in a pessimistic way for now.
8794       // TODO: Check how the range evolves and if we stripped anything, see also
8795       //       AADereferenceable or AAAlign for similar situations.
8796       for (const AAValueConstantRange *QueriedAA : QuerriedAAs) {
8797         if (QueriedAA != this)
8798           continue;
8799         // If we are in a stady state we do not need to worry.
8800         if (T.getAssumed() == getState().getAssumed())
8801           continue;
8802         T.indicatePessimisticFixpoint();
8803       }
8804 
8805       return T.isValidState();
8806     };
8807 
8808     IntegerRangeState T(getBitWidth());
8809 
8810     bool UsedAssumedInformation = false;
8811     if (!genericValueTraversal<IntegerRangeState>(A, getIRPosition(), *this, T,
8812                                                   VisitValueCB, getCtxI(),
8813                                                   UsedAssumedInformation,
8814                                                   /* UseValueSimplify */ false))
8815       return indicatePessimisticFixpoint();
8816 
8817     // Ensure that long def-use chains can't cause circular reasoning either by
8818     // introducing a cutoff below.
8819     if (clampStateAndIndicateChange(getState(), T) == ChangeStatus::UNCHANGED)
8820       return ChangeStatus::UNCHANGED;
8821     if (++NumChanges > MaxNumChanges) {
8822       LLVM_DEBUG(dbgs() << "[AAValueConstantRange] performed " << NumChanges
8823                         << " but only " << MaxNumChanges
8824                         << " are allowed to avoid cyclic reasoning.");
8825       return indicatePessimisticFixpoint();
8826     }
8827     return ChangeStatus::CHANGED;
8828   }
8829 
8830   /// See AbstractAttribute::trackStatistics()
8831   void trackStatistics() const override {
8832     STATS_DECLTRACK_FLOATING_ATTR(value_range)
8833   }
8834 
8835   /// Tracker to bail after too many widening steps of the constant range.
8836   int NumChanges = 0;
8837 
8838   /// Upper bound for the number of allowed changes (=widening steps) for the
8839   /// constant range before we give up.
8840   static constexpr int MaxNumChanges = 5;
8841 };
8842 
8843 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
8844   AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A)
8845       : AAValueConstantRangeImpl(IRP, A) {}
8846 
8847   /// See AbstractAttribute::initialize(...).
8848   ChangeStatus updateImpl(Attributor &A) override {
8849     llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will "
8850                      "not be called");
8851   }
8852 
8853   /// See AbstractAttribute::trackStatistics()
8854   void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) }
8855 };
8856 
8857 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
8858   AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A)
8859       : AAValueConstantRangeFunction(IRP, A) {}
8860 
8861   /// See AbstractAttribute::trackStatistics()
8862   void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) }
8863 };
8864 
8865 struct AAValueConstantRangeCallSiteReturned
8866     : AACallSiteReturnedFromReturned<AAValueConstantRange,
8867                                      AAValueConstantRangeImpl,
8868                                      AAValueConstantRangeImpl::StateType,
8869                                      /* IntroduceCallBaseContext */ true> {
8870   AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A)
8871       : AACallSiteReturnedFromReturned<AAValueConstantRange,
8872                                        AAValueConstantRangeImpl,
8873                                        AAValueConstantRangeImpl::StateType,
8874                                        /* IntroduceCallBaseContext */ true>(IRP,
8875                                                                             A) {
8876   }
8877 
8878   /// See AbstractAttribute::initialize(...).
8879   void initialize(Attributor &A) override {
8880     // If it is a load instruction with range metadata, use the metadata.
8881     if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue()))
8882       if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
8883         intersectKnown(getConstantRangeFromMetadata(*RangeMD));
8884 
8885     AAValueConstantRangeImpl::initialize(A);
8886   }
8887 
8888   /// See AbstractAttribute::trackStatistics()
8889   void trackStatistics() const override {
8890     STATS_DECLTRACK_CSRET_ATTR(value_range)
8891   }
8892 };
8893 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
8894   AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A)
8895       : AAValueConstantRangeFloating(IRP, A) {}
8896 
8897   /// See AbstractAttribute::manifest()
8898   ChangeStatus manifest(Attributor &A) override {
8899     return ChangeStatus::UNCHANGED;
8900   }
8901 
8902   /// See AbstractAttribute::trackStatistics()
8903   void trackStatistics() const override {
8904     STATS_DECLTRACK_CSARG_ATTR(value_range)
8905   }
8906 };
8907 } // namespace
8908 
8909 /// ------------------ Potential Values Attribute -------------------------
8910 
8911 namespace {
8912 struct AAPotentialConstantValuesImpl : AAPotentialConstantValues {
8913   using StateType = PotentialConstantIntValuesState;
8914 
8915   AAPotentialConstantValuesImpl(const IRPosition &IRP, Attributor &A)
8916       : AAPotentialConstantValues(IRP, A) {}
8917 
8918   /// See AbstractAttribute::initialize(..).
8919   void initialize(Attributor &A) override {
8920     if (A.hasSimplificationCallback(getIRPosition()))
8921       indicatePessimisticFixpoint();
8922     else
8923       AAPotentialConstantValues::initialize(A);
8924   }
8925 
8926   /// See AbstractAttribute::getAsStr().
8927   const std::string getAsStr() const override {
8928     std::string Str;
8929     llvm::raw_string_ostream OS(Str);
8930     OS << getState();
8931     return OS.str();
8932   }
8933 
8934   /// See AbstractAttribute::updateImpl(...).
8935   ChangeStatus updateImpl(Attributor &A) override {
8936     return indicatePessimisticFixpoint();
8937   }
8938 };
8939 
8940 struct AAPotentialConstantValuesArgument final
8941     : AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
8942                                       AAPotentialConstantValuesImpl,
8943                                       PotentialConstantIntValuesState> {
8944   using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
8945                                                AAPotentialConstantValuesImpl,
8946                                                PotentialConstantIntValuesState>;
8947   AAPotentialConstantValuesArgument(const IRPosition &IRP, Attributor &A)
8948       : Base(IRP, A) {}
8949 
8950   /// See AbstractAttribute::initialize(..).
8951   void initialize(Attributor &A) override {
8952     if (!getAnchorScope() || getAnchorScope()->isDeclaration()) {
8953       indicatePessimisticFixpoint();
8954     } else {
8955       Base::initialize(A);
8956     }
8957   }
8958 
8959   /// See AbstractAttribute::trackStatistics()
8960   void trackStatistics() const override {
8961     STATS_DECLTRACK_ARG_ATTR(potential_values)
8962   }
8963 };
8964 
8965 struct AAPotentialConstantValuesReturned
8966     : AAReturnedFromReturnedValues<AAPotentialConstantValues,
8967                                    AAPotentialConstantValuesImpl> {
8968   using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues,
8969                                             AAPotentialConstantValuesImpl>;
8970   AAPotentialConstantValuesReturned(const IRPosition &IRP, Attributor &A)
8971       : Base(IRP, A) {}
8972 
8973   /// See AbstractAttribute::trackStatistics()
8974   void trackStatistics() const override {
8975     STATS_DECLTRACK_FNRET_ATTR(potential_values)
8976   }
8977 };
8978 
8979 struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
8980   AAPotentialConstantValuesFloating(const IRPosition &IRP, Attributor &A)
8981       : AAPotentialConstantValuesImpl(IRP, A) {}
8982 
8983   /// See AbstractAttribute::initialize(..).
8984   void initialize(Attributor &A) override {
8985     AAPotentialConstantValuesImpl::initialize(A);
8986     if (isAtFixpoint())
8987       return;
8988 
8989     Value &V = getAssociatedValue();
8990 
8991     if (auto *C = dyn_cast<ConstantInt>(&V)) {
8992       unionAssumed(C->getValue());
8993       indicateOptimisticFixpoint();
8994       return;
8995     }
8996 
8997     if (isa<UndefValue>(&V)) {
8998       unionAssumedWithUndef();
8999       indicateOptimisticFixpoint();
9000       return;
9001     }
9002 
9003     if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V))
9004       return;
9005 
9006     if (isa<SelectInst>(V) || isa<PHINode>(V) || isa<LoadInst>(V))
9007       return;
9008 
9009     indicatePessimisticFixpoint();
9010 
9011     LLVM_DEBUG(dbgs() << "[AAPotentialConstantValues] We give up: "
9012                       << getAssociatedValue() << "\n");
9013   }
9014 
9015   static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS,
9016                                 const APInt &RHS) {
9017     return ICmpInst::compare(LHS, RHS, ICI->getPredicate());
9018   }
9019 
9020   static APInt calculateCastInst(const CastInst *CI, const APInt &Src,
9021                                  uint32_t ResultBitWidth) {
9022     Instruction::CastOps CastOp = CI->getOpcode();
9023     switch (CastOp) {
9024     default:
9025       llvm_unreachable("unsupported or not integer cast");
9026     case Instruction::Trunc:
9027       return Src.trunc(ResultBitWidth);
9028     case Instruction::SExt:
9029       return Src.sext(ResultBitWidth);
9030     case Instruction::ZExt:
9031       return Src.zext(ResultBitWidth);
9032     case Instruction::BitCast:
9033       return Src;
9034     }
9035   }
9036 
9037   static APInt calculateBinaryOperator(const BinaryOperator *BinOp,
9038                                        const APInt &LHS, const APInt &RHS,
9039                                        bool &SkipOperation, bool &Unsupported) {
9040     Instruction::BinaryOps BinOpcode = BinOp->getOpcode();
9041     // Unsupported is set to true when the binary operator is not supported.
9042     // SkipOperation is set to true when UB occur with the given operand pair
9043     // (LHS, RHS).
9044     // TODO: we should look at nsw and nuw keywords to handle operations
9045     //       that create poison or undef value.
9046     switch (BinOpcode) {
9047     default:
9048       Unsupported = true;
9049       return LHS;
9050     case Instruction::Add:
9051       return LHS + RHS;
9052     case Instruction::Sub:
9053       return LHS - RHS;
9054     case Instruction::Mul:
9055       return LHS * RHS;
9056     case Instruction::UDiv:
9057       if (RHS.isZero()) {
9058         SkipOperation = true;
9059         return LHS;
9060       }
9061       return LHS.udiv(RHS);
9062     case Instruction::SDiv:
9063       if (RHS.isZero()) {
9064         SkipOperation = true;
9065         return LHS;
9066       }
9067       return LHS.sdiv(RHS);
9068     case Instruction::URem:
9069       if (RHS.isZero()) {
9070         SkipOperation = true;
9071         return LHS;
9072       }
9073       return LHS.urem(RHS);
9074     case Instruction::SRem:
9075       if (RHS.isZero()) {
9076         SkipOperation = true;
9077         return LHS;
9078       }
9079       return LHS.srem(RHS);
9080     case Instruction::Shl:
9081       return LHS.shl(RHS);
9082     case Instruction::LShr:
9083       return LHS.lshr(RHS);
9084     case Instruction::AShr:
9085       return LHS.ashr(RHS);
9086     case Instruction::And:
9087       return LHS & RHS;
9088     case Instruction::Or:
9089       return LHS | RHS;
9090     case Instruction::Xor:
9091       return LHS ^ RHS;
9092     }
9093   }
9094 
9095   bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp,
9096                                            const APInt &LHS, const APInt &RHS) {
9097     bool SkipOperation = false;
9098     bool Unsupported = false;
9099     APInt Result =
9100         calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported);
9101     if (Unsupported)
9102       return false;
9103     // If SkipOperation is true, we can ignore this operand pair (L, R).
9104     if (!SkipOperation)
9105       unionAssumed(Result);
9106     return isValidState();
9107   }
9108 
9109   ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) {
9110     auto AssumedBefore = getAssumed();
9111     Value *LHS = ICI->getOperand(0);
9112     Value *RHS = ICI->getOperand(1);
9113 
9114     // Simplify the operands first.
9115     bool UsedAssumedInformation = false;
9116     const auto &SimplifiedLHS =
9117         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
9118                                *this, UsedAssumedInformation);
9119     if (!SimplifiedLHS.hasValue())
9120       return ChangeStatus::UNCHANGED;
9121     if (!SimplifiedLHS.getValue())
9122       return indicatePessimisticFixpoint();
9123     LHS = *SimplifiedLHS;
9124 
9125     const auto &SimplifiedRHS =
9126         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
9127                                *this, UsedAssumedInformation);
9128     if (!SimplifiedRHS.hasValue())
9129       return ChangeStatus::UNCHANGED;
9130     if (!SimplifiedRHS.getValue())
9131       return indicatePessimisticFixpoint();
9132     RHS = *SimplifiedRHS;
9133 
9134     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9135       return indicatePessimisticFixpoint();
9136 
9137     auto &LHSAA = A.getAAFor<AAPotentialConstantValues>(
9138         *this, IRPosition::value(*LHS), DepClassTy::REQUIRED);
9139     if (!LHSAA.isValidState())
9140       return indicatePessimisticFixpoint();
9141 
9142     auto &RHSAA = A.getAAFor<AAPotentialConstantValues>(
9143         *this, IRPosition::value(*RHS), DepClassTy::REQUIRED);
9144     if (!RHSAA.isValidState())
9145       return indicatePessimisticFixpoint();
9146 
9147     const SetTy &LHSAAPVS = LHSAA.getAssumedSet();
9148     const SetTy &RHSAAPVS = RHSAA.getAssumedSet();
9149 
9150     // TODO: make use of undef flag to limit potential values aggressively.
9151     bool MaybeTrue = false, MaybeFalse = false;
9152     const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0);
9153     if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) {
9154       // The result of any comparison between undefs can be soundly replaced
9155       // with undef.
9156       unionAssumedWithUndef();
9157     } else if (LHSAA.undefIsContained()) {
9158       for (const APInt &R : RHSAAPVS) {
9159         bool CmpResult = calculateICmpInst(ICI, Zero, R);
9160         MaybeTrue |= CmpResult;
9161         MaybeFalse |= !CmpResult;
9162         if (MaybeTrue & MaybeFalse)
9163           return indicatePessimisticFixpoint();
9164       }
9165     } else if (RHSAA.undefIsContained()) {
9166       for (const APInt &L : LHSAAPVS) {
9167         bool CmpResult = calculateICmpInst(ICI, L, Zero);
9168         MaybeTrue |= CmpResult;
9169         MaybeFalse |= !CmpResult;
9170         if (MaybeTrue & MaybeFalse)
9171           return indicatePessimisticFixpoint();
9172       }
9173     } else {
9174       for (const APInt &L : LHSAAPVS) {
9175         for (const APInt &R : RHSAAPVS) {
9176           bool CmpResult = calculateICmpInst(ICI, L, R);
9177           MaybeTrue |= CmpResult;
9178           MaybeFalse |= !CmpResult;
9179           if (MaybeTrue & MaybeFalse)
9180             return indicatePessimisticFixpoint();
9181         }
9182       }
9183     }
9184     if (MaybeTrue)
9185       unionAssumed(APInt(/* numBits */ 1, /* val */ 1));
9186     if (MaybeFalse)
9187       unionAssumed(APInt(/* numBits */ 1, /* val */ 0));
9188     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9189                                          : ChangeStatus::CHANGED;
9190   }
9191 
9192   ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) {
9193     auto AssumedBefore = getAssumed();
9194     Value *LHS = SI->getTrueValue();
9195     Value *RHS = SI->getFalseValue();
9196 
9197     // Simplify the operands first.
9198     bool UsedAssumedInformation = false;
9199     const auto &SimplifiedLHS =
9200         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
9201                                *this, UsedAssumedInformation);
9202     if (!SimplifiedLHS.hasValue())
9203       return ChangeStatus::UNCHANGED;
9204     if (!SimplifiedLHS.getValue())
9205       return indicatePessimisticFixpoint();
9206     LHS = *SimplifiedLHS;
9207 
9208     const auto &SimplifiedRHS =
9209         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
9210                                *this, UsedAssumedInformation);
9211     if (!SimplifiedRHS.hasValue())
9212       return ChangeStatus::UNCHANGED;
9213     if (!SimplifiedRHS.getValue())
9214       return indicatePessimisticFixpoint();
9215     RHS = *SimplifiedRHS;
9216 
9217     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9218       return indicatePessimisticFixpoint();
9219 
9220     Optional<Constant *> C = A.getAssumedConstant(*SI->getCondition(), *this,
9221                                                   UsedAssumedInformation);
9222 
9223     // Check if we only need one operand.
9224     bool OnlyLeft = false, OnlyRight = false;
9225     if (C.hasValue() && *C && (*C)->isOneValue())
9226       OnlyLeft = true;
9227     else if (C.hasValue() && *C && (*C)->isZeroValue())
9228       OnlyRight = true;
9229 
9230     const AAPotentialConstantValues *LHSAA = nullptr, *RHSAA = nullptr;
9231     if (!OnlyRight) {
9232       LHSAA = &A.getAAFor<AAPotentialConstantValues>(
9233           *this, IRPosition::value(*LHS), DepClassTy::REQUIRED);
9234       if (!LHSAA->isValidState())
9235         return indicatePessimisticFixpoint();
9236     }
9237     if (!OnlyLeft) {
9238       RHSAA = &A.getAAFor<AAPotentialConstantValues>(
9239           *this, IRPosition::value(*RHS), DepClassTy::REQUIRED);
9240       if (!RHSAA->isValidState())
9241         return indicatePessimisticFixpoint();
9242     }
9243 
9244     if (!LHSAA || !RHSAA) {
9245       // select (true/false), lhs, rhs
9246       auto *OpAA = LHSAA ? LHSAA : RHSAA;
9247 
9248       if (OpAA->undefIsContained())
9249         unionAssumedWithUndef();
9250       else
9251         unionAssumed(*OpAA);
9252 
9253     } else if (LHSAA->undefIsContained() && RHSAA->undefIsContained()) {
9254       // select i1 *, undef , undef => undef
9255       unionAssumedWithUndef();
9256     } else {
9257       unionAssumed(*LHSAA);
9258       unionAssumed(*RHSAA);
9259     }
9260     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9261                                          : ChangeStatus::CHANGED;
9262   }
9263 
9264   ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) {
9265     auto AssumedBefore = getAssumed();
9266     if (!CI->isIntegerCast())
9267       return indicatePessimisticFixpoint();
9268     assert(CI->getNumOperands() == 1 && "Expected cast to be unary!");
9269     uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth();
9270     Value *Src = CI->getOperand(0);
9271 
9272     // Simplify the operand first.
9273     bool UsedAssumedInformation = false;
9274     const auto &SimplifiedSrc =
9275         A.getAssumedSimplified(IRPosition::value(*Src, getCallBaseContext()),
9276                                *this, UsedAssumedInformation);
9277     if (!SimplifiedSrc.hasValue())
9278       return ChangeStatus::UNCHANGED;
9279     if (!SimplifiedSrc.getValue())
9280       return indicatePessimisticFixpoint();
9281     Src = *SimplifiedSrc;
9282 
9283     auto &SrcAA = A.getAAFor<AAPotentialConstantValues>(
9284         *this, IRPosition::value(*Src), DepClassTy::REQUIRED);
9285     if (!SrcAA.isValidState())
9286       return indicatePessimisticFixpoint();
9287     const SetTy &SrcAAPVS = SrcAA.getAssumedSet();
9288     if (SrcAA.undefIsContained())
9289       unionAssumedWithUndef();
9290     else {
9291       for (const APInt &S : SrcAAPVS) {
9292         APInt T = calculateCastInst(CI, S, ResultBitWidth);
9293         unionAssumed(T);
9294       }
9295     }
9296     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9297                                          : ChangeStatus::CHANGED;
9298   }
9299 
9300   ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) {
9301     auto AssumedBefore = getAssumed();
9302     Value *LHS = BinOp->getOperand(0);
9303     Value *RHS = BinOp->getOperand(1);
9304 
9305     // Simplify the operands first.
9306     bool UsedAssumedInformation = false;
9307     const auto &SimplifiedLHS =
9308         A.getAssumedSimplified(IRPosition::value(*LHS, getCallBaseContext()),
9309                                *this, UsedAssumedInformation);
9310     if (!SimplifiedLHS.hasValue())
9311       return ChangeStatus::UNCHANGED;
9312     if (!SimplifiedLHS.getValue())
9313       return indicatePessimisticFixpoint();
9314     LHS = *SimplifiedLHS;
9315 
9316     const auto &SimplifiedRHS =
9317         A.getAssumedSimplified(IRPosition::value(*RHS, getCallBaseContext()),
9318                                *this, UsedAssumedInformation);
9319     if (!SimplifiedRHS.hasValue())
9320       return ChangeStatus::UNCHANGED;
9321     if (!SimplifiedRHS.getValue())
9322       return indicatePessimisticFixpoint();
9323     RHS = *SimplifiedRHS;
9324 
9325     if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
9326       return indicatePessimisticFixpoint();
9327 
9328     auto &LHSAA = A.getAAFor<AAPotentialConstantValues>(
9329         *this, IRPosition::value(*LHS), DepClassTy::REQUIRED);
9330     if (!LHSAA.isValidState())
9331       return indicatePessimisticFixpoint();
9332 
9333     auto &RHSAA = A.getAAFor<AAPotentialConstantValues>(
9334         *this, IRPosition::value(*RHS), DepClassTy::REQUIRED);
9335     if (!RHSAA.isValidState())
9336       return indicatePessimisticFixpoint();
9337 
9338     const SetTy &LHSAAPVS = LHSAA.getAssumedSet();
9339     const SetTy &RHSAAPVS = RHSAA.getAssumedSet();
9340     const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0);
9341 
9342     // TODO: make use of undef flag to limit potential values aggressively.
9343     if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) {
9344       if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero))
9345         return indicatePessimisticFixpoint();
9346     } else if (LHSAA.undefIsContained()) {
9347       for (const APInt &R : RHSAAPVS) {
9348         if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R))
9349           return indicatePessimisticFixpoint();
9350       }
9351     } else if (RHSAA.undefIsContained()) {
9352       for (const APInt &L : LHSAAPVS) {
9353         if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero))
9354           return indicatePessimisticFixpoint();
9355       }
9356     } else {
9357       for (const APInt &L : LHSAAPVS) {
9358         for (const APInt &R : RHSAAPVS) {
9359           if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
9360             return indicatePessimisticFixpoint();
9361         }
9362       }
9363     }
9364     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9365                                          : ChangeStatus::CHANGED;
9366   }
9367 
9368   ChangeStatus updateWithPHINode(Attributor &A, PHINode *PHI) {
9369     auto AssumedBefore = getAssumed();
9370     for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) {
9371       Value *IncomingValue = PHI->getIncomingValue(u);
9372 
9373       // Simplify the operand first.
9374       bool UsedAssumedInformation = false;
9375       const auto &SimplifiedIncomingValue = A.getAssumedSimplified(
9376           IRPosition::value(*IncomingValue, getCallBaseContext()), *this,
9377           UsedAssumedInformation);
9378       if (!SimplifiedIncomingValue.hasValue())
9379         continue;
9380       if (!SimplifiedIncomingValue.getValue())
9381         return indicatePessimisticFixpoint();
9382       IncomingValue = *SimplifiedIncomingValue;
9383 
9384       auto &PotentialValuesAA = A.getAAFor<AAPotentialConstantValues>(
9385           *this, IRPosition::value(*IncomingValue), DepClassTy::REQUIRED);
9386       if (!PotentialValuesAA.isValidState())
9387         return indicatePessimisticFixpoint();
9388       if (PotentialValuesAA.undefIsContained())
9389         unionAssumedWithUndef();
9390       else
9391         unionAssumed(PotentialValuesAA.getAssumed());
9392     }
9393     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9394                                          : ChangeStatus::CHANGED;
9395   }
9396 
9397   /// See AbstractAttribute::updateImpl(...).
9398   ChangeStatus updateImpl(Attributor &A) override {
9399     Value &V = getAssociatedValue();
9400     Instruction *I = dyn_cast<Instruction>(&V);
9401 
9402     if (auto *ICI = dyn_cast<ICmpInst>(I))
9403       return updateWithICmpInst(A, ICI);
9404 
9405     if (auto *SI = dyn_cast<SelectInst>(I))
9406       return updateWithSelectInst(A, SI);
9407 
9408     if (auto *CI = dyn_cast<CastInst>(I))
9409       return updateWithCastInst(A, CI);
9410 
9411     if (auto *BinOp = dyn_cast<BinaryOperator>(I))
9412       return updateWithBinaryOperator(A, BinOp);
9413 
9414     if (auto *PHI = dyn_cast<PHINode>(I))
9415       return updateWithPHINode(A, PHI);
9416 
9417     return indicatePessimisticFixpoint();
9418   }
9419 
9420   /// See AbstractAttribute::trackStatistics()
9421   void trackStatistics() const override {
9422     STATS_DECLTRACK_FLOATING_ATTR(potential_values)
9423   }
9424 };
9425 
9426 struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl {
9427   AAPotentialConstantValuesFunction(const IRPosition &IRP, Attributor &A)
9428       : AAPotentialConstantValuesImpl(IRP, A) {}
9429 
9430   /// See AbstractAttribute::initialize(...).
9431   ChangeStatus updateImpl(Attributor &A) override {
9432     llvm_unreachable(
9433         "AAPotentialConstantValues(Function|CallSite)::updateImpl will "
9434         "not be called");
9435   }
9436 
9437   /// See AbstractAttribute::trackStatistics()
9438   void trackStatistics() const override {
9439     STATS_DECLTRACK_FN_ATTR(potential_values)
9440   }
9441 };
9442 
9443 struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction {
9444   AAPotentialConstantValuesCallSite(const IRPosition &IRP, Attributor &A)
9445       : AAPotentialConstantValuesFunction(IRP, A) {}
9446 
9447   /// See AbstractAttribute::trackStatistics()
9448   void trackStatistics() const override {
9449     STATS_DECLTRACK_CS_ATTR(potential_values)
9450   }
9451 };
9452 
9453 struct AAPotentialConstantValuesCallSiteReturned
9454     : AACallSiteReturnedFromReturned<AAPotentialConstantValues,
9455                                      AAPotentialConstantValuesImpl> {
9456   AAPotentialConstantValuesCallSiteReturned(const IRPosition &IRP,
9457                                             Attributor &A)
9458       : AACallSiteReturnedFromReturned<AAPotentialConstantValues,
9459                                        AAPotentialConstantValuesImpl>(IRP, A) {}
9460 
9461   /// See AbstractAttribute::trackStatistics()
9462   void trackStatistics() const override {
9463     STATS_DECLTRACK_CSRET_ATTR(potential_values)
9464   }
9465 };
9466 
9467 struct AAPotentialConstantValuesCallSiteArgument
9468     : AAPotentialConstantValuesFloating {
9469   AAPotentialConstantValuesCallSiteArgument(const IRPosition &IRP,
9470                                             Attributor &A)
9471       : AAPotentialConstantValuesFloating(IRP, A) {}
9472 
9473   /// See AbstractAttribute::initialize(..).
9474   void initialize(Attributor &A) override {
9475     AAPotentialConstantValuesImpl::initialize(A);
9476     if (isAtFixpoint())
9477       return;
9478 
9479     Value &V = getAssociatedValue();
9480 
9481     if (auto *C = dyn_cast<ConstantInt>(&V)) {
9482       unionAssumed(C->getValue());
9483       indicateOptimisticFixpoint();
9484       return;
9485     }
9486 
9487     if (isa<UndefValue>(&V)) {
9488       unionAssumedWithUndef();
9489       indicateOptimisticFixpoint();
9490       return;
9491     }
9492   }
9493 
9494   /// See AbstractAttribute::updateImpl(...).
9495   ChangeStatus updateImpl(Attributor &A) override {
9496     Value &V = getAssociatedValue();
9497     auto AssumedBefore = getAssumed();
9498     auto &AA = A.getAAFor<AAPotentialConstantValues>(
9499         *this, IRPosition::value(V), DepClassTy::REQUIRED);
9500     const auto &S = AA.getAssumed();
9501     unionAssumed(S);
9502     return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9503                                          : ChangeStatus::CHANGED;
9504   }
9505 
9506   /// See AbstractAttribute::trackStatistics()
9507   void trackStatistics() const override {
9508     STATS_DECLTRACK_CSARG_ATTR(potential_values)
9509   }
9510 };
9511 
9512 /// ------------------------ NoUndef Attribute ---------------------------------
9513 struct AANoUndefImpl : AANoUndef {
9514   AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {}
9515 
9516   /// See AbstractAttribute::initialize(...).
9517   void initialize(Attributor &A) override {
9518     if (getIRPosition().hasAttr({Attribute::NoUndef})) {
9519       indicateOptimisticFixpoint();
9520       return;
9521     }
9522     Value &V = getAssociatedValue();
9523     if (isa<UndefValue>(V))
9524       indicatePessimisticFixpoint();
9525     else if (isa<FreezeInst>(V))
9526       indicateOptimisticFixpoint();
9527     else if (getPositionKind() != IRPosition::IRP_RETURNED &&
9528              isGuaranteedNotToBeUndefOrPoison(&V))
9529       indicateOptimisticFixpoint();
9530     else
9531       AANoUndef::initialize(A);
9532   }
9533 
9534   /// See followUsesInMBEC
9535   bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I,
9536                        AANoUndef::StateType &State) {
9537     const Value *UseV = U->get();
9538     const DominatorTree *DT = nullptr;
9539     AssumptionCache *AC = nullptr;
9540     InformationCache &InfoCache = A.getInfoCache();
9541     if (Function *F = getAnchorScope()) {
9542       DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F);
9543       AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F);
9544     }
9545     State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT));
9546     bool TrackUse = false;
9547     // Track use for instructions which must produce undef or poison bits when
9548     // at least one operand contains such bits.
9549     if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I))
9550       TrackUse = true;
9551     return TrackUse;
9552   }
9553 
9554   /// See AbstractAttribute::getAsStr().
9555   const std::string getAsStr() const override {
9556     return getAssumed() ? "noundef" : "may-undef-or-poison";
9557   }
9558 
9559   ChangeStatus manifest(Attributor &A) override {
9560     // We don't manifest noundef attribute for dead positions because the
9561     // associated values with dead positions would be replaced with undef
9562     // values.
9563     bool UsedAssumedInformation = false;
9564     if (A.isAssumedDead(getIRPosition(), nullptr, nullptr,
9565                         UsedAssumedInformation))
9566       return ChangeStatus::UNCHANGED;
9567     // A position whose simplified value does not have any value is
9568     // considered to be dead. We don't manifest noundef in such positions for
9569     // the same reason above.
9570     if (!A.getAssumedSimplified(getIRPosition(), *this, UsedAssumedInformation)
9571              .hasValue())
9572       return ChangeStatus::UNCHANGED;
9573     return AANoUndef::manifest(A);
9574   }
9575 };
9576 
9577 struct AANoUndefFloating : public AANoUndefImpl {
9578   AANoUndefFloating(const IRPosition &IRP, Attributor &A)
9579       : AANoUndefImpl(IRP, A) {}
9580 
9581   /// See AbstractAttribute::initialize(...).
9582   void initialize(Attributor &A) override {
9583     AANoUndefImpl::initialize(A);
9584     if (!getState().isAtFixpoint())
9585       if (Instruction *CtxI = getCtxI())
9586         followUsesInMBEC(*this, A, getState(), *CtxI);
9587   }
9588 
9589   /// See AbstractAttribute::updateImpl(...).
9590   ChangeStatus updateImpl(Attributor &A) override {
9591     auto VisitValueCB = [&](Value &V, const Instruction *CtxI,
9592                             AANoUndef::StateType &T, bool Stripped) -> bool {
9593       const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V),
9594                                              DepClassTy::REQUIRED);
9595       if (!Stripped && this == &AA) {
9596         T.indicatePessimisticFixpoint();
9597       } else {
9598         const AANoUndef::StateType &S =
9599             static_cast<const AANoUndef::StateType &>(AA.getState());
9600         T ^= S;
9601       }
9602       return T.isValidState();
9603     };
9604 
9605     StateType T;
9606     bool UsedAssumedInformation = false;
9607     if (!genericValueTraversal<StateType>(A, getIRPosition(), *this, T,
9608                                           VisitValueCB, getCtxI(),
9609                                           UsedAssumedInformation))
9610       return indicatePessimisticFixpoint();
9611 
9612     return clampStateAndIndicateChange(getState(), T);
9613   }
9614 
9615   /// See AbstractAttribute::trackStatistics()
9616   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
9617 };
9618 
9619 struct AANoUndefReturned final
9620     : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
9621   AANoUndefReturned(const IRPosition &IRP, Attributor &A)
9622       : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {}
9623 
9624   /// See AbstractAttribute::trackStatistics()
9625   void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) }
9626 };
9627 
9628 struct AANoUndefArgument final
9629     : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
9630   AANoUndefArgument(const IRPosition &IRP, Attributor &A)
9631       : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {}
9632 
9633   /// See AbstractAttribute::trackStatistics()
9634   void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) }
9635 };
9636 
9637 struct AANoUndefCallSiteArgument final : AANoUndefFloating {
9638   AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A)
9639       : AANoUndefFloating(IRP, A) {}
9640 
9641   /// See AbstractAttribute::trackStatistics()
9642   void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) }
9643 };
9644 
9645 struct AANoUndefCallSiteReturned final
9646     : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> {
9647   AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A)
9648       : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {}
9649 
9650   /// See AbstractAttribute::trackStatistics()
9651   void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) }
9652 };
9653 
9654 struct AACallEdgesImpl : public AACallEdges {
9655   AACallEdgesImpl(const IRPosition &IRP, Attributor &A) : AACallEdges(IRP, A) {}
9656 
9657   virtual const SetVector<Function *> &getOptimisticEdges() const override {
9658     return CalledFunctions;
9659   }
9660 
9661   virtual bool hasUnknownCallee() const override { return HasUnknownCallee; }
9662 
9663   virtual bool hasNonAsmUnknownCallee() const override {
9664     return HasUnknownCalleeNonAsm;
9665   }
9666 
9667   const std::string getAsStr() const override {
9668     return "CallEdges[" + std::to_string(HasUnknownCallee) + "," +
9669            std::to_string(CalledFunctions.size()) + "]";
9670   }
9671 
9672   void trackStatistics() const override {}
9673 
9674 protected:
9675   void addCalledFunction(Function *Fn, ChangeStatus &Change) {
9676     if (CalledFunctions.insert(Fn)) {
9677       Change = ChangeStatus::CHANGED;
9678       LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName()
9679                         << "\n");
9680     }
9681   }
9682 
9683   void setHasUnknownCallee(bool NonAsm, ChangeStatus &Change) {
9684     if (!HasUnknownCallee)
9685       Change = ChangeStatus::CHANGED;
9686     if (NonAsm && !HasUnknownCalleeNonAsm)
9687       Change = ChangeStatus::CHANGED;
9688     HasUnknownCalleeNonAsm |= NonAsm;
9689     HasUnknownCallee = true;
9690   }
9691 
9692 private:
9693   /// Optimistic set of functions that might be called by this position.
9694   SetVector<Function *> CalledFunctions;
9695 
9696   /// Is there any call with a unknown callee.
9697   bool HasUnknownCallee = false;
9698 
9699   /// Is there any call with a unknown callee, excluding any inline asm.
9700   bool HasUnknownCalleeNonAsm = false;
9701 };
9702 
9703 struct AACallEdgesCallSite : public AACallEdgesImpl {
9704   AACallEdgesCallSite(const IRPosition &IRP, Attributor &A)
9705       : AACallEdgesImpl(IRP, A) {}
9706   /// See AbstractAttribute::updateImpl(...).
9707   ChangeStatus updateImpl(Attributor &A) override {
9708     ChangeStatus Change = ChangeStatus::UNCHANGED;
9709 
9710     auto VisitValue = [&](Value &V, const Instruction *CtxI, bool &HasUnknown,
9711                           bool Stripped) -> bool {
9712       if (Function *Fn = dyn_cast<Function>(&V)) {
9713         addCalledFunction(Fn, Change);
9714       } else {
9715         LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n");
9716         setHasUnknownCallee(true, Change);
9717       }
9718 
9719       // Explore all values.
9720       return true;
9721     };
9722 
9723     // Process any value that we might call.
9724     auto ProcessCalledOperand = [&](Value *V) {
9725       bool DummyValue = false;
9726       bool UsedAssumedInformation = false;
9727       if (!genericValueTraversal<bool>(A, IRPosition::value(*V), *this,
9728                                        DummyValue, VisitValue, nullptr,
9729                                        UsedAssumedInformation, false)) {
9730         // If we haven't gone through all values, assume that there are unknown
9731         // callees.
9732         setHasUnknownCallee(true, Change);
9733       }
9734     };
9735 
9736     CallBase *CB = cast<CallBase>(getCtxI());
9737 
9738     if (CB->isInlineAsm()) {
9739       if (!hasAssumption(*CB->getCaller(), "ompx_no_call_asm") &&
9740           !hasAssumption(*CB, "ompx_no_call_asm"))
9741         setHasUnknownCallee(false, Change);
9742       return Change;
9743     }
9744 
9745     // Process callee metadata if available.
9746     if (auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees)) {
9747       for (auto &Op : MD->operands()) {
9748         Function *Callee = mdconst::dyn_extract_or_null<Function>(Op);
9749         if (Callee)
9750           addCalledFunction(Callee, Change);
9751       }
9752       return Change;
9753     }
9754 
9755     // The most simple case.
9756     ProcessCalledOperand(CB->getCalledOperand());
9757 
9758     // Process callback functions.
9759     SmallVector<const Use *, 4u> CallbackUses;
9760     AbstractCallSite::getCallbackUses(*CB, CallbackUses);
9761     for (const Use *U : CallbackUses)
9762       ProcessCalledOperand(U->get());
9763 
9764     return Change;
9765   }
9766 };
9767 
9768 struct AACallEdgesFunction : public AACallEdgesImpl {
9769   AACallEdgesFunction(const IRPosition &IRP, Attributor &A)
9770       : AACallEdgesImpl(IRP, A) {}
9771 
9772   /// See AbstractAttribute::updateImpl(...).
9773   ChangeStatus updateImpl(Attributor &A) override {
9774     ChangeStatus Change = ChangeStatus::UNCHANGED;
9775 
9776     auto ProcessCallInst = [&](Instruction &Inst) {
9777       CallBase &CB = cast<CallBase>(Inst);
9778 
9779       auto &CBEdges = A.getAAFor<AACallEdges>(
9780           *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
9781       if (CBEdges.hasNonAsmUnknownCallee())
9782         setHasUnknownCallee(true, Change);
9783       if (CBEdges.hasUnknownCallee())
9784         setHasUnknownCallee(false, Change);
9785 
9786       for (Function *F : CBEdges.getOptimisticEdges())
9787         addCalledFunction(F, Change);
9788 
9789       return true;
9790     };
9791 
9792     // Visit all callable instructions.
9793     bool UsedAssumedInformation = false;
9794     if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this,
9795                                            UsedAssumedInformation,
9796                                            /* CheckBBLivenessOnly */ true)) {
9797       // If we haven't looked at all call like instructions, assume that there
9798       // are unknown callees.
9799       setHasUnknownCallee(true, Change);
9800     }
9801 
9802     return Change;
9803   }
9804 };
9805 
9806 struct AAFunctionReachabilityFunction : public AAFunctionReachability {
9807 private:
9808   struct QuerySet {
9809     void markReachable(const Function &Fn) {
9810       Reachable.insert(&Fn);
9811       Unreachable.erase(&Fn);
9812     }
9813 
9814     /// If there is no information about the function None is returned.
9815     Optional<bool> isCachedReachable(const Function &Fn) {
9816       // Assume that we can reach the function.
9817       // TODO: Be more specific with the unknown callee.
9818       if (CanReachUnknownCallee)
9819         return true;
9820 
9821       if (Reachable.count(&Fn))
9822         return true;
9823 
9824       if (Unreachable.count(&Fn))
9825         return false;
9826 
9827       return llvm::None;
9828     }
9829 
9830     /// Set of functions that we know for sure is reachable.
9831     DenseSet<const Function *> Reachable;
9832 
9833     /// Set of functions that are unreachable, but might become reachable.
9834     DenseSet<const Function *> Unreachable;
9835 
9836     /// If we can reach a function with a call to a unknown function we assume
9837     /// that we can reach any function.
9838     bool CanReachUnknownCallee = false;
9839   };
9840 
9841   struct QueryResolver : public QuerySet {
9842     ChangeStatus update(Attributor &A, const AAFunctionReachability &AA,
9843                         ArrayRef<const AACallEdges *> AAEdgesList) {
9844       ChangeStatus Change = ChangeStatus::UNCHANGED;
9845 
9846       for (auto *AAEdges : AAEdgesList) {
9847         if (AAEdges->hasUnknownCallee()) {
9848           if (!CanReachUnknownCallee)
9849             Change = ChangeStatus::CHANGED;
9850           CanReachUnknownCallee = true;
9851           return Change;
9852         }
9853       }
9854 
9855       for (const Function *Fn : make_early_inc_range(Unreachable)) {
9856         if (checkIfReachable(A, AA, AAEdgesList, *Fn)) {
9857           Change = ChangeStatus::CHANGED;
9858           markReachable(*Fn);
9859         }
9860       }
9861       return Change;
9862     }
9863 
9864     bool isReachable(Attributor &A, AAFunctionReachability &AA,
9865                      ArrayRef<const AACallEdges *> AAEdgesList,
9866                      const Function &Fn) {
9867       Optional<bool> Cached = isCachedReachable(Fn);
9868       if (Cached.hasValue())
9869         return Cached.getValue();
9870 
9871       // The query was not cached, thus it is new. We need to request an update
9872       // explicitly to make sure this the information is properly run to a
9873       // fixpoint.
9874       A.registerForUpdate(AA);
9875 
9876       // We need to assume that this function can't reach Fn to prevent
9877       // an infinite loop if this function is recursive.
9878       Unreachable.insert(&Fn);
9879 
9880       bool Result = checkIfReachable(A, AA, AAEdgesList, Fn);
9881       if (Result)
9882         markReachable(Fn);
9883       return Result;
9884     }
9885 
9886     bool checkIfReachable(Attributor &A, const AAFunctionReachability &AA,
9887                           ArrayRef<const AACallEdges *> AAEdgesList,
9888                           const Function &Fn) const {
9889 
9890       // Handle the most trivial case first.
9891       for (auto *AAEdges : AAEdgesList) {
9892         const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges();
9893 
9894         if (Edges.count(const_cast<Function *>(&Fn)))
9895           return true;
9896       }
9897 
9898       SmallVector<const AAFunctionReachability *, 8> Deps;
9899       for (auto &AAEdges : AAEdgesList) {
9900         const SetVector<Function *> &Edges = AAEdges->getOptimisticEdges();
9901 
9902         for (Function *Edge : Edges) {
9903           // Functions that do not call back into the module can be ignored.
9904           if (Edge->hasFnAttribute(Attribute::NoCallback))
9905             continue;
9906 
9907           // We don't need a dependency if the result is reachable.
9908           const AAFunctionReachability &EdgeReachability =
9909               A.getAAFor<AAFunctionReachability>(
9910                   AA, IRPosition::function(*Edge), DepClassTy::NONE);
9911           Deps.push_back(&EdgeReachability);
9912 
9913           if (EdgeReachability.canReach(A, Fn))
9914             return true;
9915         }
9916       }
9917 
9918       // The result is false for now, set dependencies and leave.
9919       for (auto *Dep : Deps)
9920         A.recordDependence(*Dep, AA, DepClassTy::REQUIRED);
9921 
9922       return false;
9923     }
9924   };
9925 
9926   /// Get call edges that can be reached by this instruction.
9927   bool getReachableCallEdges(Attributor &A, const AAReachability &Reachability,
9928                              const Instruction &Inst,
9929                              SmallVector<const AACallEdges *> &Result) const {
9930     // Determine call like instructions that we can reach from the inst.
9931     auto CheckCallBase = [&](Instruction &CBInst) {
9932       if (!Reachability.isAssumedReachable(A, Inst, CBInst))
9933         return true;
9934 
9935       auto &CB = cast<CallBase>(CBInst);
9936       const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
9937           *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
9938 
9939       Result.push_back(&AAEdges);
9940       return true;
9941     };
9942 
9943     bool UsedAssumedInformation = false;
9944     return A.checkForAllCallLikeInstructions(CheckCallBase, *this,
9945                                              UsedAssumedInformation,
9946                                              /* CheckBBLivenessOnly */ true);
9947   }
9948 
9949 public:
9950   AAFunctionReachabilityFunction(const IRPosition &IRP, Attributor &A)
9951       : AAFunctionReachability(IRP, A) {}
9952 
9953   bool canReach(Attributor &A, const Function &Fn) const override {
9954     if (!isValidState())
9955       return true;
9956 
9957     const AACallEdges &AAEdges =
9958         A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED);
9959 
9960     // Attributor returns attributes as const, so this function has to be
9961     // const for users of this attribute to use it without having to do
9962     // a const_cast.
9963     // This is a hack for us to be able to cache queries.
9964     auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this);
9965     bool Result = NonConstThis->WholeFunction.isReachable(A, *NonConstThis,
9966                                                           {&AAEdges}, Fn);
9967 
9968     return Result;
9969   }
9970 
9971   /// Can \p CB reach \p Fn
9972   bool canReach(Attributor &A, CallBase &CB,
9973                 const Function &Fn) const override {
9974     if (!isValidState())
9975       return true;
9976 
9977     const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
9978         *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED);
9979 
9980     // Attributor returns attributes as const, so this function has to be
9981     // const for users of this attribute to use it without having to do
9982     // a const_cast.
9983     // This is a hack for us to be able to cache queries.
9984     auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this);
9985     QueryResolver &CBQuery = NonConstThis->CBQueries[&CB];
9986 
9987     bool Result = CBQuery.isReachable(A, *NonConstThis, {&AAEdges}, Fn);
9988 
9989     return Result;
9990   }
9991 
9992   bool instructionCanReach(Attributor &A, const Instruction &Inst,
9993                            const Function &Fn,
9994                            bool UseBackwards) const override {
9995     if (!isValidState())
9996       return true;
9997 
9998     if (UseBackwards)
9999       return AA::isPotentiallyReachable(A, Inst, Fn, *this, nullptr);
10000 
10001     const auto &Reachability = A.getAAFor<AAReachability>(
10002         *this, IRPosition::function(*getAssociatedFunction()),
10003         DepClassTy::REQUIRED);
10004 
10005     SmallVector<const AACallEdges *> CallEdges;
10006     bool AllKnown = getReachableCallEdges(A, Reachability, Inst, CallEdges);
10007     // Attributor returns attributes as const, so this function has to be
10008     // const for users of this attribute to use it without having to do
10009     // a const_cast.
10010     // This is a hack for us to be able to cache queries.
10011     auto *NonConstThis = const_cast<AAFunctionReachabilityFunction *>(this);
10012     QueryResolver &InstQSet = NonConstThis->InstQueries[&Inst];
10013     if (!AllKnown)
10014       InstQSet.CanReachUnknownCallee = true;
10015 
10016     return InstQSet.isReachable(A, *NonConstThis, CallEdges, Fn);
10017   }
10018 
10019   /// See AbstractAttribute::updateImpl(...).
10020   ChangeStatus updateImpl(Attributor &A) override {
10021     const AACallEdges &AAEdges =
10022         A.getAAFor<AACallEdges>(*this, getIRPosition(), DepClassTy::REQUIRED);
10023     ChangeStatus Change = ChangeStatus::UNCHANGED;
10024 
10025     Change |= WholeFunction.update(A, *this, {&AAEdges});
10026 
10027     for (auto &CBPair : CBQueries) {
10028       const AACallEdges &AAEdges = A.getAAFor<AACallEdges>(
10029           *this, IRPosition::callsite_function(*CBPair.first),
10030           DepClassTy::REQUIRED);
10031 
10032       Change |= CBPair.second.update(A, *this, {&AAEdges});
10033     }
10034 
10035     // Update the Instruction queries.
10036     if (!InstQueries.empty()) {
10037       const AAReachability *Reachability = &A.getAAFor<AAReachability>(
10038           *this, IRPosition::function(*getAssociatedFunction()),
10039           DepClassTy::REQUIRED);
10040 
10041       // Check for local callbases first.
10042       for (auto &InstPair : InstQueries) {
10043         SmallVector<const AACallEdges *> CallEdges;
10044         bool AllKnown =
10045             getReachableCallEdges(A, *Reachability, *InstPair.first, CallEdges);
10046         // Update will return change if we this effects any queries.
10047         if (!AllKnown)
10048           InstPair.second.CanReachUnknownCallee = true;
10049         Change |= InstPair.second.update(A, *this, CallEdges);
10050       }
10051     }
10052 
10053     return Change;
10054   }
10055 
10056   const std::string getAsStr() const override {
10057     size_t QueryCount =
10058         WholeFunction.Reachable.size() + WholeFunction.Unreachable.size();
10059 
10060     return "FunctionReachability [" +
10061            std::to_string(WholeFunction.Reachable.size()) + "," +
10062            std::to_string(QueryCount) + "]";
10063   }
10064 
10065   void trackStatistics() const override {}
10066 
10067 private:
10068   bool canReachUnknownCallee() const override {
10069     return WholeFunction.CanReachUnknownCallee;
10070   }
10071 
10072   /// Used to answer if a the whole function can reacha a specific function.
10073   QueryResolver WholeFunction;
10074 
10075   /// Used to answer if a call base inside this function can reach a specific
10076   /// function.
10077   MapVector<const CallBase *, QueryResolver> CBQueries;
10078 
10079   /// This is for instruction queries than scan "forward".
10080   MapVector<const Instruction *, QueryResolver> InstQueries;
10081 };
10082 } // namespace
10083 
10084 /// ---------------------- Assumption Propagation ------------------------------
10085 namespace {
10086 struct AAAssumptionInfoImpl : public AAAssumptionInfo {
10087   AAAssumptionInfoImpl(const IRPosition &IRP, Attributor &A,
10088                        const DenseSet<StringRef> &Known)
10089       : AAAssumptionInfo(IRP, A, Known) {}
10090 
10091   bool hasAssumption(const StringRef Assumption) const override {
10092     return isValidState() && setContains(Assumption);
10093   }
10094 
10095   /// See AbstractAttribute::getAsStr()
10096   const std::string getAsStr() const override {
10097     const SetContents &Known = getKnown();
10098     const SetContents &Assumed = getAssumed();
10099 
10100     const std::string KnownStr =
10101         llvm::join(Known.getSet().begin(), Known.getSet().end(), ",");
10102     const std::string AssumedStr =
10103         (Assumed.isUniversal())
10104             ? "Universal"
10105             : llvm::join(Assumed.getSet().begin(), Assumed.getSet().end(), ",");
10106 
10107     return "Known [" + KnownStr + "]," + " Assumed [" + AssumedStr + "]";
10108   }
10109 };
10110 
10111 /// Propagates assumption information from parent functions to all of their
10112 /// successors. An assumption can be propagated if the containing function
10113 /// dominates the called function.
10114 ///
10115 /// We start with a "known" set of assumptions already valid for the associated
10116 /// function and an "assumed" set that initially contains all possible
10117 /// assumptions. The assumed set is inter-procedurally updated by narrowing its
10118 /// contents as concrete values are known. The concrete values are seeded by the
10119 /// first nodes that are either entries into the call graph, or contains no
10120 /// assumptions. Each node is updated as the intersection of the assumed state
10121 /// with all of its predecessors.
10122 struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl {
10123   AAAssumptionInfoFunction(const IRPosition &IRP, Attributor &A)
10124       : AAAssumptionInfoImpl(IRP, A,
10125                              getAssumptions(*IRP.getAssociatedFunction())) {}
10126 
10127   /// See AbstractAttribute::manifest(...).
10128   ChangeStatus manifest(Attributor &A) override {
10129     const auto &Assumptions = getKnown();
10130 
10131     // Don't manifest a universal set if it somehow made it here.
10132     if (Assumptions.isUniversal())
10133       return ChangeStatus::UNCHANGED;
10134 
10135     Function *AssociatedFunction = getAssociatedFunction();
10136 
10137     bool Changed = addAssumptions(*AssociatedFunction, Assumptions.getSet());
10138 
10139     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10140   }
10141 
10142   /// See AbstractAttribute::updateImpl(...).
10143   ChangeStatus updateImpl(Attributor &A) override {
10144     bool Changed = false;
10145 
10146     auto CallSitePred = [&](AbstractCallSite ACS) {
10147       const auto &AssumptionAA = A.getAAFor<AAAssumptionInfo>(
10148           *this, IRPosition::callsite_function(*ACS.getInstruction()),
10149           DepClassTy::REQUIRED);
10150       // Get the set of assumptions shared by all of this function's callers.
10151       Changed |= getIntersection(AssumptionAA.getAssumed());
10152       return !getAssumed().empty() || !getKnown().empty();
10153     };
10154 
10155     bool UsedAssumedInformation = false;
10156     // Get the intersection of all assumptions held by this node's predecessors.
10157     // If we don't know all the call sites then this is either an entry into the
10158     // call graph or an empty node. This node is known to only contain its own
10159     // assumptions and can be propagated to its successors.
10160     if (!A.checkForAllCallSites(CallSitePred, *this, true,
10161                                 UsedAssumedInformation))
10162       return indicatePessimisticFixpoint();
10163 
10164     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10165   }
10166 
10167   void trackStatistics() const override {}
10168 };
10169 
10170 /// Assumption Info defined for call sites.
10171 struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl {
10172 
10173   AAAssumptionInfoCallSite(const IRPosition &IRP, Attributor &A)
10174       : AAAssumptionInfoImpl(IRP, A, getInitialAssumptions(IRP)) {}
10175 
10176   /// See AbstractAttribute::initialize(...).
10177   void initialize(Attributor &A) override {
10178     const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
10179     A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
10180   }
10181 
10182   /// See AbstractAttribute::manifest(...).
10183   ChangeStatus manifest(Attributor &A) override {
10184     // Don't manifest a universal set if it somehow made it here.
10185     if (getKnown().isUniversal())
10186       return ChangeStatus::UNCHANGED;
10187 
10188     CallBase &AssociatedCall = cast<CallBase>(getAssociatedValue());
10189     bool Changed = addAssumptions(AssociatedCall, getAssumed().getSet());
10190 
10191     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10192   }
10193 
10194   /// See AbstractAttribute::updateImpl(...).
10195   ChangeStatus updateImpl(Attributor &A) override {
10196     const IRPosition &FnPos = IRPosition::function(*getAnchorScope());
10197     auto &AssumptionAA =
10198         A.getAAFor<AAAssumptionInfo>(*this, FnPos, DepClassTy::REQUIRED);
10199     bool Changed = getIntersection(AssumptionAA.getAssumed());
10200     return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
10201   }
10202 
10203   /// See AbstractAttribute::trackStatistics()
10204   void trackStatistics() const override {}
10205 
10206 private:
10207   /// Helper to initialized the known set as all the assumptions this call and
10208   /// the callee contain.
10209   DenseSet<StringRef> getInitialAssumptions(const IRPosition &IRP) {
10210     const CallBase &CB = cast<CallBase>(IRP.getAssociatedValue());
10211     auto Assumptions = getAssumptions(CB);
10212     if (Function *F = IRP.getAssociatedFunction())
10213       set_union(Assumptions, getAssumptions(*F));
10214     if (Function *F = IRP.getAssociatedFunction())
10215       set_union(Assumptions, getAssumptions(*F));
10216     return Assumptions;
10217   }
10218 };
10219 } // namespace
10220 
10221 AACallGraphNode *AACallEdgeIterator::operator*() const {
10222   return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>(
10223       &A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I))));
10224 }
10225 
10226 void AttributorCallGraph::print() { llvm::WriteGraph(outs(), this); }
10227 
10228 const char AAReturnedValues::ID = 0;
10229 const char AANoUnwind::ID = 0;
10230 const char AANoSync::ID = 0;
10231 const char AANoFree::ID = 0;
10232 const char AANonNull::ID = 0;
10233 const char AANoRecurse::ID = 0;
10234 const char AAWillReturn::ID = 0;
10235 const char AAUndefinedBehavior::ID = 0;
10236 const char AANoAlias::ID = 0;
10237 const char AAReachability::ID = 0;
10238 const char AANoReturn::ID = 0;
10239 const char AAIsDead::ID = 0;
10240 const char AADereferenceable::ID = 0;
10241 const char AAAlign::ID = 0;
10242 const char AAInstanceInfo::ID = 0;
10243 const char AANoCapture::ID = 0;
10244 const char AAValueSimplify::ID = 0;
10245 const char AAHeapToStack::ID = 0;
10246 const char AAPrivatizablePtr::ID = 0;
10247 const char AAMemoryBehavior::ID = 0;
10248 const char AAMemoryLocation::ID = 0;
10249 const char AAValueConstantRange::ID = 0;
10250 const char AAPotentialConstantValues::ID = 0;
10251 const char AANoUndef::ID = 0;
10252 const char AACallEdges::ID = 0;
10253 const char AAFunctionReachability::ID = 0;
10254 const char AAPointerInfo::ID = 0;
10255 const char AAAssumptionInfo::ID = 0;
10256 
10257 // Macro magic to create the static generator function for attributes that
10258 // follow the naming scheme.
10259 
10260 #define SWITCH_PK_INV(CLASS, PK, POS_NAME)                                     \
10261   case IRPosition::PK:                                                         \
10262     llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
10263 
10264 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX)                               \
10265   case IRPosition::PK:                                                         \
10266     AA = new (A.Allocator) CLASS##SUFFIX(IRP, A);                              \
10267     ++NumAAs;                                                                  \
10268     break;
10269 
10270 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                 \
10271   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10272     CLASS *AA = nullptr;                                                       \
10273     switch (IRP.getPositionKind()) {                                           \
10274       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10275       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
10276       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
10277       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
10278       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
10279       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
10280       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10281       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
10282     }                                                                          \
10283     return *AA;                                                                \
10284   }
10285 
10286 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                    \
10287   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10288     CLASS *AA = nullptr;                                                       \
10289     switch (IRP.getPositionKind()) {                                           \
10290       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10291       SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function")                           \
10292       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
10293       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
10294       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
10295       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
10296       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
10297       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
10298     }                                                                          \
10299     return *AA;                                                                \
10300   }
10301 
10302 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                      \
10303   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10304     CLASS *AA = nullptr;                                                       \
10305     switch (IRP.getPositionKind()) {                                           \
10306       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10307       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10308       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
10309       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
10310       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
10311       SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned)                     \
10312       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
10313       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
10314     }                                                                          \
10315     return *AA;                                                                \
10316   }
10317 
10318 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)            \
10319   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10320     CLASS *AA = nullptr;                                                       \
10321     switch (IRP.getPositionKind()) {                                           \
10322       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10323       SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument")                           \
10324       SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating")                              \
10325       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
10326       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned")       \
10327       SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument")       \
10328       SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site")                         \
10329       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10330     }                                                                          \
10331     return *AA;                                                                \
10332   }
10333 
10334 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)                  \
10335   CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) {      \
10336     CLASS *AA = nullptr;                                                       \
10337     switch (IRP.getPositionKind()) {                                           \
10338       SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid")                             \
10339       SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned")                           \
10340       SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function)                     \
10341       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite)                    \
10342       SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating)                        \
10343       SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument)                     \
10344       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned)   \
10345       SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument)   \
10346     }                                                                          \
10347     return *AA;                                                                \
10348   }
10349 
10350 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind)
10351 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync)
10352 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse)
10353 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn)
10354 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn)
10355 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues)
10356 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation)
10357 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AACallEdges)
10358 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAssumptionInfo)
10359 
10360 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull)
10361 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias)
10362 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr)
10363 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable)
10364 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign)
10365 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAInstanceInfo)
10366 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture)
10367 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange)
10368 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialConstantValues)
10369 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef)
10370 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPointerInfo)
10371 
10372 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify)
10373 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead)
10374 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree)
10375 
10376 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack)
10377 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability)
10378 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior)
10379 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAFunctionReachability)
10380 
10381 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior)
10382 
10383 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
10384 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
10385 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
10386 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
10387 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
10388 #undef SWITCH_PK_CREATE
10389 #undef SWITCH_PK_INV
10390