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