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