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/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/GlobalsModRef.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Argument.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/InstIterator.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 
39 #include <cassert>
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "attributor"
44 
45 STATISTIC(NumFnWithExactDefinition,
46           "Number of function with exact definitions");
47 STATISTIC(NumFnWithoutExactDefinition,
48           "Number of function without exact definitions");
49 STATISTIC(NumAttributesTimedOut,
50           "Number of abstract attributes timed out before fixpoint");
51 STATISTIC(NumAttributesValidFixpoint,
52           "Number of abstract attributes in a valid fixpoint state");
53 STATISTIC(NumAttributesManifested,
54           "Number of abstract attributes manifested in IR");
55 STATISTIC(NumFnNoUnwind, "Number of functions marked nounwind");
56 
57 STATISTIC(NumFnUniqueReturned, "Number of function with unique return");
58 STATISTIC(NumFnKnownReturns, "Number of function with known return values");
59 STATISTIC(NumFnArgumentReturned,
60           "Number of function arguments marked returned");
61 STATISTIC(NumFnNoSync, "Number of functions marked nosync");
62 STATISTIC(NumFnNoFree, "Number of functions marked nofree");
63 STATISTIC(NumFnReturnedNonNull,
64           "Number of function return values marked nonnull");
65 STATISTIC(NumFnArgumentNonNull, "Number of function arguments marked nonnull");
66 STATISTIC(NumCSArgumentNonNull, "Number of call site arguments marked nonnull");
67 STATISTIC(NumFnWillReturn, "Number of functions marked willreturn");
68 STATISTIC(NumFnArgumentNoAlias, "Number of function arguments marked noalias");
69 STATISTIC(NumFnReturnedDereferenceable,
70           "Number of function return values marked dereferenceable");
71 STATISTIC(NumFnArgumentDereferenceable,
72           "Number of function arguments marked dereferenceable");
73 STATISTIC(NumCSArgumentDereferenceable,
74           "Number of call site arguments marked dereferenceable");
75 STATISTIC(NumFnReturnedAlign, "Number of function return values marked align");
76 STATISTIC(NumFnArgumentAlign, "Number of function arguments marked align");
77 STATISTIC(NumCSArgumentAlign, "Number of call site arguments marked align");
78 
79 // TODO: Determine a good default value.
80 //
81 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
82 // (when run with the first 5 abstract attributes). The results also indicate
83 // that we never reach 32 iterations but always find a fixpoint sooner.
84 //
85 // This will become more evolved once we perform two interleaved fixpoint
86 // iterations: bottom-up and top-down.
87 static cl::opt<unsigned>
88     MaxFixpointIterations("attributor-max-iterations", cl::Hidden,
89                           cl::desc("Maximal number of fixpoint iterations."),
90                           cl::init(32));
91 
92 static cl::opt<bool> DisableAttributor(
93     "attributor-disable", cl::Hidden,
94     cl::desc("Disable the attributor inter-procedural deduction pass."),
95     cl::init(true));
96 
97 static cl::opt<bool> VerifyAttributor(
98     "attributor-verify", cl::Hidden,
99     cl::desc("Verify the Attributor deduction and "
100              "manifestation of attributes -- may issue false-positive errors"),
101     cl::init(false));
102 
103 /// Logic operators for the change status enum class.
104 ///
105 ///{
106 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) {
107   return l == ChangeStatus::CHANGED ? l : r;
108 }
109 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) {
110   return l == ChangeStatus::UNCHANGED ? l : r;
111 }
112 ///}
113 
114 /// Helper to adjust the statistics.
115 static void bookkeeping(AbstractAttribute::ManifestPosition MP,
116                         const Attribute &Attr) {
117   if (!AreStatisticsEnabled())
118     return;
119 
120   switch (Attr.getKindAsEnum()) {
121   case Attribute::Alignment:
122     switch (MP) {
123     case AbstractAttribute::MP_RETURNED:
124       NumFnReturnedAlign++;
125       break;
126     case AbstractAttribute::MP_ARGUMENT:
127       NumFnArgumentAlign++;
128       break;
129     case AbstractAttribute::MP_CALL_SITE_ARGUMENT:
130       NumCSArgumentAlign++;
131       break;
132     default:
133       break;
134     }
135     break;
136   case Attribute::Dereferenceable:
137     switch (MP) {
138     case AbstractAttribute::MP_RETURNED:
139       NumFnReturnedDereferenceable++;
140       break;
141     case AbstractAttribute::MP_ARGUMENT:
142       NumFnArgumentDereferenceable++;
143       break;
144     case AbstractAttribute::MP_CALL_SITE_ARGUMENT:
145       NumCSArgumentDereferenceable++;
146       break;
147     default:
148       break;
149     }
150     break;
151   case Attribute::NoUnwind:
152     NumFnNoUnwind++;
153     return;
154   case Attribute::Returned:
155     NumFnArgumentReturned++;
156     return;
157   case Attribute::NoSync:
158     NumFnNoSync++;
159     break;
160   case Attribute::NoFree:
161     NumFnNoFree++;
162     break;
163   case Attribute::NonNull:
164     switch (MP) {
165     case AbstractAttribute::MP_RETURNED:
166       NumFnReturnedNonNull++;
167       break;
168     case AbstractAttribute::MP_ARGUMENT:
169       NumFnArgumentNonNull++;
170       break;
171     case AbstractAttribute::MP_CALL_SITE_ARGUMENT:
172       NumCSArgumentNonNull++;
173       break;
174     default:
175       break;
176     }
177     break;
178   case Attribute::WillReturn:
179     NumFnWillReturn++;
180     break;
181   case Attribute::NoAlias:
182     NumFnArgumentNoAlias++;
183     return;
184   default:
185     return;
186   }
187 }
188 
189 template <typename StateTy>
190 using followValueCB_t = std::function<bool(Value *, StateTy &State)>;
191 template <typename StateTy>
192 using visitValueCB_t = std::function<void(Value *, StateTy &State)>;
193 
194 /// Recursively visit all values that might become \p InitV at some point. This
195 /// will be done by looking through cast instructions, selects, phis, and calls
196 /// with the "returned" attribute. The callback \p FollowValueCB is asked before
197 /// a potential origin value is looked at. If no \p FollowValueCB is passed, a
198 /// default one is used that will make sure we visit every value only once. Once
199 /// we cannot look through the value any further, the callback \p VisitValueCB
200 /// is invoked and passed the current value and the \p State. To limit how much
201 /// effort is invested, we will never visit more than \p MaxValues values.
202 template <typename StateTy>
203 static bool genericValueTraversal(
204     Value *InitV, StateTy &State, visitValueCB_t<StateTy> &VisitValueCB,
205     followValueCB_t<StateTy> *FollowValueCB = nullptr, int MaxValues = 8) {
206 
207   SmallPtrSet<Value *, 16> Visited;
208   followValueCB_t<bool> DefaultFollowValueCB = [&](Value *Val, bool &) {
209     return Visited.insert(Val).second;
210   };
211 
212   if (!FollowValueCB)
213     FollowValueCB = &DefaultFollowValueCB;
214 
215   SmallVector<Value *, 16> Worklist;
216   Worklist.push_back(InitV);
217 
218   int Iteration = 0;
219   do {
220     Value *V = Worklist.pop_back_val();
221 
222     // Check if we should process the current value. To prevent endless
223     // recursion keep a record of the values we followed!
224     if (!(*FollowValueCB)(V, State))
225       continue;
226 
227     // Make sure we limit the compile time for complex expressions.
228     if (Iteration++ >= MaxValues)
229       return false;
230 
231     // Explicitly look through calls with a "returned" attribute if we do
232     // not have a pointer as stripPointerCasts only works on them.
233     if (V->getType()->isPointerTy()) {
234       V = V->stripPointerCasts();
235     } else {
236       CallSite CS(V);
237       if (CS && CS.getCalledFunction()) {
238         Value *NewV = nullptr;
239         for (Argument &Arg : CS.getCalledFunction()->args())
240           if (Arg.hasReturnedAttr()) {
241             NewV = CS.getArgOperand(Arg.getArgNo());
242             break;
243           }
244         if (NewV) {
245           Worklist.push_back(NewV);
246           continue;
247         }
248       }
249     }
250 
251     // Look through select instructions, visit both potential values.
252     if (auto *SI = dyn_cast<SelectInst>(V)) {
253       Worklist.push_back(SI->getTrueValue());
254       Worklist.push_back(SI->getFalseValue());
255       continue;
256     }
257 
258     // Look through phi nodes, visit all operands.
259     if (auto *PHI = dyn_cast<PHINode>(V)) {
260       Worklist.append(PHI->op_begin(), PHI->op_end());
261       continue;
262     }
263 
264     // Once a leaf is reached we inform the user through the callback.
265     VisitValueCB(V, State);
266   } while (!Worklist.empty());
267 
268   // All values have been visited.
269   return true;
270 }
271 
272 /// Helper to identify the correct offset into an attribute list.
273 static unsigned getAttrIndex(AbstractAttribute::ManifestPosition MP,
274                              unsigned ArgNo = 0) {
275   switch (MP) {
276   case AbstractAttribute::MP_ARGUMENT:
277   case AbstractAttribute::MP_CALL_SITE_ARGUMENT:
278     return ArgNo + AttributeList::FirstArgIndex;
279   case AbstractAttribute::MP_FUNCTION:
280     return AttributeList::FunctionIndex;
281   case AbstractAttribute::MP_RETURNED:
282     return AttributeList::ReturnIndex;
283   }
284   llvm_unreachable("Unknown manifest position!");
285 }
286 
287 /// Return true if \p New is equal or worse than \p Old.
288 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
289   if (!Old.isIntAttribute())
290     return true;
291 
292   return Old.getValueAsInt() >= New.getValueAsInt();
293 }
294 
295 /// Return true if the information provided by \p Attr was added to the
296 /// attribute list \p Attrs. This is only the case if it was not already present
297 /// in \p Attrs at the position describe by \p MP and \p ArgNo.
298 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
299                              AttributeList &Attrs,
300                              AbstractAttribute::ManifestPosition MP,
301                              unsigned ArgNo = 0) {
302   unsigned AttrIdx = getAttrIndex(MP, ArgNo);
303 
304   if (Attr.isEnumAttribute()) {
305     Attribute::AttrKind Kind = Attr.getKindAsEnum();
306     if (Attrs.hasAttribute(AttrIdx, Kind))
307       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
308         return false;
309     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
310     return true;
311   }
312   if (Attr.isStringAttribute()) {
313     StringRef Kind = Attr.getKindAsString();
314     if (Attrs.hasAttribute(AttrIdx, Kind))
315       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
316         return false;
317     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
318     return true;
319   }
320   if (Attr.isIntAttribute()) {
321     Attribute::AttrKind Kind = Attr.getKindAsEnum();
322     if (Attrs.hasAttribute(AttrIdx, Kind))
323       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
324         return false;
325     Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind);
326     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
327     return true;
328   }
329 
330   llvm_unreachable("Expected enum or string attribute!");
331 }
332 
333 ChangeStatus AbstractAttribute::update(Attributor &A) {
334   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
335   if (getState().isAtFixpoint())
336     return HasChanged;
337 
338   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
339 
340   HasChanged = updateImpl(A);
341 
342   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
343                     << "\n");
344 
345   return HasChanged;
346 }
347 
348 ChangeStatus AbstractAttribute::manifest(Attributor &A) {
349   assert(getState().isValidState() &&
350          "Attempted to manifest an invalid state!");
351   assert(getAssociatedValue() &&
352          "Attempted to manifest an attribute without associated value!");
353 
354   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
355   SmallVector<Attribute, 4> DeducedAttrs;
356   getDeducedAttributes(DeducedAttrs);
357 
358   Function &ScopeFn = getAnchorScope();
359   LLVMContext &Ctx = ScopeFn.getContext();
360   ManifestPosition MP = getManifestPosition();
361 
362   AttributeList Attrs;
363   SmallVector<unsigned, 4> ArgNos;
364 
365   // In the following some generic code that will manifest attributes in
366   // DeducedAttrs if they improve the current IR. Due to the different
367   // annotation positions we use the underlying AttributeList interface.
368   // Note that MP_CALL_SITE_ARGUMENT can annotate multiple locations.
369 
370   switch (MP) {
371   case MP_ARGUMENT:
372     ArgNos.push_back(cast<Argument>(getAssociatedValue())->getArgNo());
373     Attrs = ScopeFn.getAttributes();
374     break;
375   case MP_FUNCTION:
376   case MP_RETURNED:
377     ArgNos.push_back(0);
378     Attrs = ScopeFn.getAttributes();
379     break;
380   case MP_CALL_SITE_ARGUMENT: {
381     CallSite CS(&getAnchoredValue());
382     for (unsigned u = 0, e = CS.getNumArgOperands(); u != e; u++)
383       if (CS.getArgOperand(u) == getAssociatedValue())
384         ArgNos.push_back(u);
385     Attrs = CS.getAttributes();
386   }
387   }
388 
389   for (const Attribute &Attr : DeducedAttrs) {
390     for (unsigned ArgNo : ArgNos) {
391       if (!addIfNotExistent(Ctx, Attr, Attrs, MP, ArgNo))
392         continue;
393 
394       HasChanged = ChangeStatus::CHANGED;
395       bookkeeping(MP, Attr);
396     }
397   }
398 
399   if (HasChanged == ChangeStatus::UNCHANGED)
400     return HasChanged;
401 
402   switch (MP) {
403   case MP_ARGUMENT:
404   case MP_FUNCTION:
405   case MP_RETURNED:
406     ScopeFn.setAttributes(Attrs);
407     break;
408   case MP_CALL_SITE_ARGUMENT:
409     CallSite(&getAnchoredValue()).setAttributes(Attrs);
410   }
411 
412   return HasChanged;
413 }
414 
415 Function &AbstractAttribute::getAnchorScope() {
416   Value &V = getAnchoredValue();
417   if (isa<Function>(V))
418     return cast<Function>(V);
419   if (isa<Argument>(V))
420     return *cast<Argument>(V).getParent();
421   if (isa<Instruction>(V))
422     return *cast<Instruction>(V).getFunction();
423   llvm_unreachable("No scope for anchored value found!");
424 }
425 
426 const Function &AbstractAttribute::getAnchorScope() const {
427   return const_cast<AbstractAttribute *>(this)->getAnchorScope();
428 }
429 
430 // Helper function that returns argument index of value.
431 // If the value is not an argument, this returns -1.
432 static int getArgNo(Value &V) {
433   if (auto *Arg = dyn_cast<Argument>(&V))
434     return Arg->getArgNo();
435   return -1;
436 }
437 
438 /// -----------------------NoUnwind Function Attribute--------------------------
439 
440 struct AANoUnwindFunction : AANoUnwind, BooleanState {
441 
442   AANoUnwindFunction(Function &F, InformationCache &InfoCache)
443       : AANoUnwind(F, InfoCache) {}
444 
445   /// See AbstractAttribute::getState()
446   /// {
447   AbstractState &getState() override { return *this; }
448   const AbstractState &getState() const override { return *this; }
449   /// }
450 
451   /// See AbstractAttribute::getManifestPosition().
452   ManifestPosition getManifestPosition() const override { return MP_FUNCTION; }
453 
454   const std::string getAsStr() const override {
455     return getAssumed() ? "nounwind" : "may-unwind";
456   }
457 
458   /// See AbstractAttribute::updateImpl(...).
459   ChangeStatus updateImpl(Attributor &A) override;
460 
461   /// See AANoUnwind::isAssumedNoUnwind().
462   bool isAssumedNoUnwind() const override { return getAssumed(); }
463 
464   /// See AANoUnwind::isKnownNoUnwind().
465   bool isKnownNoUnwind() const override { return getKnown(); }
466 };
467 
468 ChangeStatus AANoUnwindFunction::updateImpl(Attributor &A) {
469   Function &F = getAnchorScope();
470 
471   // The map from instruction opcodes to those instructions in the function.
472   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
473   auto Opcodes = {
474       (unsigned)Instruction::Invoke,      (unsigned)Instruction::CallBr,
475       (unsigned)Instruction::Call,        (unsigned)Instruction::CleanupRet,
476       (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume};
477 
478   for (unsigned Opcode : Opcodes) {
479     for (Instruction *I : OpcodeInstMap[Opcode]) {
480       if (!I->mayThrow())
481         continue;
482 
483       auto *NoUnwindAA = A.getAAFor<AANoUnwind>(*this, *I);
484 
485       if (!NoUnwindAA || !NoUnwindAA->isAssumedNoUnwind()) {
486         indicatePessimisticFixpoint();
487         return ChangeStatus::CHANGED;
488       }
489     }
490   }
491   return ChangeStatus::UNCHANGED;
492 }
493 
494 /// --------------------- Function Return Values -------------------------------
495 
496 /// "Attribute" that collects all potential returned values and the return
497 /// instructions that they arise from.
498 ///
499 /// If there is a unique returned value R, the manifest method will:
500 ///   - mark R with the "returned" attribute, if R is an argument.
501 class AAReturnedValuesImpl final : public AAReturnedValues, AbstractState {
502 
503   /// Mapping of values potentially returned by the associated function to the
504   /// return instructions that might return them.
505   DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> ReturnedValues;
506 
507   /// State flags
508   ///
509   ///{
510   bool IsFixed;
511   bool IsValidState;
512   bool HasOverdefinedReturnedCalls;
513   ///}
514 
515   /// Collect values that could become \p V in the set \p Values, each mapped to
516   /// \p ReturnInsts.
517   void collectValuesRecursively(
518       Attributor &A, Value *V, SmallPtrSetImpl<ReturnInst *> &ReturnInsts,
519       DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> &Values) {
520 
521     visitValueCB_t<bool> VisitValueCB = [&](Value *Val, bool &) {
522       assert(!isa<Instruction>(Val) ||
523              &getAnchorScope() == cast<Instruction>(Val)->getFunction());
524       Values[Val].insert(ReturnInsts.begin(), ReturnInsts.end());
525     };
526 
527     bool UnusedBool;
528     bool Success = genericValueTraversal(V, UnusedBool, VisitValueCB);
529 
530     // If we did abort the above traversal we haven't see all the values.
531     // Consequently, we cannot know if the information we would derive is
532     // accurate so we give up early.
533     if (!Success)
534       indicatePessimisticFixpoint();
535   }
536 
537 public:
538   /// See AbstractAttribute::AbstractAttribute(...).
539   AAReturnedValuesImpl(Function &F, InformationCache &InfoCache)
540       : AAReturnedValues(F, InfoCache) {
541     // We do not have an associated argument yet.
542     AssociatedVal = nullptr;
543   }
544 
545   /// See AbstractAttribute::initialize(...).
546   void initialize(Attributor &A) override {
547     // Reset the state.
548     AssociatedVal = nullptr;
549     IsFixed = false;
550     IsValidState = true;
551     HasOverdefinedReturnedCalls = false;
552     ReturnedValues.clear();
553 
554     Function &F = cast<Function>(getAnchoredValue());
555 
556     // The map from instruction opcodes to those instructions in the function.
557     auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
558 
559     // Look through all arguments, if one is marked as returned we are done.
560     for (Argument &Arg : F.args()) {
561       if (Arg.hasReturnedAttr()) {
562 
563         auto &ReturnInstSet = ReturnedValues[&Arg];
564         for (Instruction *RI : OpcodeInstMap[Instruction::Ret])
565           ReturnInstSet.insert(cast<ReturnInst>(RI));
566 
567         indicateOptimisticFixpoint();
568         return;
569       }
570     }
571 
572     // If no argument was marked as returned we look at all return instructions
573     // and collect potentially returned values.
574     for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) {
575       SmallPtrSet<ReturnInst *, 1> RISet({cast<ReturnInst>(RI)});
576       collectValuesRecursively(A, cast<ReturnInst>(RI)->getReturnValue(), RISet,
577                                ReturnedValues);
578     }
579   }
580 
581   /// See AbstractAttribute::manifest(...).
582   ChangeStatus manifest(Attributor &A) override;
583 
584   /// See AbstractAttribute::getState(...).
585   AbstractState &getState() override { return *this; }
586 
587   /// See AbstractAttribute::getState(...).
588   const AbstractState &getState() const override { return *this; }
589 
590   /// See AbstractAttribute::getManifestPosition().
591   ManifestPosition getManifestPosition() const override { return MP_ARGUMENT; }
592 
593   /// See AbstractAttribute::updateImpl(Attributor &A).
594   ChangeStatus updateImpl(Attributor &A) override;
595 
596   /// Return the number of potential return values, -1 if unknown.
597   size_t getNumReturnValues() const {
598     return isValidState() ? ReturnedValues.size() : -1;
599   }
600 
601   /// Return an assumed unique return value if a single candidate is found. If
602   /// there cannot be one, return a nullptr. If it is not clear yet, return the
603   /// Optional::NoneType.
604   Optional<Value *> getAssumedUniqueReturnValue() const;
605 
606   /// See AbstractState::checkForallReturnedValues(...).
607   bool
608   checkForallReturnedValues(std::function<bool(Value &)> &Pred) const override;
609 
610   /// Pretty print the attribute similar to the IR representation.
611   const std::string getAsStr() const override;
612 
613   /// See AbstractState::isAtFixpoint().
614   bool isAtFixpoint() const override { return IsFixed; }
615 
616   /// See AbstractState::isValidState().
617   bool isValidState() const override { return IsValidState; }
618 
619   /// See AbstractState::indicateOptimisticFixpoint(...).
620   void indicateOptimisticFixpoint() override {
621     IsFixed = true;
622     IsValidState &= true;
623   }
624   void indicatePessimisticFixpoint() override {
625     IsFixed = true;
626     IsValidState = false;
627   }
628 };
629 
630 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) {
631   ChangeStatus Changed = ChangeStatus::UNCHANGED;
632 
633   // Bookkeeping.
634   assert(isValidState());
635   NumFnKnownReturns++;
636 
637   // Check if we have an assumed unique return value that we could manifest.
638   Optional<Value *> UniqueRV = getAssumedUniqueReturnValue();
639 
640   if (!UniqueRV.hasValue() || !UniqueRV.getValue())
641     return Changed;
642 
643   // Bookkeeping.
644   NumFnUniqueReturned++;
645 
646   // If the assumed unique return value is an argument, annotate it.
647   if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) {
648     AssociatedVal = UniqueRVArg;
649     Changed = AbstractAttribute::manifest(A) | Changed;
650   }
651 
652   return Changed;
653 }
654 
655 const std::string AAReturnedValuesImpl::getAsStr() const {
656   return (isAtFixpoint() ? "returns(#" : "may-return(#") +
657          (isValidState() ? std::to_string(getNumReturnValues()) : "?") + ")";
658 }
659 
660 Optional<Value *> AAReturnedValuesImpl::getAssumedUniqueReturnValue() const {
661   // If checkForallReturnedValues provides a unique value, ignoring potential
662   // undef values that can also be present, it is assumed to be the actual
663   // return value and forwarded to the caller of this method. If there are
664   // multiple, a nullptr is returned indicating there cannot be a unique
665   // returned value.
666   Optional<Value *> UniqueRV;
667 
668   std::function<bool(Value &)> Pred = [&](Value &RV) -> bool {
669     // If we found a second returned value and neither the current nor the saved
670     // one is an undef, there is no unique returned value. Undefs are special
671     // since we can pretend they have any value.
672     if (UniqueRV.hasValue() && UniqueRV != &RV &&
673         !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) {
674       UniqueRV = nullptr;
675       return false;
676     }
677 
678     // Do not overwrite a value with an undef.
679     if (!UniqueRV.hasValue() || !isa<UndefValue>(RV))
680       UniqueRV = &RV;
681 
682     return true;
683   };
684 
685   if (!checkForallReturnedValues(Pred))
686     UniqueRV = nullptr;
687 
688   return UniqueRV;
689 }
690 
691 bool AAReturnedValuesImpl::checkForallReturnedValues(
692     std::function<bool(Value &)> &Pred) const {
693   if (!isValidState())
694     return false;
695 
696   // Check all returned values but ignore call sites as long as we have not
697   // encountered an overdefined one during an update.
698   for (auto &It : ReturnedValues) {
699     Value *RV = It.first;
700 
701     ImmutableCallSite ICS(RV);
702     if (ICS && !HasOverdefinedReturnedCalls)
703       continue;
704 
705     if (!Pred(*RV))
706       return false;
707   }
708 
709   return true;
710 }
711 
712 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) {
713 
714   // Check if we know of any values returned by the associated function,
715   // if not, we are done.
716   if (getNumReturnValues() == 0) {
717     indicateOptimisticFixpoint();
718     return ChangeStatus::UNCHANGED;
719   }
720 
721   // Check if any of the returned values is a call site we can refine.
722   decltype(ReturnedValues) AddRVs;
723   bool HasCallSite = false;
724 
725   // Look at all returned call sites.
726   for (auto &It : ReturnedValues) {
727     SmallPtrSet<ReturnInst *, 2> &ReturnInsts = It.second;
728     Value *RV = It.first;
729     LLVM_DEBUG(dbgs() << "[AAReturnedValues] Potentially returned value " << *RV
730                       << "\n");
731 
732     // Only call sites can change during an update, ignore the rest.
733     CallSite RetCS(RV);
734     if (!RetCS)
735       continue;
736 
737     // For now, any call site we see will prevent us from directly fixing the
738     // state. However, if the information on the callees is fixed, the call
739     // sites will be removed and we will fix the information for this state.
740     HasCallSite = true;
741 
742     // Try to find a assumed unique return value for the called function.
743     auto *RetCSAA = A.getAAFor<AAReturnedValuesImpl>(*this, *RV);
744     if (!RetCSAA) {
745       HasOverdefinedReturnedCalls = true;
746       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned call site (" << *RV
747                         << ") with " << (RetCSAA ? "invalid" : "no")
748                         << " associated state\n");
749       continue;
750     }
751 
752     // Try to find a assumed unique return value for the called function.
753     Optional<Value *> AssumedUniqueRV = RetCSAA->getAssumedUniqueReturnValue();
754 
755     // If no assumed unique return value was found due to the lack of
756     // candidates, we may need to resolve more calls (through more update
757     // iterations) or the called function will not return. Either way, we simply
758     // stick with the call sites as return values. Because there were not
759     // multiple possibilities, we do not treat it as overdefined.
760     if (!AssumedUniqueRV.hasValue())
761       continue;
762 
763     // If multiple, non-refinable values were found, there cannot be a unique
764     // return value for the called function. The returned call is overdefined!
765     if (!AssumedUniqueRV.getValue()) {
766       HasOverdefinedReturnedCalls = true;
767       LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned call site has multiple "
768                            "potentially returned values\n");
769       continue;
770     }
771 
772     LLVM_DEBUG({
773       bool UniqueRVIsKnown = RetCSAA->isAtFixpoint();
774       dbgs() << "[AAReturnedValues] Returned call site "
775              << (UniqueRVIsKnown ? "known" : "assumed")
776              << " unique return value: " << *AssumedUniqueRV << "\n";
777     });
778 
779     // The assumed unique return value.
780     Value *AssumedRetVal = AssumedUniqueRV.getValue();
781 
782     // If the assumed unique return value is an argument, lookup the matching
783     // call site operand and recursively collect new returned values.
784     // If it is not an argument, it is just put into the set of returned values
785     // as we would have already looked through casts, phis, and similar values.
786     if (Argument *AssumedRetArg = dyn_cast<Argument>(AssumedRetVal))
787       collectValuesRecursively(A,
788                                RetCS.getArgOperand(AssumedRetArg->getArgNo()),
789                                ReturnInsts, AddRVs);
790     else
791       AddRVs[AssumedRetVal].insert(ReturnInsts.begin(), ReturnInsts.end());
792   }
793 
794   // Keep track of any change to trigger updates on dependent attributes.
795   ChangeStatus Changed = ChangeStatus::UNCHANGED;
796 
797   for (auto &It : AddRVs) {
798     assert(!It.second.empty() && "Entry does not add anything.");
799     auto &ReturnInsts = ReturnedValues[It.first];
800     for (ReturnInst *RI : It.second)
801       if (ReturnInsts.insert(RI).second) {
802         LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value "
803                           << *It.first << " => " << *RI << "\n");
804         Changed = ChangeStatus::CHANGED;
805       }
806   }
807 
808   // If there is no call site in the returned values we are done.
809   if (!HasCallSite) {
810     indicateOptimisticFixpoint();
811     return ChangeStatus::CHANGED;
812   }
813 
814   return Changed;
815 }
816 
817 /// ------------------------ NoSync Function Attribute -------------------------
818 
819 struct AANoSyncFunction : AANoSync, BooleanState {
820 
821   AANoSyncFunction(Function &F, InformationCache &InfoCache)
822       : AANoSync(F, InfoCache) {}
823 
824   /// See AbstractAttribute::getState()
825   /// {
826   AbstractState &getState() override { return *this; }
827   const AbstractState &getState() const override { return *this; }
828   /// }
829 
830   /// See AbstractAttribute::getManifestPosition().
831   ManifestPosition getManifestPosition() const override { return MP_FUNCTION; }
832 
833   const std::string getAsStr() const override {
834     return getAssumed() ? "nosync" : "may-sync";
835   }
836 
837   /// See AbstractAttribute::updateImpl(...).
838   ChangeStatus updateImpl(Attributor &A) override;
839 
840   /// See AANoSync::isAssumedNoSync()
841   bool isAssumedNoSync() const override { return getAssumed(); }
842 
843   /// See AANoSync::isKnownNoSync()
844   bool isKnownNoSync() const override { return getKnown(); }
845 
846   /// Helper function used to determine whether an instruction is non-relaxed
847   /// atomic. In other words, if an atomic instruction does not have unordered
848   /// or monotonic ordering
849   static bool isNonRelaxedAtomic(Instruction *I);
850 
851   /// Helper function used to determine whether an instruction is volatile.
852   static bool isVolatile(Instruction *I);
853 
854   /// Helper function uset to check if intrinsic is volatile (memcpy, memmove,
855   /// memset).
856   static bool isNoSyncIntrinsic(Instruction *I);
857 };
858 
859 bool AANoSyncFunction::isNonRelaxedAtomic(Instruction *I) {
860   if (!I->isAtomic())
861     return false;
862 
863   AtomicOrdering Ordering;
864   switch (I->getOpcode()) {
865   case Instruction::AtomicRMW:
866     Ordering = cast<AtomicRMWInst>(I)->getOrdering();
867     break;
868   case Instruction::Store:
869     Ordering = cast<StoreInst>(I)->getOrdering();
870     break;
871   case Instruction::Load:
872     Ordering = cast<LoadInst>(I)->getOrdering();
873     break;
874   case Instruction::Fence: {
875     auto *FI = cast<FenceInst>(I);
876     if (FI->getSyncScopeID() == SyncScope::SingleThread)
877       return false;
878     Ordering = FI->getOrdering();
879     break;
880   }
881   case Instruction::AtomicCmpXchg: {
882     AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering();
883     AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering();
884     // Only if both are relaxed, than it can be treated as relaxed.
885     // Otherwise it is non-relaxed.
886     if (Success != AtomicOrdering::Unordered &&
887         Success != AtomicOrdering::Monotonic)
888       return true;
889     if (Failure != AtomicOrdering::Unordered &&
890         Failure != AtomicOrdering::Monotonic)
891       return true;
892     return false;
893   }
894   default:
895     llvm_unreachable(
896         "New atomic operations need to be known in the attributor.");
897   }
898 
899   // Relaxed.
900   if (Ordering == AtomicOrdering::Unordered ||
901       Ordering == AtomicOrdering::Monotonic)
902     return false;
903   return true;
904 }
905 
906 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics.
907 /// FIXME: We should ipmrove the handling of intrinsics.
908 bool AANoSyncFunction::isNoSyncIntrinsic(Instruction *I) {
909   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
910     switch (II->getIntrinsicID()) {
911     /// Element wise atomic memory intrinsics are can only be unordered,
912     /// therefore nosync.
913     case Intrinsic::memset_element_unordered_atomic:
914     case Intrinsic::memmove_element_unordered_atomic:
915     case Intrinsic::memcpy_element_unordered_atomic:
916       return true;
917     case Intrinsic::memset:
918     case Intrinsic::memmove:
919     case Intrinsic::memcpy:
920       if (!cast<MemIntrinsic>(II)->isVolatile())
921         return true;
922       return false;
923     default:
924       return false;
925     }
926   }
927   return false;
928 }
929 
930 bool AANoSyncFunction::isVolatile(Instruction *I) {
931   assert(!ImmutableCallSite(I) && !isa<CallBase>(I) &&
932          "Calls should not be checked here");
933 
934   switch (I->getOpcode()) {
935   case Instruction::AtomicRMW:
936     return cast<AtomicRMWInst>(I)->isVolatile();
937   case Instruction::Store:
938     return cast<StoreInst>(I)->isVolatile();
939   case Instruction::Load:
940     return cast<LoadInst>(I)->isVolatile();
941   case Instruction::AtomicCmpXchg:
942     return cast<AtomicCmpXchgInst>(I)->isVolatile();
943   default:
944     return false;
945   }
946 }
947 
948 ChangeStatus AANoSyncFunction::updateImpl(Attributor &A) {
949   Function &F = getAnchorScope();
950 
951   /// We are looking for volatile instructions or Non-Relaxed atomics.
952   /// FIXME: We should ipmrove the handling of intrinsics.
953   for (Instruction *I : InfoCache.getReadOrWriteInstsForFunction(F)) {
954     ImmutableCallSite ICS(I);
955     auto *NoSyncAA = A.getAAFor<AANoSyncFunction>(*this, *I);
956 
957     if (isa<IntrinsicInst>(I) && isNoSyncIntrinsic(I))
958       continue;
959 
960     if (ICS && (!NoSyncAA || !NoSyncAA->isAssumedNoSync()) &&
961         !ICS.hasFnAttr(Attribute::NoSync)) {
962       indicatePessimisticFixpoint();
963       return ChangeStatus::CHANGED;
964     }
965 
966     if (ICS)
967       continue;
968 
969     if (!isVolatile(I) && !isNonRelaxedAtomic(I))
970       continue;
971 
972     indicatePessimisticFixpoint();
973     return ChangeStatus::CHANGED;
974   }
975 
976   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
977   auto Opcodes = {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
978                   (unsigned)Instruction::Call};
979 
980   for (unsigned Opcode : Opcodes) {
981     for (Instruction *I : OpcodeInstMap[Opcode]) {
982       // At this point we handled all read/write effects and they are all
983       // nosync, so they can be skipped.
984       if (I->mayReadOrWriteMemory())
985         continue;
986 
987       ImmutableCallSite ICS(I);
988 
989       // non-convergent and readnone imply nosync.
990       if (!ICS.isConvergent())
991         continue;
992 
993       indicatePessimisticFixpoint();
994       return ChangeStatus::CHANGED;
995     }
996   }
997 
998   return ChangeStatus::UNCHANGED;
999 }
1000 
1001 /// ------------------------ No-Free Attributes ----------------------------
1002 
1003 struct AANoFreeFunction : AbstractAttribute, BooleanState {
1004 
1005   /// See AbstractAttribute::AbstractAttribute(...).
1006   AANoFreeFunction(Function &F, InformationCache &InfoCache)
1007       : AbstractAttribute(F, InfoCache) {}
1008 
1009   /// See AbstractAttribute::getState()
1010   ///{
1011   AbstractState &getState() override { return *this; }
1012   const AbstractState &getState() const override { return *this; }
1013   ///}
1014 
1015   /// See AbstractAttribute::getManifestPosition().
1016   ManifestPosition getManifestPosition() const override { return MP_FUNCTION; }
1017 
1018   /// See AbstractAttribute::getAsStr().
1019   const std::string getAsStr() const override {
1020     return getAssumed() ? "nofree" : "may-free";
1021   }
1022 
1023   /// See AbstractAttribute::updateImpl(...).
1024   ChangeStatus updateImpl(Attributor &A) override;
1025 
1026   /// See AbstractAttribute::getAttrKind().
1027   Attribute::AttrKind getAttrKind() const override { return ID; }
1028 
1029   /// Return true if "nofree" is assumed.
1030   bool isAssumedNoFree() const { return getAssumed(); }
1031 
1032   /// Return true if "nofree" is known.
1033   bool isKnownNoFree() const { return getKnown(); }
1034 
1035   /// The identifier used by the Attributor for this class of attributes.
1036   static constexpr Attribute::AttrKind ID = Attribute::NoFree;
1037 };
1038 
1039 ChangeStatus AANoFreeFunction::updateImpl(Attributor &A) {
1040   Function &F = getAnchorScope();
1041 
1042   // The map from instruction opcodes to those instructions in the function.
1043   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
1044 
1045   for (unsigned Opcode :
1046        {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
1047         (unsigned)Instruction::Call}) {
1048     for (Instruction *I : OpcodeInstMap[Opcode]) {
1049 
1050       auto ICS = ImmutableCallSite(I);
1051       auto *NoFreeAA = A.getAAFor<AANoFreeFunction>(*this, *I);
1052 
1053       if ((!NoFreeAA || !NoFreeAA->isAssumedNoFree()) &&
1054           !ICS.hasFnAttr(Attribute::NoFree)) {
1055         indicatePessimisticFixpoint();
1056         return ChangeStatus::CHANGED;
1057       }
1058     }
1059   }
1060   return ChangeStatus::UNCHANGED;
1061 }
1062 
1063 /// ------------------------ NonNull Argument Attribute ------------------------
1064 struct AANonNullImpl : AANonNull, BooleanState {
1065 
1066   AANonNullImpl(Value &V, InformationCache &InfoCache)
1067       : AANonNull(V, InfoCache) {}
1068 
1069   AANonNullImpl(Value *AssociatedVal, Value &AnchoredValue,
1070                 InformationCache &InfoCache)
1071       : AANonNull(AssociatedVal, AnchoredValue, InfoCache) {}
1072 
1073   /// See AbstractAttribute::getState()
1074   /// {
1075   AbstractState &getState() override { return *this; }
1076   const AbstractState &getState() const override { return *this; }
1077   /// }
1078 
1079   /// See AbstractAttribute::getAsStr().
1080   const std::string getAsStr() const override {
1081     return getAssumed() ? "nonnull" : "may-null";
1082   }
1083 
1084   /// See AANonNull::isAssumedNonNull().
1085   bool isAssumedNonNull() const override { return getAssumed(); }
1086 
1087   /// See AANonNull::isKnownNonNull().
1088   bool isKnownNonNull() const override { return getKnown(); }
1089 
1090   /// Generate a predicate that checks if a given value is assumed nonnull.
1091   /// The generated function returns true if a value satisfies any of
1092   /// following conditions.
1093   /// (i) A value is known nonZero(=nonnull).
1094   /// (ii) A value is associated with AANonNull and its isAssumedNonNull() is
1095   /// true.
1096   std::function<bool(Value &)> generatePredicate(Attributor &);
1097 };
1098 
1099 std::function<bool(Value &)> AANonNullImpl::generatePredicate(Attributor &A) {
1100   // FIXME: The `AAReturnedValues` should provide the predicate with the
1101   // `ReturnInst` vector as well such that we can use the control flow sensitive
1102   // version of `isKnownNonZero`. This should fix `test11` in
1103   // `test/Transforms/FunctionAttrs/nonnull.ll`
1104 
1105   std::function<bool(Value &)> Pred = [&](Value &RV) -> bool {
1106     if (isKnownNonZero(&RV, getAnchorScope().getParent()->getDataLayout()))
1107       return true;
1108 
1109     auto *NonNullAA = A.getAAFor<AANonNull>(*this, RV);
1110 
1111     ImmutableCallSite ICS(&RV);
1112 
1113     if ((!NonNullAA || !NonNullAA->isAssumedNonNull()) &&
1114         (!ICS || !ICS.hasRetAttr(Attribute::NonNull)))
1115       return false;
1116 
1117     return true;
1118   };
1119 
1120   return Pred;
1121 }
1122 
1123 /// NonNull attribute for function return value.
1124 struct AANonNullReturned : AANonNullImpl {
1125 
1126   AANonNullReturned(Function &F, InformationCache &InfoCache)
1127       : AANonNullImpl(F, InfoCache) {}
1128 
1129   /// See AbstractAttribute::getManifestPosition().
1130   ManifestPosition getManifestPosition() const override { return MP_RETURNED; }
1131 
1132   /// See AbstractAttriubute::initialize(...).
1133   void initialize(Attributor &A) override {
1134     Function &F = getAnchorScope();
1135 
1136     // Already nonnull.
1137     if (F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
1138                                        Attribute::NonNull) ||
1139         F.getAttributes().hasAttribute(AttributeList::ReturnIndex,
1140                                        Attribute::Dereferenceable))
1141       indicateOptimisticFixpoint();
1142   }
1143 
1144   /// See AbstractAttribute::updateImpl(...).
1145   ChangeStatus updateImpl(Attributor &A) override;
1146 };
1147 
1148 ChangeStatus AANonNullReturned::updateImpl(Attributor &A) {
1149   Function &F = getAnchorScope();
1150 
1151   auto *AARetVal = A.getAAFor<AAReturnedValues>(*this, F);
1152   if (!AARetVal) {
1153     indicatePessimisticFixpoint();
1154     return ChangeStatus::CHANGED;
1155   }
1156 
1157   std::function<bool(Value &)> Pred = this->generatePredicate(A);
1158   if (!AARetVal->checkForallReturnedValues(Pred)) {
1159     indicatePessimisticFixpoint();
1160     return ChangeStatus::CHANGED;
1161   }
1162   return ChangeStatus::UNCHANGED;
1163 }
1164 
1165 /// NonNull attribute for function argument.
1166 struct AANonNullArgument : AANonNullImpl {
1167 
1168   AANonNullArgument(Argument &A, InformationCache &InfoCache)
1169       : AANonNullImpl(A, InfoCache) {}
1170 
1171   /// See AbstractAttribute::getManifestPosition().
1172   ManifestPosition getManifestPosition() const override { return MP_ARGUMENT; }
1173 
1174   /// See AbstractAttriubute::initialize(...).
1175   void initialize(Attributor &A) override {
1176     Argument *Arg = cast<Argument>(getAssociatedValue());
1177     if (Arg->hasNonNullAttr())
1178       indicateOptimisticFixpoint();
1179   }
1180 
1181   /// See AbstractAttribute::updateImpl(...).
1182   ChangeStatus updateImpl(Attributor &A) override;
1183 };
1184 
1185 /// NonNull attribute for a call site argument.
1186 struct AANonNullCallSiteArgument : AANonNullImpl {
1187 
1188   /// See AANonNullImpl::AANonNullImpl(...).
1189   AANonNullCallSiteArgument(CallSite CS, unsigned ArgNo,
1190                             InformationCache &InfoCache)
1191       : AANonNullImpl(CS.getArgOperand(ArgNo), *CS.getInstruction(), InfoCache),
1192         ArgNo(ArgNo) {}
1193 
1194   /// See AbstractAttribute::initialize(...).
1195   void initialize(Attributor &A) override {
1196     CallSite CS(&getAnchoredValue());
1197     if (CS.paramHasAttr(ArgNo, getAttrKind()) ||
1198         CS.paramHasAttr(ArgNo, Attribute::Dereferenceable) ||
1199         isKnownNonZero(getAssociatedValue(),
1200                        getAnchorScope().getParent()->getDataLayout()))
1201       indicateOptimisticFixpoint();
1202   }
1203 
1204   /// See AbstractAttribute::updateImpl(Attributor &A).
1205   ChangeStatus updateImpl(Attributor &A) override;
1206 
1207   /// See AbstractAttribute::getManifestPosition().
1208   ManifestPosition getManifestPosition() const override {
1209     return MP_CALL_SITE_ARGUMENT;
1210   };
1211 
1212   // Return argument index of associated value.
1213   int getArgNo() const { return ArgNo; }
1214 
1215 private:
1216   unsigned ArgNo;
1217 };
1218 ChangeStatus AANonNullArgument::updateImpl(Attributor &A) {
1219   Function &F = getAnchorScope();
1220   Argument &Arg = cast<Argument>(getAnchoredValue());
1221 
1222   unsigned ArgNo = Arg.getArgNo();
1223 
1224   // Callback function
1225   std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) {
1226     assert(CS && "Sanity check: Call site was not initialized properly!");
1227 
1228     auto *NonNullAA = A.getAAFor<AANonNull>(*this, *CS.getInstruction(), ArgNo);
1229 
1230     // Check that NonNullAA is AANonNullCallSiteArgument.
1231     if (NonNullAA) {
1232       ImmutableCallSite ICS(&NonNullAA->getAnchoredValue());
1233       if (ICS && CS.getInstruction() == ICS.getInstruction())
1234         return NonNullAA->isAssumedNonNull();
1235       return false;
1236     }
1237 
1238     if (CS.paramHasAttr(ArgNo, Attribute::NonNull))
1239       return true;
1240 
1241     Value *V = CS.getArgOperand(ArgNo);
1242     if (isKnownNonZero(V, getAnchorScope().getParent()->getDataLayout()))
1243       return true;
1244 
1245     return false;
1246   };
1247   if (!A.checkForAllCallSites(F, CallSiteCheck, true)) {
1248     indicatePessimisticFixpoint();
1249     return ChangeStatus::CHANGED;
1250   }
1251   return ChangeStatus::UNCHANGED;
1252 }
1253 
1254 ChangeStatus AANonNullCallSiteArgument::updateImpl(Attributor &A) {
1255   // NOTE: Never look at the argument of the callee in this method.
1256   //       If we do this, "nonnull" is always deduced because of the assumption.
1257 
1258   Value &V = *getAssociatedValue();
1259 
1260   auto *NonNullAA = A.getAAFor<AANonNull>(*this, V);
1261 
1262   if (!NonNullAA || !NonNullAA->isAssumedNonNull()) {
1263     indicatePessimisticFixpoint();
1264     return ChangeStatus::CHANGED;
1265   }
1266 
1267   return ChangeStatus::UNCHANGED;
1268 }
1269 
1270 /// ------------------------ Will-Return Attributes ----------------------------
1271 
1272 struct AAWillReturnImpl : public AAWillReturn, BooleanState {
1273 
1274   /// See AbstractAttribute::AbstractAttribute(...).
1275   AAWillReturnImpl(Function &F, InformationCache &InfoCache)
1276       : AAWillReturn(F, InfoCache) {}
1277 
1278   /// See AAWillReturn::isKnownWillReturn().
1279   bool isKnownWillReturn() const override { return getKnown(); }
1280 
1281   /// See AAWillReturn::isAssumedWillReturn().
1282   bool isAssumedWillReturn() const override { return getAssumed(); }
1283 
1284   /// See AbstractAttribute::getState(...).
1285   AbstractState &getState() override { return *this; }
1286 
1287   /// See AbstractAttribute::getState(...).
1288   const AbstractState &getState() const override { return *this; }
1289 
1290   /// See AbstractAttribute::getAsStr()
1291   const std::string getAsStr() const override {
1292     return getAssumed() ? "willreturn" : "may-noreturn";
1293   }
1294 };
1295 
1296 struct AAWillReturnFunction final : AAWillReturnImpl {
1297 
1298   /// See AbstractAttribute::AbstractAttribute(...).
1299   AAWillReturnFunction(Function &F, InformationCache &InfoCache)
1300       : AAWillReturnImpl(F, InfoCache) {}
1301 
1302   /// See AbstractAttribute::getManifestPosition().
1303   ManifestPosition getManifestPosition() const override { return MP_FUNCTION; }
1304 
1305   /// See AbstractAttribute::initialize(...).
1306   void initialize(Attributor &A) override;
1307 
1308   /// See AbstractAttribute::updateImpl(...).
1309   ChangeStatus updateImpl(Attributor &A) override;
1310 };
1311 
1312 // Helper function that checks whether a function has any cycle.
1313 // TODO: Replace with more efficent code
1314 bool containsCycle(Function &F) {
1315   SmallPtrSet<BasicBlock *, 32> Visited;
1316 
1317   // Traverse BB by dfs and check whether successor is already visited.
1318   for (BasicBlock *BB : depth_first(&F)) {
1319     Visited.insert(BB);
1320     for (auto *SuccBB : successors(BB)) {
1321       if (Visited.count(SuccBB))
1322         return true;
1323     }
1324   }
1325   return false;
1326 }
1327 
1328 // Helper function that checks the function have a loop which might become an
1329 // endless loop
1330 // FIXME: Any cycle is regarded as endless loop for now.
1331 //        We have to allow some patterns.
1332 bool containsPossiblyEndlessLoop(Function &F) { return containsCycle(F); }
1333 
1334 void AAWillReturnFunction::initialize(Attributor &A) {
1335   Function &F = getAnchorScope();
1336 
1337   if (containsPossiblyEndlessLoop(F))
1338     indicatePessimisticFixpoint();
1339 }
1340 
1341 ChangeStatus AAWillReturnFunction::updateImpl(Attributor &A) {
1342   Function &F = getAnchorScope();
1343 
1344   // The map from instruction opcodes to those instructions in the function.
1345   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
1346 
1347   for (unsigned Opcode :
1348        {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
1349         (unsigned)Instruction::Call}) {
1350     for (Instruction *I : OpcodeInstMap[Opcode]) {
1351       auto ICS = ImmutableCallSite(I);
1352 
1353       if (ICS.hasFnAttr(Attribute::WillReturn))
1354         continue;
1355 
1356       auto *WillReturnAA = A.getAAFor<AAWillReturn>(*this, *I);
1357       if (!WillReturnAA || !WillReturnAA->isAssumedWillReturn()) {
1358         indicatePessimisticFixpoint();
1359         return ChangeStatus::CHANGED;
1360       }
1361 
1362       auto *NoRecurseAA = A.getAAFor<AANoRecurse>(*this, *I);
1363 
1364       // FIXME: (i) Prohibit any recursion for now.
1365       //        (ii) AANoRecurse isn't implemented yet so currently any call is
1366       //        regarded as having recursion.
1367       //       Code below should be
1368       //       if ((!NoRecurseAA || !NoRecurseAA->isAssumedNoRecurse()) &&
1369       if (!NoRecurseAA && !ICS.hasFnAttr(Attribute::NoRecurse)) {
1370         indicatePessimisticFixpoint();
1371         return ChangeStatus::CHANGED;
1372       }
1373     }
1374   }
1375 
1376   return ChangeStatus::UNCHANGED;
1377 }
1378 
1379 /// ------------------------ NoAlias Argument Attribute ------------------------
1380 
1381 struct AANoAliasImpl : AANoAlias, BooleanState {
1382 
1383   AANoAliasImpl(Value &V, InformationCache &InfoCache)
1384       : AANoAlias(V, InfoCache) {}
1385 
1386   /// See AbstractAttribute::getState()
1387   /// {
1388   AbstractState &getState() override { return *this; }
1389   const AbstractState &getState() const override { return *this; }
1390   /// }
1391 
1392   const std::string getAsStr() const override {
1393     return getAssumed() ? "noalias" : "may-alias";
1394   }
1395 
1396   /// See AANoAlias::isAssumedNoAlias().
1397   bool isAssumedNoAlias() const override { return getAssumed(); }
1398 
1399   /// See AANoAlias::isKnowndNoAlias().
1400   bool isKnownNoAlias() const override { return getKnown(); }
1401 };
1402 
1403 /// NoAlias attribute for function return value.
1404 struct AANoAliasReturned : AANoAliasImpl {
1405 
1406   AANoAliasReturned(Function &F, InformationCache &InfoCache)
1407       : AANoAliasImpl(F, InfoCache) {}
1408 
1409   /// See AbstractAttribute::getManifestPosition().
1410   virtual ManifestPosition getManifestPosition() const override {
1411     return MP_RETURNED;
1412   }
1413 
1414   /// See AbstractAttriubute::initialize(...).
1415   void initialize(Attributor &A) override {
1416     Function &F = getAnchorScope();
1417 
1418     // Already noalias.
1419     if (F.returnDoesNotAlias()) {
1420       indicateOptimisticFixpoint();
1421       return;
1422     }
1423   }
1424 
1425   /// See AbstractAttribute::updateImpl(...).
1426   virtual ChangeStatus updateImpl(Attributor &A) override;
1427 };
1428 
1429 ChangeStatus AANoAliasReturned::updateImpl(Attributor &A) {
1430   Function &F = getAnchorScope();
1431 
1432   auto *AARetValImpl = A.getAAFor<AAReturnedValuesImpl>(*this, F);
1433   if (!AARetValImpl) {
1434     indicatePessimisticFixpoint();
1435     return ChangeStatus::CHANGED;
1436   }
1437 
1438   std::function<bool(Value &)> Pred = [&](Value &RV) -> bool {
1439     if (Constant *C = dyn_cast<Constant>(&RV))
1440       if (C->isNullValue() || isa<UndefValue>(C))
1441         return true;
1442 
1443     /// For now, we can only deduce noalias if we have call sites.
1444     /// FIXME: add more support.
1445     ImmutableCallSite ICS(&RV);
1446     if (!ICS)
1447       return false;
1448 
1449     auto *NoAliasAA = A.getAAFor<AANoAlias>(*this, RV);
1450 
1451     if (!ICS.returnDoesNotAlias() &&
1452         (!NoAliasAA || !NoAliasAA->isAssumedNoAlias()))
1453       return false;
1454 
1455     /// FIXME: We can improve capture check in two ways:
1456     /// 1. Use the AANoCapture facilities.
1457     /// 2. Use the location of return insts for escape queries.
1458     if (PointerMayBeCaptured(&RV, /* ReturnCaptures */ false,
1459                              /* StoreCaptures */ true))
1460       return false;
1461 
1462     return true;
1463   };
1464 
1465   if (!AARetValImpl->checkForallReturnedValues(Pred)) {
1466     indicatePessimisticFixpoint();
1467     return ChangeStatus::CHANGED;
1468   }
1469 
1470   return ChangeStatus::UNCHANGED;
1471 }
1472 
1473 /// -------------------AAIsDead Function Attribute-----------------------
1474 
1475 struct AAIsDeadFunction : AAIsDead, BooleanState {
1476 
1477   AAIsDeadFunction(Function &F, InformationCache &InfoCache)
1478       : AAIsDead(F, InfoCache) {}
1479 
1480   /// See AbstractAttribute::getState()
1481   /// {
1482   AbstractState &getState() override { return *this; }
1483   const AbstractState &getState() const override { return *this; }
1484   /// }
1485 
1486   /// See AbstractAttribute::getManifestPosition().
1487   ManifestPosition getManifestPosition() const override { return MP_FUNCTION; }
1488 
1489   void initialize(Attributor &A) override {
1490     Function &F = getAnchorScope();
1491 
1492     ToBeExploredPaths.insert(&(F.getEntryBlock().front()));
1493     AssumedLiveBlocks.insert(&(F.getEntryBlock()));
1494     for (size_t i = 0; i < ToBeExploredPaths.size(); ++i)
1495       explorePath(A, ToBeExploredPaths[i]);
1496   }
1497 
1498   /// Explores new instructions starting from \p I. If instruction is dead, stop
1499   /// and return true if it discovered a new instruction.
1500   bool explorePath(Attributor &A, Instruction *I);
1501 
1502   const std::string getAsStr() const override {
1503     return "LiveBBs(" + std::to_string(AssumedLiveBlocks.size()) + "/" +
1504            std::to_string(getAnchorScope().size()) + ")";
1505   }
1506 
1507   /// See AbstractAttribute::manifest(...).
1508   ChangeStatus manifest(Attributor &A) override {
1509     assert(getState().isValidState() &&
1510            "Attempted to manifest an invalid state!");
1511 
1512     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1513 
1514     for (Instruction *I : NoReturnCalls) {
1515       BasicBlock *BB = I->getParent();
1516 
1517       /// Invoke is replaced with a call and unreachable is placed after it.
1518       if (auto *II = dyn_cast<InvokeInst>(I)) {
1519         changeToCall(II);
1520         changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false);
1521         LLVM_DEBUG(dbgs() << "[AAIsDead] Replaced invoke with call inst\n");
1522         continue;
1523       }
1524 
1525       SplitBlock(BB, I->getNextNode());
1526       changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false);
1527       HasChanged = ChangeStatus::CHANGED;
1528     }
1529 
1530     return HasChanged;
1531   }
1532 
1533   /// See AbstractAttribute::updateImpl(...).
1534   ChangeStatus updateImpl(Attributor &A) override;
1535 
1536   /// See AAIsDead::isAssumedDead().
1537   bool isAssumedDead(BasicBlock *BB) const override {
1538     if (!getAssumed())
1539       return false;
1540     return !AssumedLiveBlocks.count(BB);
1541   }
1542 
1543   /// See AAIsDead::isKnownDead().
1544   bool isKnownDead(BasicBlock *BB) const override {
1545     if (!getKnown())
1546       return false;
1547     return !AssumedLiveBlocks.count(BB);
1548   }
1549 
1550   /// Collection of to be explored paths.
1551   SmallSetVector<Instruction *, 8> ToBeExploredPaths;
1552 
1553   /// Collection of all assumed live BasicBlocks.
1554   DenseSet<BasicBlock *> AssumedLiveBlocks;
1555 
1556   /// Collection of calls with noreturn attribute, assumed or knwon.
1557   SmallSetVector<Instruction *, 4> NoReturnCalls;
1558 };
1559 
1560 bool AAIsDeadFunction::explorePath(Attributor &A, Instruction *I) {
1561   BasicBlock *BB = I->getParent();
1562 
1563   while (I) {
1564     ImmutableCallSite ICS(I);
1565 
1566     if (ICS) {
1567       auto *NoReturnAA = A.getAAFor<AANoReturn>(*this, *I);
1568 
1569       if (NoReturnAA && NoReturnAA->isAssumedNoReturn()) {
1570         if (!NoReturnCalls.insert(I))
1571           // If I is already in the NoReturnCalls set, then it stayed noreturn
1572           // and we didn't discover any new instructions.
1573           return false;
1574 
1575         // Discovered new noreturn call, return true to indicate that I is not
1576         // noreturn anymore and should be deleted from NoReturnCalls.
1577         return true;
1578       }
1579 
1580       if (ICS.hasFnAttr(Attribute::NoReturn)) {
1581         if (!NoReturnCalls.insert(I))
1582           return false;
1583 
1584         return true;
1585       }
1586     }
1587 
1588     I = I->getNextNode();
1589   }
1590 
1591   // get new paths (reachable blocks).
1592   for (BasicBlock *SuccBB : successors(BB)) {
1593     Instruction *Inst = &(SuccBB->front());
1594     AssumedLiveBlocks.insert(SuccBB);
1595     ToBeExploredPaths.insert(Inst);
1596   }
1597 
1598   return true;
1599 }
1600 
1601 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) {
1602   // Temporary collection to iterate over existing noreturn instructions. This
1603   // will alow easier modification of NoReturnCalls collection
1604   SmallVector<Instruction *, 8> NoReturnChanged;
1605   ChangeStatus Status = ChangeStatus::UNCHANGED;
1606 
1607   for (Instruction *I : NoReturnCalls)
1608     NoReturnChanged.push_back(I);
1609 
1610   for (Instruction *I : NoReturnChanged) {
1611     size_t Size = ToBeExploredPaths.size();
1612 
1613     // Still noreturn.
1614     if (!explorePath(A, I))
1615       continue;
1616 
1617     NoReturnCalls.remove(I);
1618 
1619     // No new paths.
1620     if (Size == ToBeExploredPaths.size())
1621       continue;
1622 
1623     // At least one new path.
1624     Status = ChangeStatus::CHANGED;
1625 
1626     // explore new paths.
1627     while (Size != ToBeExploredPaths.size())
1628       explorePath(A, ToBeExploredPaths[Size++]);
1629   }
1630 
1631   LLVM_DEBUG(
1632       dbgs() << "[AAIsDead] AssumedLiveBlocks: " << AssumedLiveBlocks.size()
1633              << "Total number of blocks: " << getAnchorScope().size() << "\n");
1634 
1635   return Status;
1636 }
1637 
1638 /// -------------------- Dereferenceable Argument Attribute --------------------
1639 
1640 struct DerefState : AbstractState {
1641 
1642   /// State representing for dereferenceable bytes.
1643   IntegerState DerefBytesState;
1644 
1645   /// State representing that whether the value is nonnull or global.
1646   IntegerState NonNullGlobalState;
1647 
1648   /// Bits encoding for NonNullGlobalState.
1649   enum {
1650     DEREF_NONNULL = 1 << 0,
1651     DEREF_GLOBAL = 1 << 1,
1652   };
1653 
1654   /// See AbstractState::isValidState()
1655   bool isValidState() const override { return DerefBytesState.isValidState(); }
1656 
1657   // See AbstractState::isAtFixpoint()
1658   bool isAtFixpoint() const override {
1659     return DerefBytesState.isAtFixpoint() && NonNullGlobalState.isAtFixpoint();
1660   }
1661 
1662   /// See AbstractState::indicateOptimisticFixpoint(...)
1663   void indicateOptimisticFixpoint() override {
1664     DerefBytesState.indicateOptimisticFixpoint();
1665     NonNullGlobalState.indicateOptimisticFixpoint();
1666   }
1667 
1668   /// See AbstractState::indicatePessimisticFixpoint(...)
1669   void indicatePessimisticFixpoint() override {
1670     DerefBytesState.indicatePessimisticFixpoint();
1671     NonNullGlobalState.indicatePessimisticFixpoint();
1672   }
1673 
1674   /// Update known dereferenceable bytes.
1675   void takeKnownDerefBytesMaximum(uint64_t Bytes) {
1676     DerefBytesState.takeKnownMaximum(Bytes);
1677   }
1678 
1679   /// Update assumed dereferenceable bytes.
1680   void takeAssumedDerefBytesMinimum(uint64_t Bytes) {
1681     DerefBytesState.takeAssumedMinimum(Bytes);
1682   }
1683 
1684   /// Update assumed NonNullGlobalState
1685   void updateAssumedNonNullGlobalState(bool IsNonNull, bool IsGlobal) {
1686     if (!IsNonNull)
1687       NonNullGlobalState.removeAssumedBits(DEREF_NONNULL);
1688     if (!IsGlobal)
1689       NonNullGlobalState.removeAssumedBits(DEREF_GLOBAL);
1690   }
1691 
1692   /// Equality for DerefState.
1693   bool operator==(const DerefState &R) {
1694     return this->DerefBytesState == R.DerefBytesState &&
1695            this->NonNullGlobalState == R.NonNullGlobalState;
1696   }
1697 };
1698 struct AADereferenceableImpl : AADereferenceable, DerefState {
1699 
1700   AADereferenceableImpl(Value &V, InformationCache &InfoCache)
1701       : AADereferenceable(V, InfoCache) {}
1702 
1703   AADereferenceableImpl(Value *AssociatedVal, Value &AnchoredValue,
1704                         InformationCache &InfoCache)
1705       : AADereferenceable(AssociatedVal, AnchoredValue, InfoCache) {}
1706 
1707   /// See AbstractAttribute::getState()
1708   /// {
1709   AbstractState &getState() override { return *this; }
1710   const AbstractState &getState() const override { return *this; }
1711   /// }
1712 
1713   /// See AADereferenceable::getAssumedDereferenceableBytes().
1714   uint32_t getAssumedDereferenceableBytes() const override {
1715     return DerefBytesState.getAssumed();
1716   }
1717 
1718   /// See AADereferenceable::getKnownDereferenceableBytes().
1719   uint32_t getKnownDereferenceableBytes() const override {
1720     return DerefBytesState.getKnown();
1721   }
1722 
1723   // Helper function for syncing nonnull state.
1724   void syncNonNull(const AANonNull *NonNullAA) {
1725     if (!NonNullAA) {
1726       NonNullGlobalState.removeAssumedBits(DEREF_NONNULL);
1727       return;
1728     }
1729 
1730     if (NonNullAA->isKnownNonNull())
1731       NonNullGlobalState.addKnownBits(DEREF_NONNULL);
1732 
1733     if (!NonNullAA->isAssumedNonNull())
1734       NonNullGlobalState.removeAssumedBits(DEREF_NONNULL);
1735   }
1736 
1737   /// See AADereferenceable::isAssumedGlobal().
1738   bool isAssumedGlobal() const override {
1739     return NonNullGlobalState.isAssumed(DEREF_GLOBAL);
1740   }
1741 
1742   /// See AADereferenceable::isKnownGlobal().
1743   bool isKnownGlobal() const override {
1744     return NonNullGlobalState.isKnown(DEREF_GLOBAL);
1745   }
1746 
1747   /// See AADereferenceable::isAssumedNonNull().
1748   bool isAssumedNonNull() const override {
1749     return NonNullGlobalState.isAssumed(DEREF_NONNULL);
1750   }
1751 
1752   /// See AADereferenceable::isKnownNonNull().
1753   bool isKnownNonNull() const override {
1754     return NonNullGlobalState.isKnown(DEREF_NONNULL);
1755   }
1756 
1757   void getDeducedAttributes(SmallVectorImpl<Attribute> &Attrs) const override {
1758     LLVMContext &Ctx = AnchoredVal.getContext();
1759 
1760     // TODO: Add *_globally support
1761     if (isAssumedNonNull())
1762       Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
1763           Ctx, getAssumedDereferenceableBytes()));
1764     else
1765       Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
1766           Ctx, getAssumedDereferenceableBytes()));
1767   }
1768   uint64_t computeAssumedDerefenceableBytes(Attributor &A, Value &V,
1769                                             bool &IsNonNull, bool &IsGlobal);
1770 
1771   void initialize(Attributor &A) override {
1772     Function &F = getAnchorScope();
1773     unsigned AttrIdx =
1774         getAttrIndex(getManifestPosition(), getArgNo(getAnchoredValue()));
1775 
1776     for (Attribute::AttrKind AK :
1777          {Attribute::Dereferenceable, Attribute::DereferenceableOrNull})
1778       if (F.getAttributes().hasAttribute(AttrIdx, AK))
1779         takeKnownDerefBytesMaximum(F.getAttribute(AttrIdx, AK).getValueAsInt());
1780   }
1781 
1782   /// See AbstractAttribute::getAsStr().
1783   const std::string getAsStr() const override {
1784     if (!getAssumedDereferenceableBytes())
1785       return "unknown-dereferenceable";
1786     return std::string("dereferenceable") +
1787            (isAssumedNonNull() ? "" : "_or_null") +
1788            (isAssumedGlobal() ? "_globally" : "") + "<" +
1789            std::to_string(getKnownDereferenceableBytes()) + "-" +
1790            std::to_string(getAssumedDereferenceableBytes()) + ">";
1791   }
1792 };
1793 
1794 struct AADereferenceableReturned : AADereferenceableImpl {
1795   AADereferenceableReturned(Function &F, InformationCache &InfoCache)
1796       : AADereferenceableImpl(F, InfoCache) {}
1797 
1798   /// See AbstractAttribute::getManifestPosition().
1799   ManifestPosition getManifestPosition() const override { return MP_RETURNED; }
1800 
1801   /// See AbstractAttribute::updateImpl(...).
1802   ChangeStatus updateImpl(Attributor &A) override;
1803 };
1804 
1805 // Helper function that returns dereferenceable bytes.
1806 static uint64_t calcDifferenceIfBaseIsNonNull(int64_t DerefBytes,
1807                                               int64_t Offset, bool IsNonNull) {
1808   if (!IsNonNull)
1809     return 0;
1810   return std::max((int64_t)0, DerefBytes - Offset);
1811 }
1812 
1813 uint64_t AADereferenceableImpl::computeAssumedDerefenceableBytes(
1814     Attributor &A, Value &V, bool &IsNonNull, bool &IsGlobal) {
1815   // TODO: Tracking the globally flag.
1816   IsGlobal = false;
1817 
1818   // First, we try to get information about V from Attributor.
1819   if (auto *DerefAA = A.getAAFor<AADereferenceable>(*this, V)) {
1820     IsNonNull &= DerefAA->isAssumedNonNull();
1821     return DerefAA->getAssumedDereferenceableBytes();
1822   }
1823 
1824   // Otherwise, we try to compute assumed bytes from base pointer.
1825   const DataLayout &DL = getAnchorScope().getParent()->getDataLayout();
1826   unsigned IdxWidth =
1827       DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace());
1828   APInt Offset(IdxWidth, 0);
1829   Value *Base = V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1830 
1831   if (auto *BaseDerefAA = A.getAAFor<AADereferenceable>(*this, *Base)) {
1832     IsNonNull &= Offset != 0;
1833     return calcDifferenceIfBaseIsNonNull(
1834         BaseDerefAA->getAssumedDereferenceableBytes(), Offset.getSExtValue(),
1835         Offset != 0 || BaseDerefAA->isAssumedNonNull());
1836   }
1837 
1838   // Then, use IR information.
1839 
1840   if (isDereferenceablePointer(Base, Base->getType(), DL))
1841     return calcDifferenceIfBaseIsNonNull(
1842         DL.getTypeStoreSize(Base->getType()->getPointerElementType()),
1843         Offset.getSExtValue(),
1844         !NullPointerIsDefined(&getAnchorScope(),
1845                               V.getType()->getPointerAddressSpace()));
1846 
1847   IsNonNull = false;
1848   return 0;
1849 }
1850 ChangeStatus AADereferenceableReturned::updateImpl(Attributor &A) {
1851   Function &F = getAnchorScope();
1852   auto BeforeState = static_cast<DerefState>(*this);
1853 
1854   syncNonNull(A.getAAFor<AANonNull>(*this, F));
1855 
1856   auto *AARetVal = A.getAAFor<AAReturnedValues>(*this, F);
1857   if (!AARetVal) {
1858     indicatePessimisticFixpoint();
1859     return ChangeStatus::CHANGED;
1860   }
1861 
1862   bool IsNonNull = isAssumedNonNull();
1863   bool IsGlobal = isAssumedGlobal();
1864 
1865   std::function<bool(Value &)> Pred = [&](Value &RV) -> bool {
1866     takeAssumedDerefBytesMinimum(
1867         computeAssumedDerefenceableBytes(A, RV, IsNonNull, IsGlobal));
1868     return isValidState();
1869   };
1870 
1871   if (AARetVal->checkForallReturnedValues(Pred)) {
1872     updateAssumedNonNullGlobalState(IsNonNull, IsGlobal);
1873     return BeforeState == static_cast<DerefState>(*this)
1874                ? ChangeStatus::UNCHANGED
1875                : ChangeStatus::CHANGED;
1876   }
1877   indicatePessimisticFixpoint();
1878   return ChangeStatus::CHANGED;
1879 }
1880 
1881 struct AADereferenceableArgument : AADereferenceableImpl {
1882   AADereferenceableArgument(Argument &A, InformationCache &InfoCache)
1883       : AADereferenceableImpl(A, InfoCache) {}
1884 
1885   /// See AbstractAttribute::getManifestPosition().
1886   ManifestPosition getManifestPosition() const override { return MP_ARGUMENT; }
1887 
1888   /// See AbstractAttribute::updateImpl(...).
1889   ChangeStatus updateImpl(Attributor &A) override;
1890 };
1891 
1892 ChangeStatus AADereferenceableArgument::updateImpl(Attributor &A) {
1893   Function &F = getAnchorScope();
1894   Argument &Arg = cast<Argument>(getAnchoredValue());
1895 
1896   auto BeforeState = static_cast<DerefState>(*this);
1897 
1898   unsigned ArgNo = Arg.getArgNo();
1899 
1900   syncNonNull(A.getAAFor<AANonNull>(*this, F, ArgNo));
1901 
1902   bool IsNonNull = isAssumedNonNull();
1903   bool IsGlobal = isAssumedGlobal();
1904 
1905   // Callback function
1906   std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) -> bool {
1907     assert(CS && "Sanity check: Call site was not initialized properly!");
1908 
1909     // Check that DereferenceableAA is AADereferenceableCallSiteArgument.
1910     if (auto *DereferenceableAA =
1911             A.getAAFor<AADereferenceable>(*this, *CS.getInstruction(), ArgNo)) {
1912       ImmutableCallSite ICS(&DereferenceableAA->getAnchoredValue());
1913       if (ICS && CS.getInstruction() == ICS.getInstruction()) {
1914         takeAssumedDerefBytesMinimum(
1915             DereferenceableAA->getAssumedDereferenceableBytes());
1916         IsNonNull &= DereferenceableAA->isAssumedNonNull();
1917         IsGlobal &= DereferenceableAA->isAssumedGlobal();
1918         return isValidState();
1919       }
1920     }
1921 
1922     takeAssumedDerefBytesMinimum(computeAssumedDerefenceableBytes(
1923         A, *CS.getArgOperand(ArgNo), IsNonNull, IsGlobal));
1924 
1925     return isValidState();
1926   };
1927 
1928   if (!A.checkForAllCallSites(F, CallSiteCheck, true)) {
1929     indicatePessimisticFixpoint();
1930     return ChangeStatus::CHANGED;
1931   }
1932 
1933   updateAssumedNonNullGlobalState(IsNonNull, IsGlobal);
1934 
1935   return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED
1936                                                        : ChangeStatus::CHANGED;
1937 }
1938 
1939 /// Dereferenceable attribute for a call site argument.
1940 struct AADereferenceableCallSiteArgument : AADereferenceableImpl {
1941 
1942   /// See AADereferenceableImpl::AADereferenceableImpl(...).
1943   AADereferenceableCallSiteArgument(CallSite CS, unsigned ArgNo,
1944                                     InformationCache &InfoCache)
1945       : AADereferenceableImpl(CS.getArgOperand(ArgNo), *CS.getInstruction(),
1946                               InfoCache),
1947         ArgNo(ArgNo) {}
1948 
1949   /// See AbstractAttribute::initialize(...).
1950   void initialize(Attributor &A) override {
1951     CallSite CS(&getAnchoredValue());
1952     if (CS.paramHasAttr(ArgNo, Attribute::Dereferenceable))
1953       takeKnownDerefBytesMaximum(CS.getDereferenceableBytes(ArgNo));
1954 
1955     if (CS.paramHasAttr(ArgNo, Attribute::DereferenceableOrNull))
1956       takeKnownDerefBytesMaximum(CS.getDereferenceableOrNullBytes(ArgNo));
1957   }
1958 
1959   /// See AbstractAttribute::updateImpl(Attributor &A).
1960   ChangeStatus updateImpl(Attributor &A) override;
1961 
1962   /// See AbstractAttribute::getManifestPosition().
1963   ManifestPosition getManifestPosition() const override {
1964     return MP_CALL_SITE_ARGUMENT;
1965   };
1966 
1967   // Return argument index of associated value.
1968   int getArgNo() const { return ArgNo; }
1969 
1970 private:
1971   unsigned ArgNo;
1972 };
1973 
1974 ChangeStatus AADereferenceableCallSiteArgument::updateImpl(Attributor &A) {
1975   // NOTE: Never look at the argument of the callee in this method.
1976   //       If we do this, "dereferenceable" is always deduced because of the
1977   //       assumption.
1978 
1979   Value &V = *getAssociatedValue();
1980 
1981   auto BeforeState = static_cast<DerefState>(*this);
1982 
1983   syncNonNull(A.getAAFor<AANonNull>(*this, getAnchoredValue(), ArgNo));
1984   bool IsNonNull = isAssumedNonNull();
1985   bool IsGlobal = isKnownGlobal();
1986 
1987   takeAssumedDerefBytesMinimum(
1988       computeAssumedDerefenceableBytes(A, V, IsNonNull, IsGlobal));
1989   updateAssumedNonNullGlobalState(IsNonNull, IsGlobal);
1990 
1991   return BeforeState == static_cast<DerefState>(*this) ? ChangeStatus::UNCHANGED
1992                                                        : ChangeStatus::CHANGED;
1993 }
1994 
1995 // ------------------------ Align Argument Attribute ------------------------
1996 
1997 struct AAAlignImpl : AAAlign, IntegerState {
1998 
1999   // Max alignemnt value allowed in IR
2000   static const unsigned MAX_ALIGN = 1U << 29;
2001 
2002   AAAlignImpl(Value *AssociatedVal, Value &AnchoredValue,
2003               InformationCache &InfoCache)
2004       : AAAlign(AssociatedVal, AnchoredValue, InfoCache),
2005         IntegerState(MAX_ALIGN) {}
2006 
2007   AAAlignImpl(Value &V, InformationCache &InfoCache)
2008       : AAAlignImpl(&V, V, InfoCache) {}
2009 
2010   /// See AbstractAttribute::getState()
2011   /// {
2012   AbstractState &getState() override { return *this; }
2013   const AbstractState &getState() const override { return *this; }
2014   /// }
2015 
2016   virtual const std::string getAsStr() const override {
2017     return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) +
2018                                 "-" + std::to_string(getAssumedAlign()) + ">")
2019                              : "unknown-align";
2020   }
2021 
2022   /// See AAAlign::getAssumedAlign().
2023   unsigned getAssumedAlign() const override { return getAssumed(); }
2024 
2025   /// See AAAlign::getKnownAlign().
2026   unsigned getKnownAlign() const override { return getKnown(); }
2027 
2028   /// See AbstractAttriubute::initialize(...).
2029   void initialize(Attributor &A) override {
2030     Function &F = getAnchorScope();
2031 
2032     unsigned AttrIdx =
2033         getAttrIndex(getManifestPosition(), getArgNo(getAnchoredValue()));
2034 
2035     // Already the function has align attribute on return value or argument.
2036     if (F.getAttributes().hasAttribute(AttrIdx, ID))
2037       addKnownBits(F.getAttribute(AttrIdx, ID).getAlignment());
2038   }
2039 
2040   /// See AbstractAttribute::getDeducedAttributes
2041   virtual void
2042   getDeducedAttributes(SmallVectorImpl<Attribute> &Attrs) const override {
2043     LLVMContext &Ctx = AnchoredVal.getContext();
2044 
2045     Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign()));
2046   }
2047 };
2048 
2049 /// Align attribute for function return value.
2050 struct AAAlignReturned : AAAlignImpl {
2051 
2052   AAAlignReturned(Function &F, InformationCache &InfoCache)
2053       : AAAlignImpl(F, InfoCache) {}
2054 
2055   /// See AbstractAttribute::getManifestPosition().
2056   virtual ManifestPosition getManifestPosition() const override {
2057     return MP_RETURNED;
2058   }
2059 
2060   /// See AbstractAttribute::updateImpl(...).
2061   virtual ChangeStatus updateImpl(Attributor &A) override;
2062 };
2063 
2064 ChangeStatus AAAlignReturned::updateImpl(Attributor &A) {
2065   Function &F = getAnchorScope();
2066   auto *AARetValImpl = A.getAAFor<AAReturnedValuesImpl>(*this, F);
2067   if (!AARetValImpl) {
2068     indicatePessimisticFixpoint();
2069     return ChangeStatus::CHANGED;
2070   }
2071 
2072   // Currently, align<n> is deduced if alignments in return values are assumed
2073   // as greater than n. We reach pessimistic fixpoint if any of the return value
2074   // wouldn't have align. If no assumed state was used for reasoning, an
2075   // optimistic fixpoint is reached earlier.
2076 
2077   base_t BeforeState = getAssumed();
2078   std::function<bool(Value &)> Pred = [&](Value &RV) -> bool {
2079     auto *AlignAA = A.getAAFor<AAAlign>(*this, RV);
2080 
2081     if (AlignAA)
2082       takeAssumedMinimum(AlignAA->getAssumedAlign());
2083     else
2084       // Use IR information.
2085       takeAssumedMinimum(RV.getPointerAlignment(
2086           getAnchorScope().getParent()->getDataLayout()));
2087 
2088     return isValidState();
2089   };
2090 
2091   if (!AARetValImpl->checkForallReturnedValues(Pred)) {
2092     indicatePessimisticFixpoint();
2093     return ChangeStatus::CHANGED;
2094   }
2095 
2096   return (getAssumed() != BeforeState) ? ChangeStatus::CHANGED
2097                                        : ChangeStatus::UNCHANGED;
2098 }
2099 
2100 /// Align attribute for function argument.
2101 struct AAAlignArgument : AAAlignImpl {
2102 
2103   AAAlignArgument(Argument &A, InformationCache &InfoCache)
2104       : AAAlignImpl(A, InfoCache) {}
2105 
2106   /// See AbstractAttribute::getManifestPosition().
2107   virtual ManifestPosition getManifestPosition() const override {
2108     return MP_ARGUMENT;
2109   }
2110 
2111   /// See AbstractAttribute::updateImpl(...).
2112   virtual ChangeStatus updateImpl(Attributor &A) override;
2113 };
2114 
2115 ChangeStatus AAAlignArgument::updateImpl(Attributor &A) {
2116 
2117   Function &F = getAnchorScope();
2118   Argument &Arg = cast<Argument>(getAnchoredValue());
2119 
2120   unsigned ArgNo = Arg.getArgNo();
2121   const DataLayout &DL = F.getParent()->getDataLayout();
2122 
2123   auto BeforeState = getAssumed();
2124 
2125   // Callback function
2126   std::function<bool(CallSite)> CallSiteCheck = [&](CallSite CS) {
2127     assert(CS && "Sanity check: Call site was not initialized properly!");
2128 
2129     auto *AlignAA = A.getAAFor<AAAlign>(*this, *CS.getInstruction(), ArgNo);
2130 
2131     // Check that AlignAA is AAAlignCallSiteArgument.
2132     if (AlignAA) {
2133       ImmutableCallSite ICS(&AlignAA->getAnchoredValue());
2134       if (ICS && CS.getInstruction() == ICS.getInstruction()) {
2135         takeAssumedMinimum(AlignAA->getAssumedAlign());
2136         return isValidState();
2137       }
2138     }
2139 
2140     Value *V = CS.getArgOperand(ArgNo);
2141     takeAssumedMinimum(V->getPointerAlignment(DL));
2142     return isValidState();
2143   };
2144 
2145   if (!A.checkForAllCallSites(F, CallSiteCheck, true))
2146     indicatePessimisticFixpoint();
2147 
2148   return BeforeState == getAssumed() ? ChangeStatus::UNCHANGED
2149                                      : ChangeStatus ::CHANGED;
2150 }
2151 
2152 struct AAAlignCallSiteArgument : AAAlignImpl {
2153 
2154   /// See AANonNullImpl::AANonNullImpl(...).
2155   AAAlignCallSiteArgument(CallSite CS, unsigned ArgNo,
2156                           InformationCache &InfoCache)
2157       : AAAlignImpl(CS.getArgOperand(ArgNo), *CS.getInstruction(), InfoCache),
2158         ArgNo(ArgNo) {}
2159 
2160   /// See AbstractAttribute::initialize(...).
2161   void initialize(Attributor &A) override {
2162     CallSite CS(&getAnchoredValue());
2163     takeKnownMaximum(getAssociatedValue()->getPointerAlignment(
2164         getAnchorScope().getParent()->getDataLayout()));
2165   }
2166 
2167   /// See AbstractAttribute::updateImpl(Attributor &A).
2168   ChangeStatus updateImpl(Attributor &A) override;
2169 
2170   /// See AbstractAttribute::getManifestPosition().
2171   ManifestPosition getManifestPosition() const override {
2172     return MP_CALL_SITE_ARGUMENT;
2173   };
2174 
2175   // Return argument index of associated value.
2176   int getArgNo() const { return ArgNo; }
2177 
2178 private:
2179   unsigned ArgNo;
2180 };
2181 
2182 ChangeStatus AAAlignCallSiteArgument::updateImpl(Attributor &A) {
2183   // NOTE: Never look at the argument of the callee in this method.
2184   //       If we do this, "align" is always deduced because of the assumption.
2185 
2186   auto BeforeState = getAssumed();
2187 
2188   Value &V = *getAssociatedValue();
2189 
2190   auto *AlignAA = A.getAAFor<AAAlign>(*this, V);
2191 
2192   if (AlignAA)
2193     takeAssumedMinimum(AlignAA->getAssumedAlign());
2194   else
2195     indicatePessimisticFixpoint();
2196 
2197   return BeforeState == getAssumed() ? ChangeStatus::UNCHANGED
2198                                      : ChangeStatus::CHANGED;
2199 }
2200 
2201 /// ----------------------------------------------------------------------------
2202 ///                               Attributor
2203 /// ----------------------------------------------------------------------------
2204 
2205 bool Attributor::checkForAllCallSites(Function &F,
2206                                       std::function<bool(CallSite)> &Pred,
2207                                       bool RequireAllCallSites) {
2208   // We can try to determine information from
2209   // the call sites. However, this is only possible all call sites are known,
2210   // hence the function has internal linkage.
2211   if (RequireAllCallSites && !F.hasInternalLinkage()) {
2212     LLVM_DEBUG(
2213         dbgs()
2214         << "Attributor: Function " << F.getName()
2215         << " has no internal linkage, hence not all call sites are known\n");
2216     return false;
2217   }
2218 
2219   for (const Use &U : F.uses()) {
2220 
2221     CallSite CS(U.getUser());
2222     if (!CS || !CS.isCallee(&U) || !CS.getCaller()->hasExactDefinition()) {
2223       if (!RequireAllCallSites)
2224         continue;
2225 
2226       LLVM_DEBUG(dbgs() << "Attributor: User " << *U.getUser()
2227                         << " is an invalid use of " << F.getName() << "\n");
2228       return false;
2229     }
2230 
2231     if (Pred(CS))
2232       continue;
2233 
2234     LLVM_DEBUG(dbgs() << "Attributor: Call site callback failed for "
2235                       << *CS.getInstruction() << "\n");
2236     return false;
2237   }
2238 
2239   return true;
2240 }
2241 
2242 ChangeStatus Attributor::run() {
2243   // Initialize all abstract attributes.
2244   for (AbstractAttribute *AA : AllAbstractAttributes)
2245     AA->initialize(*this);
2246 
2247   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
2248                     << AllAbstractAttributes.size()
2249                     << " abstract attributes.\n");
2250 
2251   // Now that all abstract attributes are collected and initialized we start
2252   // the abstract analysis.
2253 
2254   unsigned IterationCounter = 1;
2255 
2256   SmallVector<AbstractAttribute *, 64> ChangedAAs;
2257   SetVector<AbstractAttribute *> Worklist;
2258   Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end());
2259 
2260   do {
2261     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
2262                       << ", Worklist size: " << Worklist.size() << "\n");
2263 
2264     // Add all abstract attributes that are potentially dependent on one that
2265     // changed to the work list.
2266     for (AbstractAttribute *ChangedAA : ChangedAAs) {
2267       auto &QuerriedAAs = QueryMap[ChangedAA];
2268       Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end());
2269     }
2270 
2271     // Reset the changed set.
2272     ChangedAAs.clear();
2273 
2274     // Update all abstract attribute in the work list and record the ones that
2275     // changed.
2276     for (AbstractAttribute *AA : Worklist)
2277       if (AA->update(*this) == ChangeStatus::CHANGED)
2278         ChangedAAs.push_back(AA);
2279 
2280     // Reset the work list and repopulate with the changed abstract attributes.
2281     // Note that dependent ones are added above.
2282     Worklist.clear();
2283     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
2284 
2285   } while (!Worklist.empty() && ++IterationCounter < MaxFixpointIterations);
2286 
2287   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
2288                     << IterationCounter << "/" << MaxFixpointIterations
2289                     << " iterations\n");
2290 
2291   bool FinishedAtFixpoint = Worklist.empty();
2292 
2293   // Reset abstract arguments not settled in a sound fixpoint by now. This
2294   // happens when we stopped the fixpoint iteration early. Note that only the
2295   // ones marked as "changed" *and* the ones transitively depending on them
2296   // need to be reverted to a pessimistic state. Others might not be in a
2297   // fixpoint state but we can use the optimistic results for them anyway.
2298   SmallPtrSet<AbstractAttribute *, 32> Visited;
2299   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
2300     AbstractAttribute *ChangedAA = ChangedAAs[u];
2301     if (!Visited.insert(ChangedAA).second)
2302       continue;
2303 
2304     AbstractState &State = ChangedAA->getState();
2305     if (!State.isAtFixpoint()) {
2306       State.indicatePessimisticFixpoint();
2307 
2308       NumAttributesTimedOut++;
2309     }
2310 
2311     auto &QuerriedAAs = QueryMap[ChangedAA];
2312     ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end());
2313   }
2314 
2315   LLVM_DEBUG({
2316     if (!Visited.empty())
2317       dbgs() << "\n[Attributor] Finalized " << Visited.size()
2318              << " abstract attributes.\n";
2319   });
2320 
2321   unsigned NumManifested = 0;
2322   unsigned NumAtFixpoint = 0;
2323   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
2324   for (AbstractAttribute *AA : AllAbstractAttributes) {
2325     AbstractState &State = AA->getState();
2326 
2327     // If there is not already a fixpoint reached, we can now take the
2328     // optimistic state. This is correct because we enforced a pessimistic one
2329     // on abstract attributes that were transitively dependent on a changed one
2330     // already above.
2331     if (!State.isAtFixpoint())
2332       State.indicateOptimisticFixpoint();
2333 
2334     // If the state is invalid, we do not try to manifest it.
2335     if (!State.isValidState())
2336       continue;
2337 
2338     // Manifest the state and record if we changed the IR.
2339     ChangeStatus LocalChange = AA->manifest(*this);
2340     ManifestChange = ManifestChange | LocalChange;
2341 
2342     NumAtFixpoint++;
2343     NumManifested += (LocalChange == ChangeStatus::CHANGED);
2344   }
2345 
2346   (void)NumManifested;
2347   (void)NumAtFixpoint;
2348   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
2349                     << " arguments while " << NumAtFixpoint
2350                     << " were in a valid fixpoint state\n");
2351 
2352   // If verification is requested, we finished this run at a fixpoint, and the
2353   // IR was changed, we re-run the whole fixpoint analysis, starting at
2354   // re-initialization of the arguments. This re-run should not result in an IR
2355   // change. Though, the (virtual) state of attributes at the end of the re-run
2356   // might be more optimistic than the known state or the IR state if the better
2357   // state cannot be manifested.
2358   if (VerifyAttributor && FinishedAtFixpoint &&
2359       ManifestChange == ChangeStatus::CHANGED) {
2360     VerifyAttributor = false;
2361     ChangeStatus VerifyStatus = run();
2362     if (VerifyStatus != ChangeStatus::UNCHANGED)
2363       llvm_unreachable(
2364           "Attributor verification failed, re-run did result in an IR change "
2365           "even after a fixpoint was reached in the original run. (False "
2366           "positives possible!)");
2367     VerifyAttributor = true;
2368   }
2369 
2370   NumAttributesManifested += NumManifested;
2371   NumAttributesValidFixpoint += NumAtFixpoint;
2372 
2373   return ManifestChange;
2374 }
2375 
2376 void Attributor::identifyDefaultAbstractAttributes(
2377     Function &F, InformationCache &InfoCache,
2378     DenseSet</* Attribute::AttrKind */ unsigned> *Whitelist) {
2379 
2380   // Every function can be nounwind.
2381   registerAA(*new AANoUnwindFunction(F, InfoCache));
2382 
2383   // Every function might be marked "nosync"
2384   registerAA(*new AANoSyncFunction(F, InfoCache));
2385 
2386   // Every function might be "no-free".
2387   registerAA(*new AANoFreeFunction(F, InfoCache));
2388 
2389   // Return attributes are only appropriate if the return type is non void.
2390   Type *ReturnType = F.getReturnType();
2391   if (!ReturnType->isVoidTy()) {
2392     // Argument attribute "returned" --- Create only one per function even
2393     // though it is an argument attribute.
2394     if (!Whitelist || Whitelist->count(AAReturnedValues::ID))
2395       registerAA(*new AAReturnedValuesImpl(F, InfoCache));
2396 
2397     if (ReturnType->isPointerTy()) {
2398       // Every function with pointer return type might be marked align.
2399       if (!Whitelist || Whitelist->count(AAAlignReturned::ID))
2400         registerAA(*new AAAlignReturned(F, InfoCache));
2401 
2402       // Every function with pointer return type might be marked nonnull.
2403       if (!Whitelist || Whitelist->count(AANonNullReturned::ID))
2404         registerAA(*new AANonNullReturned(F, InfoCache));
2405 
2406       // Every function with pointer return type might be marked noalias.
2407       if (!Whitelist || Whitelist->count(AANoAliasReturned::ID))
2408         registerAA(*new AANoAliasReturned(F, InfoCache));
2409 
2410       // Every function with pointer return type might be marked
2411       // dereferenceable.
2412       if (ReturnType->isPointerTy() &&
2413           (!Whitelist || Whitelist->count(AADereferenceableReturned::ID)))
2414         registerAA(*new AADereferenceableReturned(F, InfoCache));
2415     }
2416   }
2417 
2418   for (Argument &Arg : F.args()) {
2419     if (Arg.getType()->isPointerTy()) {
2420       // Every argument with pointer type might be marked nonnull.
2421       if (!Whitelist || Whitelist->count(AANonNullArgument::ID))
2422         registerAA(*new AANonNullArgument(Arg, InfoCache));
2423 
2424       // Every argument with pointer type might be marked dereferenceable.
2425       if (!Whitelist || Whitelist->count(AADereferenceableArgument::ID))
2426         registerAA(*new AADereferenceableArgument(Arg, InfoCache));
2427 
2428       // Every argument with pointer type might be marked align.
2429       if (!Whitelist || Whitelist->count(AAAlignArgument::ID))
2430         registerAA(*new AAAlignArgument(Arg, InfoCache));
2431     }
2432   }
2433 
2434   // Every function might be "will-return".
2435   registerAA(*new AAWillReturnFunction(F, InfoCache));
2436 
2437   // Check for dead BasicBlocks in every function.
2438   registerAA(*new AAIsDeadFunction(F, InfoCache));
2439 
2440   // Walk all instructions to find more attribute opportunities and also
2441   // interesting instructions that might be queried by abstract attributes
2442   // during their initialization or update.
2443   auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F];
2444   auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F];
2445 
2446   for (Instruction &I : instructions(&F)) {
2447     bool IsInterestingOpcode = false;
2448 
2449     // To allow easy access to all instructions in a function with a given
2450     // opcode we store them in the InfoCache. As not all opcodes are interesting
2451     // to concrete attributes we only cache the ones that are as identified in
2452     // the following switch.
2453     // Note: There are no concrete attributes now so this is initially empty.
2454     switch (I.getOpcode()) {
2455     default:
2456       assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) &&
2457              "New call site/base instruction type needs to be known int the "
2458              "attributor.");
2459       break;
2460     case Instruction::Call:
2461     case Instruction::CallBr:
2462     case Instruction::Invoke:
2463     case Instruction::CleanupRet:
2464     case Instruction::CatchSwitch:
2465     case Instruction::Resume:
2466     case Instruction::Ret:
2467       IsInterestingOpcode = true;
2468     }
2469     if (IsInterestingOpcode)
2470       InstOpcodeMap[I.getOpcode()].push_back(&I);
2471     if (I.mayReadOrWriteMemory())
2472       ReadOrWriteInsts.push_back(&I);
2473 
2474     CallSite CS(&I);
2475     if (CS && CS.getCalledFunction()) {
2476       for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) {
2477         if (!CS.getArgument(i)->getType()->isPointerTy())
2478           continue;
2479 
2480         // Call site argument attribute "non-null".
2481         if (!Whitelist || Whitelist->count(AANonNullCallSiteArgument::ID))
2482           registerAA(*new AANonNullCallSiteArgument(CS, i, InfoCache), i);
2483 
2484         // Call site argument attribute "dereferenceable".
2485         if (!Whitelist ||
2486             Whitelist->count(AADereferenceableCallSiteArgument::ID))
2487           registerAA(*new AADereferenceableCallSiteArgument(CS, i, InfoCache),
2488                      i);
2489 
2490         // Call site argument attribute "align".
2491         if (!Whitelist || Whitelist->count(AAAlignCallSiteArgument::ID))
2492           registerAA(*new AAAlignCallSiteArgument(CS, i, InfoCache), i);
2493       }
2494     }
2495   }
2496 }
2497 
2498 /// Helpers to ease debugging through output streams and print calls.
2499 ///
2500 ///{
2501 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
2502   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
2503 }
2504 
2505 raw_ostream &llvm::operator<<(raw_ostream &OS,
2506                               AbstractAttribute::ManifestPosition AP) {
2507   switch (AP) {
2508   case AbstractAttribute::MP_ARGUMENT:
2509     return OS << "arg";
2510   case AbstractAttribute::MP_CALL_SITE_ARGUMENT:
2511     return OS << "cs_arg";
2512   case AbstractAttribute::MP_FUNCTION:
2513     return OS << "fn";
2514   case AbstractAttribute::MP_RETURNED:
2515     return OS << "fn_ret";
2516   }
2517   llvm_unreachable("Unknown attribute position!");
2518 }
2519 
2520 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
2521   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
2522 }
2523 
2524 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
2525   AA.print(OS);
2526   return OS;
2527 }
2528 
2529 void AbstractAttribute::print(raw_ostream &OS) const {
2530   OS << "[" << getManifestPosition() << "][" << getAsStr() << "]["
2531      << AnchoredVal.getName() << "]";
2532 }
2533 ///}
2534 
2535 /// ----------------------------------------------------------------------------
2536 ///                       Pass (Manager) Boilerplate
2537 /// ----------------------------------------------------------------------------
2538 
2539 static bool runAttributorOnModule(Module &M) {
2540   if (DisableAttributor)
2541     return false;
2542 
2543   LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size()
2544                     << " functions.\n");
2545 
2546   // Create an Attributor and initially empty information cache that is filled
2547   // while we identify default attribute opportunities.
2548   Attributor A;
2549   InformationCache InfoCache;
2550 
2551   for (Function &F : M) {
2552     // TODO: Not all attributes require an exact definition. Find a way to
2553     //       enable deduction for some but not all attributes in case the
2554     //       definition might be changed at runtime, see also
2555     //       http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html.
2556     // TODO: We could always determine abstract attributes and if sufficient
2557     //       information was found we could duplicate the functions that do not
2558     //       have an exact definition.
2559     if (!F.hasExactDefinition()) {
2560       NumFnWithoutExactDefinition++;
2561       continue;
2562     }
2563 
2564     // For now we ignore naked and optnone functions.
2565     if (F.hasFnAttribute(Attribute::Naked) ||
2566         F.hasFnAttribute(Attribute::OptimizeNone))
2567       continue;
2568 
2569     NumFnWithExactDefinition++;
2570 
2571     // Populate the Attributor with abstract attribute opportunities in the
2572     // function and the information cache with IR information.
2573     A.identifyDefaultAbstractAttributes(F, InfoCache);
2574   }
2575 
2576   return A.run() == ChangeStatus::CHANGED;
2577 }
2578 
2579 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
2580   if (runAttributorOnModule(M)) {
2581     // FIXME: Think about passes we will preserve and add them here.
2582     return PreservedAnalyses::none();
2583   }
2584   return PreservedAnalyses::all();
2585 }
2586 
2587 namespace {
2588 
2589 struct AttributorLegacyPass : public ModulePass {
2590   static char ID;
2591 
2592   AttributorLegacyPass() : ModulePass(ID) {
2593     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
2594   }
2595 
2596   bool runOnModule(Module &M) override {
2597     if (skipModule(M))
2598       return false;
2599     return runAttributorOnModule(M);
2600   }
2601 
2602   void getAnalysisUsage(AnalysisUsage &AU) const override {
2603     // FIXME: Think about passes we will preserve and add them here.
2604     AU.setPreservesCFG();
2605   }
2606 };
2607 
2608 } // end anonymous namespace
2609 
2610 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
2611 
2612 char AttributorLegacyPass::ID = 0;
2613 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
2614                       "Deduce and propagate attributes", false, false)
2615 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
2616                     "Deduce and propagate attributes", false, false)
2617