1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Rewrite an existing set of gc.statepoints such that they make potential
11 // relocations performed by the garbage collector explicit in the IR.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Pass.h"
16 #include "llvm/Analysis/CFG.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstIterator.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/Cloning.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45 
46 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
47 
48 using namespace llvm;
49 
50 // Print the liveset found at the insert location
51 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52                                   cl::init(false));
53 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54                                       cl::init(false));
55 // Print out the base pointers for debugging
56 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57                                        cl::init(false));
58 
59 // Cost threshold measuring when it is profitable to rematerialize value instead
60 // of relocating it
61 static cl::opt<unsigned>
62 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
63                            cl::init(6));
64 
65 #ifdef XDEBUG
66 static bool ClobberNonLive = true;
67 #else
68 static bool ClobberNonLive = false;
69 #endif
70 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
71                                                   cl::location(ClobberNonLive),
72                                                   cl::Hidden);
73 
74 static cl::opt<bool>
75     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
76                                    cl::Hidden, cl::init(true));
77 
78 namespace {
79 struct RewriteStatepointsForGC : public ModulePass {
80   static char ID; // Pass identification, replacement for typeid
81 
82   RewriteStatepointsForGC() : ModulePass(ID) {
83     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84   }
85   bool runOnFunction(Function &F);
86   bool runOnModule(Module &M) override {
87     bool Changed = false;
88     for (Function &F : M)
89       Changed |= runOnFunction(F);
90 
91     if (Changed) {
92       // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
93       // returns true for at least one function in the module.  Since at least
94       // one function changed, we know that the precondition is satisfied.
95       stripNonValidAttributes(M);
96     }
97 
98     return Changed;
99   }
100 
101   void getAnalysisUsage(AnalysisUsage &AU) const override {
102     // We add and rewrite a bunch of instructions, but don't really do much
103     // else.  We could in theory preserve a lot more analyses here.
104     AU.addRequired<DominatorTreeWrapperPass>();
105     AU.addRequired<TargetTransformInfoWrapperPass>();
106   }
107 
108   /// The IR fed into RewriteStatepointsForGC may have had attributes implying
109   /// dereferenceability that are no longer valid/correct after
110   /// RewriteStatepointsForGC has run.  This is because semantically, after
111   /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
112   /// heap.  stripNonValidAttributes (conservatively) restores correctness
113   /// by erasing all attributes in the module that externally imply
114   /// dereferenceability.
115   /// Similar reasoning also applies to the noalias attributes. gc.statepoint
116   /// can touch the entire heap including noalias objects.
117   void stripNonValidAttributes(Module &M);
118 
119   // Helpers for stripNonValidAttributes
120   void stripNonValidAttributesFromBody(Function &F);
121   void stripNonValidAttributesFromPrototype(Function &F);
122 };
123 } // namespace
124 
125 char RewriteStatepointsForGC::ID = 0;
126 
127 ModulePass *llvm::createRewriteStatepointsForGCPass() {
128   return new RewriteStatepointsForGC();
129 }
130 
131 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
132                       "Make relocations explicit at statepoints", false, false)
133 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
134 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
135                     "Make relocations explicit at statepoints", false, false)
136 
137 namespace {
138 struct GCPtrLivenessData {
139   /// Values defined in this block.
140   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
141   /// Values used in this block (and thus live); does not included values
142   /// killed within this block.
143   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
144 
145   /// Values live into this basic block (i.e. used by any
146   /// instruction in this basic block or ones reachable from here)
147   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
148 
149   /// Values live out of this basic block (i.e. live into
150   /// any successor block)
151   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
152 };
153 
154 // The type of the internal cache used inside the findBasePointers family
155 // of functions.  From the callers perspective, this is an opaque type and
156 // should not be inspected.
157 //
158 // In the actual implementation this caches two relations:
159 // - The base relation itself (i.e. this pointer is based on that one)
160 // - The base defining value relation (i.e. before base_phi insertion)
161 // Generally, after the execution of a full findBasePointer call, only the
162 // base relation will remain.  Internally, we add a mixture of the two
163 // types, then update all the second type to the first type
164 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
165 typedef DenseSet<Value *> StatepointLiveSetTy;
166 typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
167   RematerializedValueMapTy;
168 
169 struct PartiallyConstructedSafepointRecord {
170   /// The set of values known to be live across this safepoint
171   StatepointLiveSetTy LiveSet;
172 
173   /// Mapping from live pointers to a base-defining-value
174   DenseMap<Value *, Value *> PointerToBase;
175 
176   /// The *new* gc.statepoint instruction itself.  This produces the token
177   /// that normal path gc.relocates and the gc.result are tied to.
178   Instruction *StatepointToken;
179 
180   /// Instruction to which exceptional gc relocates are attached
181   /// Makes it easier to iterate through them during relocationViaAlloca.
182   Instruction *UnwindToken;
183 
184   /// Record live values we are rematerialized instead of relocating.
185   /// They are not included into 'LiveSet' field.
186   /// Maps rematerialized copy to it's original value.
187   RematerializedValueMapTy RematerializedValues;
188 };
189 }
190 
191 static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
192   Optional<OperandBundleUse> DeoptBundle =
193       CS.getOperandBundle(LLVMContext::OB_deopt);
194 
195   if (!DeoptBundle.hasValue()) {
196     assert(AllowStatepointWithNoDeoptInfo &&
197            "Found non-leaf call without deopt info!");
198     return None;
199   }
200 
201   return DeoptBundle.getValue().Inputs;
202 }
203 
204 /// Compute the live-in set for every basic block in the function
205 static void computeLiveInValues(DominatorTree &DT, Function &F,
206                                 GCPtrLivenessData &Data);
207 
208 /// Given results from the dataflow liveness computation, find the set of live
209 /// Values at a particular instruction.
210 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
211                               StatepointLiveSetTy &out);
212 
213 // TODO: Once we can get to the GCStrategy, this becomes
214 // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
215 
216 static bool isGCPointerType(Type *T) {
217   if (auto *PT = dyn_cast<PointerType>(T))
218     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
219     // GC managed heap.  We know that a pointer into this heap needs to be
220     // updated and that no other pointer does.
221     return (1 == PT->getAddressSpace());
222   return false;
223 }
224 
225 // Return true if this type is one which a) is a gc pointer or contains a GC
226 // pointer and b) is of a type this code expects to encounter as a live value.
227 // (The insertion code will assert that a type which matches (a) and not (b)
228 // is not encountered.)
229 static bool isHandledGCPointerType(Type *T) {
230   // We fully support gc pointers
231   if (isGCPointerType(T))
232     return true;
233   // We partially support vectors of gc pointers. The code will assert if it
234   // can't handle something.
235   if (auto VT = dyn_cast<VectorType>(T))
236     if (isGCPointerType(VT->getElementType()))
237       return true;
238   return false;
239 }
240 
241 #ifndef NDEBUG
242 /// Returns true if this type contains a gc pointer whether we know how to
243 /// handle that type or not.
244 static bool containsGCPtrType(Type *Ty) {
245   if (isGCPointerType(Ty))
246     return true;
247   if (VectorType *VT = dyn_cast<VectorType>(Ty))
248     return isGCPointerType(VT->getScalarType());
249   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
250     return containsGCPtrType(AT->getElementType());
251   if (StructType *ST = dyn_cast<StructType>(Ty))
252     return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
253                        containsGCPtrType);
254   return false;
255 }
256 
257 // Returns true if this is a type which a) is a gc pointer or contains a GC
258 // pointer and b) is of a type which the code doesn't expect (i.e. first class
259 // aggregates).  Used to trip assertions.
260 static bool isUnhandledGCPointerType(Type *Ty) {
261   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
262 }
263 #endif
264 
265 static bool order_by_name(Value *a, Value *b) {
266   if (a->hasName() && b->hasName()) {
267     return -1 == a->getName().compare(b->getName());
268   } else if (a->hasName() && !b->hasName()) {
269     return true;
270   } else if (!a->hasName() && b->hasName()) {
271     return false;
272   } else {
273     // Better than nothing, but not stable
274     return a < b;
275   }
276 }
277 
278 // Return the name of the value suffixed with the provided value, or if the
279 // value didn't have a name, the default value specified.
280 static std::string suffixed_name_or(Value *V, StringRef Suffix,
281                                     StringRef DefaultName) {
282   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
283 }
284 
285 // Conservatively identifies any definitions which might be live at the
286 // given instruction. The  analysis is performed immediately before the
287 // given instruction. Values defined by that instruction are not considered
288 // live.  Values used by that instruction are considered live.
289 static void analyzeParsePointLiveness(
290     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
291     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
292   Instruction *inst = CS.getInstruction();
293 
294   StatepointLiveSetTy LiveSet;
295   findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
296 
297   if (PrintLiveSet) {
298     // Note: This output is used by several of the test cases
299     // The order of elements in a set is not stable, put them in a vec and sort
300     // by name
301     SmallVector<Value *, 64> Temp;
302     Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
303     std::sort(Temp.begin(), Temp.end(), order_by_name);
304     errs() << "Live Variables:\n";
305     for (Value *V : Temp)
306       dbgs() << " " << V->getName() << " " << *V << "\n";
307   }
308   if (PrintLiveSetSize) {
309     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
310     errs() << "Number live values: " << LiveSet.size() << "\n";
311   }
312   result.LiveSet = LiveSet;
313 }
314 
315 static bool isKnownBaseResult(Value *V);
316 namespace {
317 /// A single base defining value - An immediate base defining value for an
318 /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
319 /// For instructions which have multiple pointer [vector] inputs or that
320 /// transition between vector and scalar types, there is no immediate base
321 /// defining value.  The 'base defining value' for 'Def' is the transitive
322 /// closure of this relation stopping at the first instruction which has no
323 /// immediate base defining value.  The b.d.v. might itself be a base pointer,
324 /// but it can also be an arbitrary derived pointer.
325 struct BaseDefiningValueResult {
326   /// Contains the value which is the base defining value.
327   Value * const BDV;
328   /// True if the base defining value is also known to be an actual base
329   /// pointer.
330   const bool IsKnownBase;
331   BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
332     : BDV(BDV), IsKnownBase(IsKnownBase) {
333 #ifndef NDEBUG
334     // Check consistency between new and old means of checking whether a BDV is
335     // a base.
336     bool MustBeBase = isKnownBaseResult(BDV);
337     assert(!MustBeBase || MustBeBase == IsKnownBase);
338 #endif
339   }
340 };
341 }
342 
343 static BaseDefiningValueResult findBaseDefiningValue(Value *I);
344 
345 /// Return a base defining value for the 'Index' element of the given vector
346 /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
347 /// 'I'.  As an optimization, this method will try to determine when the
348 /// element is known to already be a base pointer.  If this can be established,
349 /// the second value in the returned pair will be true.  Note that either a
350 /// vector or a pointer typed value can be returned.  For the former, the
351 /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
352 /// If the later, the return pointer is a BDV (or possibly a base) for the
353 /// particular element in 'I'.
354 static BaseDefiningValueResult
355 findBaseDefiningValueOfVector(Value *I) {
356   // Each case parallels findBaseDefiningValue below, see that code for
357   // detailed motivation.
358 
359   if (isa<Argument>(I))
360     // An incoming argument to the function is a base pointer
361     return BaseDefiningValueResult(I, true);
362 
363   if (isa<Constant>(I))
364     // Constant vectors consist only of constant pointers.
365     return BaseDefiningValueResult(I, true);
366 
367   if (isa<LoadInst>(I))
368     return BaseDefiningValueResult(I, true);
369 
370   if (isa<InsertElementInst>(I))
371     // We don't know whether this vector contains entirely base pointers or
372     // not.  To be conservatively correct, we treat it as a BDV and will
373     // duplicate code as needed to construct a parallel vector of bases.
374     return BaseDefiningValueResult(I, false);
375 
376   if (isa<ShuffleVectorInst>(I))
377     // We don't know whether this vector contains entirely base pointers or
378     // not.  To be conservatively correct, we treat it as a BDV and will
379     // duplicate code as needed to construct a parallel vector of bases.
380     // TODO: There a number of local optimizations which could be applied here
381     // for particular sufflevector patterns.
382     return BaseDefiningValueResult(I, false);
383 
384   // A PHI or Select is a base defining value.  The outer findBasePointer
385   // algorithm is responsible for constructing a base value for this BDV.
386   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
387          "unknown vector instruction - no base found for vector element");
388   return BaseDefiningValueResult(I, false);
389 }
390 
391 /// Helper function for findBasePointer - Will return a value which either a)
392 /// defines the base pointer for the input, b) blocks the simple search
393 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
394 /// from pointer to vector type or back.
395 static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
396   assert(I->getType()->isPtrOrPtrVectorTy() &&
397          "Illegal to ask for the base pointer of a non-pointer type");
398 
399   if (I->getType()->isVectorTy())
400     return findBaseDefiningValueOfVector(I);
401 
402   if (isa<Argument>(I))
403     // An incoming argument to the function is a base pointer
404     // We should have never reached here if this argument isn't an gc value
405     return BaseDefiningValueResult(I, true);
406 
407   if (isa<Constant>(I))
408     // We assume that objects with a constant base (e.g. a global) can't move
409     // and don't need to be reported to the collector because they are always
410     // live.  All constants have constant bases.  Besides global references, all
411     // kinds of constants (e.g. undef, constant expressions, null pointers) can
412     // be introduced by the inliner or the optimizer, especially on dynamically
413     // dead paths.  See e.g. test4 in constants.ll.
414     return BaseDefiningValueResult(I, true);
415 
416   if (CastInst *CI = dyn_cast<CastInst>(I)) {
417     Value *Def = CI->stripPointerCasts();
418     // If stripping pointer casts changes the address space there is an
419     // addrspacecast in between.
420     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
421                cast<PointerType>(CI->getType())->getAddressSpace() &&
422            "unsupported addrspacecast");
423     // If we find a cast instruction here, it means we've found a cast which is
424     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
425     // handle int->ptr conversion.
426     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
427     return findBaseDefiningValue(Def);
428   }
429 
430   if (isa<LoadInst>(I))
431     // The value loaded is an gc base itself
432     return BaseDefiningValueResult(I, true);
433 
434 
435   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
436     // The base of this GEP is the base
437     return findBaseDefiningValue(GEP->getPointerOperand());
438 
439   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
440     switch (II->getIntrinsicID()) {
441     default:
442       // fall through to general call handling
443       break;
444     case Intrinsic::experimental_gc_statepoint:
445       llvm_unreachable("statepoints don't produce pointers");
446     case Intrinsic::experimental_gc_relocate: {
447       // Rerunning safepoint insertion after safepoints are already
448       // inserted is not supported.  It could probably be made to work,
449       // but why are you doing this?  There's no good reason.
450       llvm_unreachable("repeat safepoint insertion is not supported");
451     }
452     case Intrinsic::gcroot:
453       // Currently, this mechanism hasn't been extended to work with gcroot.
454       // There's no reason it couldn't be, but I haven't thought about the
455       // implications much.
456       llvm_unreachable(
457           "interaction with the gcroot mechanism is not supported");
458     }
459   }
460   // We assume that functions in the source language only return base
461   // pointers.  This should probably be generalized via attributes to support
462   // both source language and internal functions.
463   if (isa<CallInst>(I) || isa<InvokeInst>(I))
464     return BaseDefiningValueResult(I, true);
465 
466   // I have absolutely no idea how to implement this part yet.  It's not
467   // necessarily hard, I just haven't really looked at it yet.
468   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
469 
470   if (isa<AtomicCmpXchgInst>(I))
471     // A CAS is effectively a atomic store and load combined under a
472     // predicate.  From the perspective of base pointers, we just treat it
473     // like a load.
474     return BaseDefiningValueResult(I, true);
475 
476   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
477                                    "binary ops which don't apply to pointers");
478 
479   // The aggregate ops.  Aggregates can either be in the heap or on the
480   // stack, but in either case, this is simply a field load.  As a result,
481   // this is a defining definition of the base just like a load is.
482   if (isa<ExtractValueInst>(I))
483     return BaseDefiningValueResult(I, true);
484 
485   // We should never see an insert vector since that would require we be
486   // tracing back a struct value not a pointer value.
487   assert(!isa<InsertValueInst>(I) &&
488          "Base pointer for a struct is meaningless");
489 
490   // An extractelement produces a base result exactly when it's input does.
491   // We may need to insert a parallel instruction to extract the appropriate
492   // element out of the base vector corresponding to the input. Given this,
493   // it's analogous to the phi and select case even though it's not a merge.
494   if (isa<ExtractElementInst>(I))
495     // Note: There a lot of obvious peephole cases here.  This are deliberately
496     // handled after the main base pointer inference algorithm to make writing
497     // test cases to exercise that code easier.
498     return BaseDefiningValueResult(I, false);
499 
500   // The last two cases here don't return a base pointer.  Instead, they
501   // return a value which dynamically selects from among several base
502   // derived pointers (each with it's own base potentially).  It's the job of
503   // the caller to resolve these.
504   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
505          "missing instruction case in findBaseDefiningValing");
506   return BaseDefiningValueResult(I, false);
507 }
508 
509 /// Returns the base defining value for this value.
510 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
511   Value *&Cached = Cache[I];
512   if (!Cached) {
513     Cached = findBaseDefiningValue(I).BDV;
514     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
515                  << Cached->getName() << "\n");
516   }
517   assert(Cache[I] != nullptr);
518   return Cached;
519 }
520 
521 /// Return a base pointer for this value if known.  Otherwise, return it's
522 /// base defining value.
523 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
524   Value *Def = findBaseDefiningValueCached(I, Cache);
525   auto Found = Cache.find(Def);
526   if (Found != Cache.end()) {
527     // Either a base-of relation, or a self reference.  Caller must check.
528     return Found->second;
529   }
530   // Only a BDV available
531   return Def;
532 }
533 
534 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
535 /// is it known to be a base pointer?  Or do we need to continue searching.
536 static bool isKnownBaseResult(Value *V) {
537   if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
538       !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
539       !isa<ShuffleVectorInst>(V)) {
540     // no recursion possible
541     return true;
542   }
543   if (isa<Instruction>(V) &&
544       cast<Instruction>(V)->getMetadata("is_base_value")) {
545     // This is a previously inserted base phi or select.  We know
546     // that this is a base value.
547     return true;
548   }
549 
550   // We need to keep searching
551   return false;
552 }
553 
554 namespace {
555 /// Models the state of a single base defining value in the findBasePointer
556 /// algorithm for determining where a new instruction is needed to propagate
557 /// the base of this BDV.
558 class BDVState {
559 public:
560   enum Status { Unknown, Base, Conflict };
561 
562   BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
563     assert(status != Base || b);
564   }
565   explicit BDVState(Value *b) : status(Base), base(b) {}
566   BDVState() : status(Unknown), base(nullptr) {}
567 
568   Status getStatus() const { return status; }
569   Value *getBase() const { return base; }
570 
571   bool isBase() const { return getStatus() == Base; }
572   bool isUnknown() const { return getStatus() == Unknown; }
573   bool isConflict() const { return getStatus() == Conflict; }
574 
575   bool operator==(const BDVState &other) const {
576     return base == other.base && status == other.status;
577   }
578 
579   bool operator!=(const BDVState &other) const { return !(*this == other); }
580 
581   LLVM_DUMP_METHOD
582   void dump() const { print(dbgs()); dbgs() << '\n'; }
583 
584   void print(raw_ostream &OS) const {
585     switch (status) {
586     case Unknown:
587       OS << "U";
588       break;
589     case Base:
590       OS << "B";
591       break;
592     case Conflict:
593       OS << "C";
594       break;
595     };
596     OS << " (" << base << " - "
597        << (base ? base->getName() : "nullptr") << "): ";
598   }
599 
600 private:
601   Status status;
602   AssertingVH<Value> base; // non null only if status == base
603 };
604 }
605 
606 #ifndef NDEBUG
607 static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
608   State.print(OS);
609   return OS;
610 }
611 #endif
612 
613 namespace {
614 // Values of type BDVState form a lattice, and this is a helper
615 // class that implementes the meet operation.  The meat of the meet
616 // operation is implemented in MeetBDVStates::pureMeet
617 class MeetBDVStates {
618 public:
619   /// Initializes the currentResult to the TOP state so that if can be met with
620   /// any other state to produce that state.
621   MeetBDVStates() {}
622 
623   // Destructively meet the current result with the given BDVState
624   void meetWith(BDVState otherState) {
625     currentResult = meet(otherState, currentResult);
626   }
627 
628   BDVState getResult() const { return currentResult; }
629 
630 private:
631   BDVState currentResult;
632 
633   /// Perform a meet operation on two elements of the BDVState lattice.
634   static BDVState meet(BDVState LHS, BDVState RHS) {
635     assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
636            "math is wrong: meet does not commute!");
637     BDVState Result = pureMeet(LHS, RHS);
638     DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
639                  << " produced " << Result << "\n");
640     return Result;
641   }
642 
643   static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
644     switch (stateA.getStatus()) {
645     case BDVState::Unknown:
646       return stateB;
647 
648     case BDVState::Base:
649       assert(stateA.getBase() && "can't be null");
650       if (stateB.isUnknown())
651         return stateA;
652 
653       if (stateB.isBase()) {
654         if (stateA.getBase() == stateB.getBase()) {
655           assert(stateA == stateB && "equality broken!");
656           return stateA;
657         }
658         return BDVState(BDVState::Conflict);
659       }
660       assert(stateB.isConflict() && "only three states!");
661       return BDVState(BDVState::Conflict);
662 
663     case BDVState::Conflict:
664       return stateA;
665     }
666     llvm_unreachable("only three states!");
667   }
668 };
669 }
670 
671 
672 /// For a given value or instruction, figure out what base ptr it's derived
673 /// from.  For gc objects, this is simply itself.  On success, returns a value
674 /// which is the base pointer.  (This is reliable and can be used for
675 /// relocation.)  On failure, returns nullptr.
676 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
677   Value *def = findBaseOrBDV(I, cache);
678 
679   if (isKnownBaseResult(def)) {
680     return def;
681   }
682 
683   // Here's the rough algorithm:
684   // - For every SSA value, construct a mapping to either an actual base
685   //   pointer or a PHI which obscures the base pointer.
686   // - Construct a mapping from PHI to unknown TOP state.  Use an
687   //   optimistic algorithm to propagate base pointer information.  Lattice
688   //   looks like:
689   //   UNKNOWN
690   //   b1 b2 b3 b4
691   //   CONFLICT
692   //   When algorithm terminates, all PHIs will either have a single concrete
693   //   base or be in a conflict state.
694   // - For every conflict, insert a dummy PHI node without arguments.  Add
695   //   these to the base[Instruction] = BasePtr mapping.  For every
696   //   non-conflict, add the actual base.
697   //  - For every conflict, add arguments for the base[a] of each input
698   //   arguments.
699   //
700   // Note: A simpler form of this would be to add the conflict form of all
701   // PHIs without running the optimistic algorithm.  This would be
702   // analogous to pessimistic data flow and would likely lead to an
703   // overall worse solution.
704 
705 #ifndef NDEBUG
706   auto isExpectedBDVType = [](Value *BDV) {
707     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
708            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
709   };
710 #endif
711 
712   // Once populated, will contain a mapping from each potentially non-base BDV
713   // to a lattice value (described above) which corresponds to that BDV.
714   // We use the order of insertion (DFS over the def/use graph) to provide a
715   // stable deterministic ordering for visiting DenseMaps (which are unordered)
716   // below.  This is important for deterministic compilation.
717   MapVector<Value *, BDVState> States;
718 
719   // Recursively fill in all base defining values reachable from the initial
720   // one for which we don't already know a definite base value for
721   /* scope */ {
722     SmallVector<Value*, 16> Worklist;
723     Worklist.push_back(def);
724     States.insert(std::make_pair(def, BDVState()));
725     while (!Worklist.empty()) {
726       Value *Current = Worklist.pop_back_val();
727       assert(!isKnownBaseResult(Current) && "why did it get added?");
728 
729       auto visitIncomingValue = [&](Value *InVal) {
730         Value *Base = findBaseOrBDV(InVal, cache);
731         if (isKnownBaseResult(Base))
732           // Known bases won't need new instructions introduced and can be
733           // ignored safely
734           return;
735         assert(isExpectedBDVType(Base) && "the only non-base values "
736                "we see should be base defining values");
737         if (States.insert(std::make_pair(Base, BDVState())).second)
738           Worklist.push_back(Base);
739       };
740       if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
741         for (Value *InVal : Phi->incoming_values())
742           visitIncomingValue(InVal);
743       } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
744         visitIncomingValue(Sel->getTrueValue());
745         visitIncomingValue(Sel->getFalseValue());
746       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
747         visitIncomingValue(EE->getVectorOperand());
748       } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
749         visitIncomingValue(IE->getOperand(0)); // vector operand
750         visitIncomingValue(IE->getOperand(1)); // scalar operand
751       } else {
752         // There is one known class of instructions we know we don't handle.
753         assert(isa<ShuffleVectorInst>(Current));
754         llvm_unreachable("unimplemented instruction case");
755       }
756     }
757   }
758 
759 #ifndef NDEBUG
760   DEBUG(dbgs() << "States after initialization:\n");
761   for (auto Pair : States) {
762     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
763   }
764 #endif
765 
766   // Return a phi state for a base defining value.  We'll generate a new
767   // base state for known bases and expect to find a cached state otherwise.
768   auto getStateForBDV = [&](Value *baseValue) {
769     if (isKnownBaseResult(baseValue))
770       return BDVState(baseValue);
771     auto I = States.find(baseValue);
772     assert(I != States.end() && "lookup failed!");
773     return I->second;
774   };
775 
776   bool progress = true;
777   while (progress) {
778 #ifndef NDEBUG
779     const size_t oldSize = States.size();
780 #endif
781     progress = false;
782     // We're only changing values in this loop, thus safe to keep iterators.
783     // Since this is computing a fixed point, the order of visit does not
784     // effect the result.  TODO: We could use a worklist here and make this run
785     // much faster.
786     for (auto Pair : States) {
787       Value *BDV = Pair.first;
788       assert(!isKnownBaseResult(BDV) && "why did it get added?");
789 
790       // Given an input value for the current instruction, return a BDVState
791       // instance which represents the BDV of that value.
792       auto getStateForInput = [&](Value *V) mutable {
793         Value *BDV = findBaseOrBDV(V, cache);
794         return getStateForBDV(BDV);
795       };
796 
797       MeetBDVStates calculateMeet;
798       if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
799         calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
800         calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
801       } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
802         for (Value *Val : Phi->incoming_values())
803           calculateMeet.meetWith(getStateForInput(Val));
804       } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
805         // The 'meet' for an extractelement is slightly trivial, but it's still
806         // useful in that it drives us to conflict if our input is.
807         calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
808       } else {
809         // Given there's a inherent type mismatch between the operands, will
810         // *always* produce Conflict.
811         auto *IE = cast<InsertElementInst>(BDV);
812         calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
813         calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
814       }
815 
816       BDVState oldState = States[BDV];
817       BDVState newState = calculateMeet.getResult();
818       if (oldState != newState) {
819         progress = true;
820         States[BDV] = newState;
821       }
822     }
823 
824     assert(oldSize == States.size() &&
825            "fixed point shouldn't be adding any new nodes to state");
826   }
827 
828 #ifndef NDEBUG
829   DEBUG(dbgs() << "States after meet iteration:\n");
830   for (auto Pair : States) {
831     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
832   }
833 #endif
834 
835   // Insert Phis for all conflicts
836   // TODO: adjust naming patterns to avoid this order of iteration dependency
837   for (auto Pair : States) {
838     Instruction *I = cast<Instruction>(Pair.first);
839     BDVState State = Pair.second;
840     assert(!isKnownBaseResult(I) && "why did it get added?");
841     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
842 
843     // extractelement instructions are a bit special in that we may need to
844     // insert an extract even when we know an exact base for the instruction.
845     // The problem is that we need to convert from a vector base to a scalar
846     // base for the particular indice we're interested in.
847     if (State.isBase() && isa<ExtractElementInst>(I) &&
848         isa<VectorType>(State.getBase()->getType())) {
849       auto *EE = cast<ExtractElementInst>(I);
850       // TODO: In many cases, the new instruction is just EE itself.  We should
851       // exploit this, but can't do it here since it would break the invariant
852       // about the BDV not being known to be a base.
853       auto *BaseInst = ExtractElementInst::Create(State.getBase(),
854                                                   EE->getIndexOperand(),
855                                                   "base_ee", EE);
856       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
857       States[I] = BDVState(BDVState::Base, BaseInst);
858     }
859 
860     // Since we're joining a vector and scalar base, they can never be the
861     // same.  As a result, we should always see insert element having reached
862     // the conflict state.
863     if (isa<InsertElementInst>(I)) {
864       assert(State.isConflict());
865     }
866 
867     if (!State.isConflict())
868       continue;
869 
870     /// Create and insert a new instruction which will represent the base of
871     /// the given instruction 'I'.
872     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
873       if (isa<PHINode>(I)) {
874         BasicBlock *BB = I->getParent();
875         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
876         assert(NumPreds > 0 && "how did we reach here");
877         std::string Name = suffixed_name_or(I, ".base", "base_phi");
878         return PHINode::Create(I->getType(), NumPreds, Name, I);
879       } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
880         // The undef will be replaced later
881         UndefValue *Undef = UndefValue::get(Sel->getType());
882         std::string Name = suffixed_name_or(I, ".base", "base_select");
883         return SelectInst::Create(Sel->getCondition(), Undef,
884                                   Undef, Name, Sel);
885       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
886         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
887         std::string Name = suffixed_name_or(I, ".base", "base_ee");
888         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
889                                           EE);
890       } else {
891         auto *IE = cast<InsertElementInst>(I);
892         UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
893         UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
894         std::string Name = suffixed_name_or(I, ".base", "base_ie");
895         return InsertElementInst::Create(VecUndef, ScalarUndef,
896                                          IE->getOperand(2), Name, IE);
897       }
898 
899     };
900     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
901     // Add metadata marking this as a base value
902     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
903     States[I] = BDVState(BDVState::Conflict, BaseInst);
904   }
905 
906   // Returns a instruction which produces the base pointer for a given
907   // instruction.  The instruction is assumed to be an input to one of the BDVs
908   // seen in the inference algorithm above.  As such, we must either already
909   // know it's base defining value is a base, or have inserted a new
910   // instruction to propagate the base of it's BDV and have entered that newly
911   // introduced instruction into the state table.  In either case, we are
912   // assured to be able to determine an instruction which produces it's base
913   // pointer.
914   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
915     Value *BDV = findBaseOrBDV(Input, cache);
916     Value *Base = nullptr;
917     if (isKnownBaseResult(BDV)) {
918       Base = BDV;
919     } else {
920       // Either conflict or base.
921       assert(States.count(BDV));
922       Base = States[BDV].getBase();
923     }
924     assert(Base && "can't be null");
925     // The cast is needed since base traversal may strip away bitcasts
926     if (Base->getType() != Input->getType() &&
927         InsertPt) {
928       Base = new BitCastInst(Base, Input->getType(), "cast",
929                              InsertPt);
930     }
931     return Base;
932   };
933 
934   // Fixup all the inputs of the new PHIs.  Visit order needs to be
935   // deterministic and predictable because we're naming newly created
936   // instructions.
937   for (auto Pair : States) {
938     Instruction *BDV = cast<Instruction>(Pair.first);
939     BDVState State = Pair.second;
940 
941     assert(!isKnownBaseResult(BDV) && "why did it get added?");
942     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
943     if (!State.isConflict())
944       continue;
945 
946     if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
947       PHINode *phi = cast<PHINode>(BDV);
948       unsigned NumPHIValues = phi->getNumIncomingValues();
949       for (unsigned i = 0; i < NumPHIValues; i++) {
950         Value *InVal = phi->getIncomingValue(i);
951         BasicBlock *InBB = phi->getIncomingBlock(i);
952 
953         // If we've already seen InBB, add the same incoming value
954         // we added for it earlier.  The IR verifier requires phi
955         // nodes with multiple entries from the same basic block
956         // to have the same incoming value for each of those
957         // entries.  If we don't do this check here and basephi
958         // has a different type than base, we'll end up adding two
959         // bitcasts (and hence two distinct values) as incoming
960         // values for the same basic block.
961 
962         int blockIndex = basephi->getBasicBlockIndex(InBB);
963         if (blockIndex != -1) {
964           Value *oldBase = basephi->getIncomingValue(blockIndex);
965           basephi->addIncoming(oldBase, InBB);
966 
967 #ifndef NDEBUG
968           Value *Base = getBaseForInput(InVal, nullptr);
969           // In essence this assert states: the only way two
970           // values incoming from the same basic block may be
971           // different is by being different bitcasts of the same
972           // value.  A cleanup that remains TODO is changing
973           // findBaseOrBDV to return an llvm::Value of the correct
974           // type (and still remain pure).  This will remove the
975           // need to add bitcasts.
976           assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
977                  "sanity -- findBaseOrBDV should be pure!");
978 #endif
979           continue;
980         }
981 
982         // Find the instruction which produces the base for each input.  We may
983         // need to insert a bitcast in the incoming block.
984         // TODO: Need to split critical edges if insertion is needed
985         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
986         basephi->addIncoming(Base, InBB);
987       }
988       assert(basephi->getNumIncomingValues() == NumPHIValues);
989     } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
990       SelectInst *Sel = cast<SelectInst>(BDV);
991       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
992       // something more safe and less hacky.
993       for (int i = 1; i <= 2; i++) {
994         Value *InVal = Sel->getOperand(i);
995         // Find the instruction which produces the base for each input.  We may
996         // need to insert a bitcast.
997         Value *Base = getBaseForInput(InVal, BaseSel);
998         BaseSel->setOperand(i, Base);
999       }
1000     } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
1001       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1002       // Find the instruction which produces the base for each input.  We may
1003       // need to insert a bitcast.
1004       Value *Base = getBaseForInput(InVal, BaseEE);
1005       BaseEE->setOperand(0, Base);
1006     } else {
1007       auto *BaseIE = cast<InsertElementInst>(State.getBase());
1008       auto *BdvIE = cast<InsertElementInst>(BDV);
1009       auto UpdateOperand = [&](int OperandIdx) {
1010         Value *InVal = BdvIE->getOperand(OperandIdx);
1011         Value *Base = getBaseForInput(InVal, BaseIE);
1012         BaseIE->setOperand(OperandIdx, Base);
1013       };
1014       UpdateOperand(0); // vector operand
1015       UpdateOperand(1); // scalar operand
1016     }
1017 
1018   }
1019 
1020   // Cache all of our results so we can cheaply reuse them
1021   // NOTE: This is actually two caches: one of the base defining value
1022   // relation and one of the base pointer relation!  FIXME
1023   for (auto Pair : States) {
1024     auto *BDV = Pair.first;
1025     Value *base = Pair.second.getBase();
1026     assert(BDV && base);
1027     assert(!isKnownBaseResult(BDV) && "why did it get added?");
1028 
1029     std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
1030     DEBUG(dbgs() << "Updating base value cache"
1031           << " for: " << BDV->getName()
1032           << " from: " << fromstr
1033           << " to: " << base->getName() << "\n");
1034 
1035     if (cache.count(BDV)) {
1036       assert(isKnownBaseResult(base) &&
1037              "must be something we 'know' is a base pointer");
1038       // Once we transition from the BDV relation being store in the cache to
1039       // the base relation being stored, it must be stable
1040       assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
1041              "base relation should be stable");
1042     }
1043     cache[BDV] = base;
1044   }
1045   assert(cache.count(def));
1046   return cache[def];
1047 }
1048 
1049 // For a set of live pointers (base and/or derived), identify the base
1050 // pointer of the object which they are derived from.  This routine will
1051 // mutate the IR graph as needed to make the 'base' pointer live at the
1052 // definition site of 'derived'.  This ensures that any use of 'derived' can
1053 // also use 'base'.  This may involve the insertion of a number of
1054 // additional PHI nodes.
1055 //
1056 // preconditions: live is a set of pointer type Values
1057 //
1058 // side effects: may insert PHI nodes into the existing CFG, will preserve
1059 // CFG, will not remove or mutate any existing nodes
1060 //
1061 // post condition: PointerToBase contains one (derived, base) pair for every
1062 // pointer in live.  Note that derived can be equal to base if the original
1063 // pointer was a base pointer.
1064 static void
1065 findBasePointers(const StatepointLiveSetTy &live,
1066                  DenseMap<Value *, Value *> &PointerToBase,
1067                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
1068   // For the naming of values inserted to be deterministic - which makes for
1069   // much cleaner and more stable tests - we need to assign an order to the
1070   // live values.  DenseSets do not provide a deterministic order across runs.
1071   SmallVector<Value *, 64> Temp;
1072   Temp.insert(Temp.end(), live.begin(), live.end());
1073   std::sort(Temp.begin(), Temp.end(), order_by_name);
1074   for (Value *ptr : Temp) {
1075     Value *base = findBasePointer(ptr, DVCache);
1076     assert(base && "failed to find base pointer");
1077     PointerToBase[ptr] = base;
1078     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1079             DT->dominates(cast<Instruction>(base)->getParent(),
1080                           cast<Instruction>(ptr)->getParent())) &&
1081            "The base we found better dominate the derived pointer");
1082 
1083     // If you see this trip and like to live really dangerously, the code should
1084     // be correct, just with idioms the verifier can't handle.  You can try
1085     // disabling the verifier at your own substantial risk.
1086     assert(!isa<ConstantPointerNull>(base) &&
1087            "the relocation code needs adjustment to handle the relocation of "
1088            "a null pointer constant without causing false positives in the "
1089            "safepoint ir verifier.");
1090   }
1091 }
1092 
1093 /// Find the required based pointers (and adjust the live set) for the given
1094 /// parse point.
1095 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1096                              const CallSite &CS,
1097                              PartiallyConstructedSafepointRecord &result) {
1098   DenseMap<Value *, Value *> PointerToBase;
1099   findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1100 
1101   if (PrintBasePointers) {
1102     // Note: Need to print these in a stable order since this is checked in
1103     // some tests.
1104     errs() << "Base Pairs (w/o Relocation):\n";
1105     SmallVector<Value *, 64> Temp;
1106     Temp.reserve(PointerToBase.size());
1107     for (auto Pair : PointerToBase) {
1108       Temp.push_back(Pair.first);
1109     }
1110     std::sort(Temp.begin(), Temp.end(), order_by_name);
1111     for (Value *Ptr : Temp) {
1112       Value *Base = PointerToBase[Ptr];
1113       errs() << " derived ";
1114       Ptr->printAsOperand(errs(), false);
1115       errs() << " base ";
1116       Base->printAsOperand(errs(), false);
1117       errs() << "\n";;
1118     }
1119   }
1120 
1121   result.PointerToBase = PointerToBase;
1122 }
1123 
1124 /// Given an updated version of the dataflow liveness results, update the
1125 /// liveset and base pointer maps for the call site CS.
1126 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1127                                   const CallSite &CS,
1128                                   PartiallyConstructedSafepointRecord &result);
1129 
1130 static void recomputeLiveInValues(
1131     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1132     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1133   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1134   // again.  The old values are still live and will help it stabilize quickly.
1135   GCPtrLivenessData RevisedLivenessData;
1136   computeLiveInValues(DT, F, RevisedLivenessData);
1137   for (size_t i = 0; i < records.size(); i++) {
1138     struct PartiallyConstructedSafepointRecord &info = records[i];
1139     const CallSite &CS = toUpdate[i];
1140     recomputeLiveInValues(RevisedLivenessData, CS, info);
1141   }
1142 }
1143 
1144 // When inserting gc.relocate and gc.result calls, we need to ensure there are
1145 // no uses of the original value / return value between the gc.statepoint and
1146 // the gc.relocate / gc.result call.  One case which can arise is a phi node
1147 // starting one of the successor blocks.  We also need to be able to insert the
1148 // gc.relocates only on the path which goes through the statepoint.  We might
1149 // need to split an edge to make this possible.
1150 static BasicBlock *
1151 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1152                             DominatorTree &DT) {
1153   BasicBlock *Ret = BB;
1154   if (!BB->getUniquePredecessor())
1155     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1156 
1157   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1158   // from it
1159   FoldSingleEntryPHINodes(Ret);
1160   assert(!isa<PHINode>(Ret->begin()) &&
1161          "All PHI nodes should have been removed!");
1162 
1163   // At this point, we can safely insert a gc.relocate or gc.result as the first
1164   // instruction in Ret if needed.
1165   return Ret;
1166 }
1167 
1168 // Create new attribute set containing only attributes which can be transferred
1169 // from original call to the safepoint.
1170 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1171   AttributeSet Ret;
1172 
1173   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1174     unsigned Index = AS.getSlotIndex(Slot);
1175 
1176     if (Index == AttributeSet::ReturnIndex ||
1177         Index == AttributeSet::FunctionIndex) {
1178 
1179       for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
1180 
1181         // Do not allow certain attributes - just skip them
1182         // Safepoint can not be read only or read none.
1183         if (Attr.hasAttribute(Attribute::ReadNone) ||
1184             Attr.hasAttribute(Attribute::ReadOnly))
1185           continue;
1186 
1187         // These attributes control the generation of the gc.statepoint call /
1188         // invoke itself; and once the gc.statepoint is in place, they're of no
1189         // use.
1190         if (isStatepointDirectiveAttr(Attr))
1191           continue;
1192 
1193         Ret = Ret.addAttributes(
1194             AS.getContext(), Index,
1195             AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
1196       }
1197     }
1198 
1199     // Just skip parameter attributes for now
1200   }
1201 
1202   return Ret;
1203 }
1204 
1205 /// Helper function to place all gc relocates necessary for the given
1206 /// statepoint.
1207 /// Inputs:
1208 ///   liveVariables - list of variables to be relocated.
1209 ///   liveStart - index of the first live variable.
1210 ///   basePtrs - base pointers.
1211 ///   statepointToken - statepoint instruction to which relocates should be
1212 ///   bound.
1213 ///   Builder - Llvm IR builder to be used to construct new calls.
1214 static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1215                               const int LiveStart,
1216                               ArrayRef<Value *> BasePtrs,
1217                               Instruction *StatepointToken,
1218                               IRBuilder<> Builder) {
1219   if (LiveVariables.empty())
1220     return;
1221 
1222   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1223     auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1224     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1225     size_t Index = std::distance(LiveVec.begin(), ValIt);
1226     assert(Index < LiveVec.size() && "Bug in std::find?");
1227     return Index;
1228   };
1229   Module *M = StatepointToken->getModule();
1230 
1231   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1232   // element type is i8 addrspace(1)*). We originally generated unique
1233   // declarations for each pointer type, but this proved problematic because
1234   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1235   // towards a single unified pointer type anyways, we can just cast everything
1236   // to an i8* of the right address space.  A bitcast is added later to convert
1237   // gc_relocate to the actual value's type.
1238   auto getGCRelocateDecl = [&] (Type *Ty) {
1239     assert(isHandledGCPointerType(Ty));
1240     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1241     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1242     if (auto *VT = dyn_cast<VectorType>(Ty))
1243       NewTy = VectorType::get(NewTy, VT->getNumElements());
1244     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1245                                      {NewTy});
1246   };
1247 
1248   // Lazily populated map from input types to the canonicalized form mentioned
1249   // in the comment above.  This should probably be cached somewhere more
1250   // broadly.
1251   DenseMap<Type*, Value*> TypeToDeclMap;
1252 
1253   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1254     // Generate the gc.relocate call and save the result
1255     Value *BaseIdx =
1256       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
1257     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1258 
1259     Type *Ty = LiveVariables[i]->getType();
1260     if (!TypeToDeclMap.count(Ty))
1261       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1262     Value *GCRelocateDecl = TypeToDeclMap[Ty];
1263 
1264     // only specify a debug name if we can give a useful one
1265     CallInst *Reloc = Builder.CreateCall(
1266         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1267         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1268     // Trick CodeGen into thinking there are lots of free registers at this
1269     // fake call.
1270     Reloc->setCallingConv(CallingConv::Cold);
1271   }
1272 }
1273 
1274 namespace {
1275 
1276 /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
1277 /// avoids having to worry about keeping around dangling pointers to Values.
1278 class DeferredReplacement {
1279   AssertingVH<Instruction> Old;
1280   AssertingVH<Instruction> New;
1281   bool IsDeoptimize = false;
1282 
1283   DeferredReplacement() {}
1284 
1285 public:
1286   static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1287     assert(Old != New && Old && New &&
1288            "Cannot RAUW equal values or to / from null!");
1289 
1290     DeferredReplacement D;
1291     D.Old = Old;
1292     D.New = New;
1293     return D;
1294   }
1295 
1296   static DeferredReplacement createDelete(Instruction *ToErase) {
1297     DeferredReplacement D;
1298     D.Old = ToErase;
1299     return D;
1300   }
1301 
1302   static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1303 #ifndef NDEBUG
1304     auto *F = cast<CallInst>(Old)->getCalledFunction();
1305     assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1306            "Only way to construct a deoptimize deferred replacement");
1307 #endif
1308     DeferredReplacement D;
1309     D.Old = Old;
1310     D.IsDeoptimize = true;
1311     return D;
1312   }
1313 
1314   /// Does the task represented by this instance.
1315   void doReplacement() {
1316     Instruction *OldI = Old;
1317     Instruction *NewI = New;
1318 
1319     assert(OldI != NewI && "Disallowed at construction?!");
1320     assert((!IsDeoptimize || !New) &&
1321            "Deoptimize instrinsics are not replaced!");
1322 
1323     Old = nullptr;
1324     New = nullptr;
1325 
1326     if (NewI)
1327       OldI->replaceAllUsesWith(NewI);
1328 
1329     if (IsDeoptimize) {
1330       // Note: we've inserted instructions, so the call to llvm.deoptimize may
1331       // not necessarilly be followed by the matching return.
1332       auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1333       new UnreachableInst(RI->getContext(), RI);
1334       RI->eraseFromParent();
1335     }
1336 
1337     OldI->eraseFromParent();
1338   }
1339 };
1340 }
1341 
1342 static void
1343 makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1344                            const SmallVectorImpl<Value *> &BasePtrs,
1345                            const SmallVectorImpl<Value *> &LiveVariables,
1346                            PartiallyConstructedSafepointRecord &Result,
1347                            std::vector<DeferredReplacement> &Replacements) {
1348   assert(BasePtrs.size() == LiveVariables.size());
1349 
1350   // Then go ahead and use the builder do actually do the inserts.  We insert
1351   // immediately before the previous instruction under the assumption that all
1352   // arguments will be available here.  We can't insert afterwards since we may
1353   // be replacing a terminator.
1354   Instruction *InsertBefore = CS.getInstruction();
1355   IRBuilder<> Builder(InsertBefore);
1356 
1357   ArrayRef<Value *> GCArgs(LiveVariables);
1358   uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
1359   uint32_t NumPatchBytes = 0;
1360   uint32_t Flags = uint32_t(StatepointFlags::None);
1361 
1362   ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
1363   ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
1364   ArrayRef<Use> TransitionArgs;
1365   if (auto TransitionBundle =
1366       CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1367     Flags |= uint32_t(StatepointFlags::GCTransition);
1368     TransitionArgs = TransitionBundle->Inputs;
1369   }
1370 
1371   // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1372   // with a return value, we lower then as never returning calls to
1373   // __llvm_deoptimize that are followed by unreachable to get better codegen.
1374   bool IsDeoptimize = false;
1375 
1376   StatepointDirectives SD =
1377       parseStatepointDirectivesFromAttrs(CS.getAttributes());
1378   if (SD.NumPatchBytes)
1379     NumPatchBytes = *SD.NumPatchBytes;
1380   if (SD.StatepointID)
1381     StatepointID = *SD.StatepointID;
1382 
1383   Value *CallTarget = CS.getCalledValue();
1384   if (Function *F = dyn_cast<Function>(CallTarget)) {
1385     if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
1386       // Calls to llvm.experimental.deoptimize are lowered to calls the the
1387       // __llvm_deoptimize symbol.  We want to resolve this now, since the
1388       // verifier does not allow taking the address of an intrinsic function.
1389 
1390       SmallVector<Type *, 8> DomainTy;
1391       for (Value *Arg : CallArgs)
1392         DomainTy.push_back(Arg->getType());
1393       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1394                                     /* isVarArg = */ false);
1395 
1396       // Note: CallTarget can be a bitcast instruction of a symbol if there are
1397       // calls to @llvm.experimental.deoptimize with different argument types in
1398       // the same module.  This is fine -- we assume the frontend knew what it
1399       // was doing when generating this kind of IR.
1400       CallTarget =
1401           F->getParent()->getOrInsertFunction("__llvm_deoptimize", FTy);
1402 
1403       IsDeoptimize = true;
1404     }
1405   }
1406 
1407   // Create the statepoint given all the arguments
1408   Instruction *Token = nullptr;
1409   AttributeSet ReturnAttrs;
1410   if (CS.isCall()) {
1411     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
1412     CallInst *Call = Builder.CreateGCStatepointCall(
1413         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1414         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1415 
1416     Call->setTailCall(ToReplace->isTailCall());
1417     Call->setCallingConv(ToReplace->getCallingConv());
1418 
1419     // Currently we will fail on parameter attributes and on certain
1420     // function attributes.
1421     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
1422     // In case if we can handle this set of attributes - set up function attrs
1423     // directly on statepoint and return attrs later for gc_result intrinsic.
1424     Call->setAttributes(NewAttrs.getFnAttributes());
1425     ReturnAttrs = NewAttrs.getRetAttributes();
1426 
1427     Token = Call;
1428 
1429     // Put the following gc_result and gc_relocate calls immediately after the
1430     // the old call (which we're about to delete)
1431     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1432     Builder.SetInsertPoint(ToReplace->getNextNode());
1433     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1434   } else {
1435     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1436 
1437     // Insert the new invoke into the old block.  We'll remove the old one in a
1438     // moment at which point this will become the new terminator for the
1439     // original block.
1440     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1441         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1442         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1443         GCArgs, "statepoint_token");
1444 
1445     Invoke->setCallingConv(ToReplace->getCallingConv());
1446 
1447     // Currently we will fail on parameter attributes and on certain
1448     // function attributes.
1449     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
1450     // In case if we can handle this set of attributes - set up function attrs
1451     // directly on statepoint and return attrs later for gc_result intrinsic.
1452     Invoke->setAttributes(NewAttrs.getFnAttributes());
1453     ReturnAttrs = NewAttrs.getRetAttributes();
1454 
1455     Token = Invoke;
1456 
1457     // Generate gc relocates in exceptional path
1458     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1459     assert(!isa<PHINode>(UnwindBlock->begin()) &&
1460            UnwindBlock->getUniquePredecessor() &&
1461            "can't safely insert in this block!");
1462 
1463     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
1464     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1465 
1466     // Attach exceptional gc relocates to the landingpad.
1467     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1468     Result.UnwindToken = ExceptionalToken;
1469 
1470     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
1471     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1472                       Builder);
1473 
1474     // Generate gc relocates and returns for normal block
1475     BasicBlock *NormalDest = ToReplace->getNormalDest();
1476     assert(!isa<PHINode>(NormalDest->begin()) &&
1477            NormalDest->getUniquePredecessor() &&
1478            "can't safely insert in this block!");
1479 
1480     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1481 
1482     // gc relocates will be generated later as if it were regular call
1483     // statepoint
1484   }
1485   assert(Token && "Should be set in one of the above branches!");
1486 
1487   if (IsDeoptimize) {
1488     // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1489     // transform the tail-call like structure to a call to a void function
1490     // followed by unreachable to get better codegen.
1491     Replacements.push_back(
1492         DeferredReplacement::createDeoptimizeReplacement(CS.getInstruction()));
1493   } else {
1494     Token->setName("statepoint_token");
1495     if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1496       StringRef Name =
1497           CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1498       CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1499       GCResult->setAttributes(CS.getAttributes().getRetAttributes());
1500 
1501       // We cannot RAUW or delete CS.getInstruction() because it could be in the
1502       // live set of some other safepoint, in which case that safepoint's
1503       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1504       // llvm::Instruction.  Instead, we defer the replacement and deletion to
1505       // after the live sets have been made explicit in the IR, and we no longer
1506       // have raw pointers to worry about.
1507       Replacements.emplace_back(
1508           DeferredReplacement::createRAUW(CS.getInstruction(), GCResult));
1509     } else {
1510       Replacements.emplace_back(
1511           DeferredReplacement::createDelete(CS.getInstruction()));
1512     }
1513   }
1514 
1515   Result.StatepointToken = Token;
1516 
1517   // Second, create a gc.relocate for every live variable
1518   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
1519   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1520 }
1521 
1522 static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1523                            SmallVectorImpl<Value *> &LiveVec) {
1524   assert(BaseVec.size() == LiveVec.size());
1525 
1526   struct BaseDerivedPair {
1527     Value *Base;
1528     Value *Derived;
1529   };
1530 
1531   SmallVector<BaseDerivedPair, 64> NameOrdering;
1532   NameOrdering.reserve(BaseVec.size());
1533 
1534   for (size_t i = 0, e = BaseVec.size(); i < e; i++)
1535     NameOrdering.push_back({BaseVec[i], LiveVec[i]});
1536 
1537   std::sort(NameOrdering.begin(), NameOrdering.end(),
1538             [](const BaseDerivedPair &L, const BaseDerivedPair &R) {
1539               return L.Derived->getName() < R.Derived->getName();
1540             });
1541 
1542   for (size_t i = 0; i < BaseVec.size(); i++) {
1543     BaseVec[i] = NameOrdering[i].Base;
1544     LiveVec[i] = NameOrdering[i].Derived;
1545   }
1546 }
1547 
1548 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1549 // which make the relocations happening at this safepoint explicit.
1550 //
1551 // WARNING: Does not do any fixup to adjust users of the original live
1552 // values.  That's the callers responsibility.
1553 static void
1554 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
1555                        PartiallyConstructedSafepointRecord &Result,
1556                        std::vector<DeferredReplacement> &Replacements) {
1557   const auto &LiveSet = Result.LiveSet;
1558   const auto &PointerToBase = Result.PointerToBase;
1559 
1560   // Convert to vector for efficient cross referencing.
1561   SmallVector<Value *, 64> BaseVec, LiveVec;
1562   LiveVec.reserve(LiveSet.size());
1563   BaseVec.reserve(LiveSet.size());
1564   for (Value *L : LiveSet) {
1565     LiveVec.push_back(L);
1566     assert(PointerToBase.count(L));
1567     Value *Base = PointerToBase.find(L)->second;
1568     BaseVec.push_back(Base);
1569   }
1570   assert(LiveVec.size() == BaseVec.size());
1571 
1572   // To make the output IR slightly more stable (for use in diffs), ensure a
1573   // fixed order of the values in the safepoint (by sorting the value name).
1574   // The order is otherwise meaningless.
1575   StabilizeOrder(BaseVec, LiveVec);
1576 
1577   // Do the actual rewriting and delete the old statepoint
1578   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1579 }
1580 
1581 // Helper function for the relocationViaAlloca.
1582 //
1583 // It receives iterator to the statepoint gc relocates and emits a store to the
1584 // assigned location (via allocaMap) for the each one of them.  It adds the
1585 // visited values into the visitedLiveValues set, which we will later use them
1586 // for sanity checking.
1587 static void
1588 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1589                        DenseMap<Value *, Value *> &AllocaMap,
1590                        DenseSet<Value *> &VisitedLiveValues) {
1591 
1592   for (User *U : GCRelocs) {
1593     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1594     if (!Relocate)
1595       continue;
1596 
1597     Value *OriginalValue = Relocate->getDerivedPtr();
1598     assert(AllocaMap.count(OriginalValue));
1599     Value *Alloca = AllocaMap[OriginalValue];
1600 
1601     // Emit store into the related alloca
1602     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1603     // the correct type according to alloca.
1604     assert(Relocate->getNextNode() &&
1605            "Should always have one since it's not a terminator");
1606     IRBuilder<> Builder(Relocate->getNextNode());
1607     Value *CastedRelocatedValue =
1608       Builder.CreateBitCast(Relocate,
1609                             cast<AllocaInst>(Alloca)->getAllocatedType(),
1610                             suffixed_name_or(Relocate, ".casted", ""));
1611 
1612     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1613     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1614 
1615 #ifndef NDEBUG
1616     VisitedLiveValues.insert(OriginalValue);
1617 #endif
1618   }
1619 }
1620 
1621 // Helper function for the "relocationViaAlloca". Similar to the
1622 // "insertRelocationStores" but works for rematerialized values.
1623 static void insertRematerializationStores(
1624     const RematerializedValueMapTy &RematerializedValues,
1625     DenseMap<Value *, Value *> &AllocaMap,
1626     DenseSet<Value *> &VisitedLiveValues) {
1627 
1628   for (auto RematerializedValuePair: RematerializedValues) {
1629     Instruction *RematerializedValue = RematerializedValuePair.first;
1630     Value *OriginalValue = RematerializedValuePair.second;
1631 
1632     assert(AllocaMap.count(OriginalValue) &&
1633            "Can not find alloca for rematerialized value");
1634     Value *Alloca = AllocaMap[OriginalValue];
1635 
1636     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1637     Store->insertAfter(RematerializedValue);
1638 
1639 #ifndef NDEBUG
1640     VisitedLiveValues.insert(OriginalValue);
1641 #endif
1642   }
1643 }
1644 
1645 /// Do all the relocation update via allocas and mem2reg
1646 static void relocationViaAlloca(
1647     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1648     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1649 #ifndef NDEBUG
1650   // record initial number of (static) allocas; we'll check we have the same
1651   // number when we get done.
1652   int InitialAllocaNum = 0;
1653   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1654        I++)
1655     if (isa<AllocaInst>(*I))
1656       InitialAllocaNum++;
1657 #endif
1658 
1659   // TODO-PERF: change data structures, reserve
1660   DenseMap<Value *, Value *> AllocaMap;
1661   SmallVector<AllocaInst *, 200> PromotableAllocas;
1662   // Used later to chack that we have enough allocas to store all values
1663   std::size_t NumRematerializedValues = 0;
1664   PromotableAllocas.reserve(Live.size());
1665 
1666   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1667   // "PromotableAllocas"
1668   auto emitAllocaFor = [&](Value *LiveValue) {
1669     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1670                                         F.getEntryBlock().getFirstNonPHI());
1671     AllocaMap[LiveValue] = Alloca;
1672     PromotableAllocas.push_back(Alloca);
1673   };
1674 
1675   // Emit alloca for each live gc pointer
1676   for (Value *V : Live)
1677     emitAllocaFor(V);
1678 
1679   // Emit allocas for rematerialized values
1680   for (const auto &Info : Records)
1681     for (auto RematerializedValuePair : Info.RematerializedValues) {
1682       Value *OriginalValue = RematerializedValuePair.second;
1683       if (AllocaMap.count(OriginalValue) != 0)
1684         continue;
1685 
1686       emitAllocaFor(OriginalValue);
1687       ++NumRematerializedValues;
1688     }
1689 
1690   // The next two loops are part of the same conceptual operation.  We need to
1691   // insert a store to the alloca after the original def and at each
1692   // redefinition.  We need to insert a load before each use.  These are split
1693   // into distinct loops for performance reasons.
1694 
1695   // Update gc pointer after each statepoint: either store a relocated value or
1696   // null (if no relocated value was found for this gc pointer and it is not a
1697   // gc_result).  This must happen before we update the statepoint with load of
1698   // alloca otherwise we lose the link between statepoint and old def.
1699   for (const auto &Info : Records) {
1700     Value *Statepoint = Info.StatepointToken;
1701 
1702     // This will be used for consistency check
1703     DenseSet<Value *> VisitedLiveValues;
1704 
1705     // Insert stores for normal statepoint gc relocates
1706     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1707 
1708     // In case if it was invoke statepoint
1709     // we will insert stores for exceptional path gc relocates.
1710     if (isa<InvokeInst>(Statepoint)) {
1711       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1712                              VisitedLiveValues);
1713     }
1714 
1715     // Do similar thing with rematerialized values
1716     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1717                                   VisitedLiveValues);
1718 
1719     if (ClobberNonLive) {
1720       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1721       // the gc.statepoint.  This will turn some subtle GC problems into
1722       // slightly easier to debug SEGVs.  Note that on large IR files with
1723       // lots of gc.statepoints this is extremely costly both memory and time
1724       // wise.
1725       SmallVector<AllocaInst *, 64> ToClobber;
1726       for (auto Pair : AllocaMap) {
1727         Value *Def = Pair.first;
1728         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1729 
1730         // This value was relocated
1731         if (VisitedLiveValues.count(Def)) {
1732           continue;
1733         }
1734         ToClobber.push_back(Alloca);
1735       }
1736 
1737       auto InsertClobbersAt = [&](Instruction *IP) {
1738         for (auto *AI : ToClobber) {
1739           auto PT = cast<PointerType>(AI->getAllocatedType());
1740           Constant *CPN = ConstantPointerNull::get(PT);
1741           StoreInst *Store = new StoreInst(CPN, AI);
1742           Store->insertBefore(IP);
1743         }
1744       };
1745 
1746       // Insert the clobbering stores.  These may get intermixed with the
1747       // gc.results and gc.relocates, but that's fine.
1748       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1749         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1750         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1751       } else {
1752         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1753       }
1754     }
1755   }
1756 
1757   // Update use with load allocas and add store for gc_relocated.
1758   for (auto Pair : AllocaMap) {
1759     Value *Def = Pair.first;
1760     Value *Alloca = Pair.second;
1761 
1762     // We pre-record the uses of allocas so that we dont have to worry about
1763     // later update that changes the user information..
1764 
1765     SmallVector<Instruction *, 20> Uses;
1766     // PERF: trade a linear scan for repeated reallocation
1767     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1768     for (User *U : Def->users()) {
1769       if (!isa<ConstantExpr>(U)) {
1770         // If the def has a ConstantExpr use, then the def is either a
1771         // ConstantExpr use itself or null.  In either case
1772         // (recursively in the first, directly in the second), the oop
1773         // it is ultimately dependent on is null and this particular
1774         // use does not need to be fixed up.
1775         Uses.push_back(cast<Instruction>(U));
1776       }
1777     }
1778 
1779     std::sort(Uses.begin(), Uses.end());
1780     auto Last = std::unique(Uses.begin(), Uses.end());
1781     Uses.erase(Last, Uses.end());
1782 
1783     for (Instruction *Use : Uses) {
1784       if (isa<PHINode>(Use)) {
1785         PHINode *Phi = cast<PHINode>(Use);
1786         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1787           if (Def == Phi->getIncomingValue(i)) {
1788             LoadInst *Load = new LoadInst(
1789                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1790             Phi->setIncomingValue(i, Load);
1791           }
1792         }
1793       } else {
1794         LoadInst *Load = new LoadInst(Alloca, "", Use);
1795         Use->replaceUsesOfWith(Def, Load);
1796       }
1797     }
1798 
1799     // Emit store for the initial gc value.  Store must be inserted after load,
1800     // otherwise store will be in alloca's use list and an extra load will be
1801     // inserted before it.
1802     StoreInst *Store = new StoreInst(Def, Alloca);
1803     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1804       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1805         // InvokeInst is a TerminatorInst so the store need to be inserted
1806         // into its normal destination block.
1807         BasicBlock *NormalDest = Invoke->getNormalDest();
1808         Store->insertBefore(NormalDest->getFirstNonPHI());
1809       } else {
1810         assert(!Inst->isTerminator() &&
1811                "The only TerminatorInst that can produce a value is "
1812                "InvokeInst which is handled above.");
1813         Store->insertAfter(Inst);
1814       }
1815     } else {
1816       assert(isa<Argument>(Def));
1817       Store->insertAfter(cast<Instruction>(Alloca));
1818     }
1819   }
1820 
1821   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1822          "we must have the same allocas with lives");
1823   if (!PromotableAllocas.empty()) {
1824     // Apply mem2reg to promote alloca to SSA
1825     PromoteMemToReg(PromotableAllocas, DT);
1826   }
1827 
1828 #ifndef NDEBUG
1829   for (auto &I : F.getEntryBlock())
1830     if (isa<AllocaInst>(I))
1831       InitialAllocaNum--;
1832   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1833 #endif
1834 }
1835 
1836 /// Implement a unique function which doesn't require we sort the input
1837 /// vector.  Doing so has the effect of changing the output of a couple of
1838 /// tests in ways which make them less useful in testing fused safepoints.
1839 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1840   SmallSet<T, 8> Seen;
1841   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1842               return !Seen.insert(V).second;
1843             }), Vec.end());
1844 }
1845 
1846 /// Insert holders so that each Value is obviously live through the entire
1847 /// lifetime of the call.
1848 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1849                                  SmallVectorImpl<CallInst *> &Holders) {
1850   if (Values.empty())
1851     // No values to hold live, might as well not insert the empty holder
1852     return;
1853 
1854   Module *M = CS.getInstruction()->getModule();
1855   // Use a dummy vararg function to actually hold the values live
1856   Function *Func = cast<Function>(M->getOrInsertFunction(
1857       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1858   if (CS.isCall()) {
1859     // For call safepoints insert dummy calls right after safepoint
1860     Holders.push_back(CallInst::Create(Func, Values, "",
1861                                        &*++CS.getInstruction()->getIterator()));
1862     return;
1863   }
1864   // For invoke safepooints insert dummy calls both in normal and
1865   // exceptional destination blocks
1866   auto *II = cast<InvokeInst>(CS.getInstruction());
1867   Holders.push_back(CallInst::Create(
1868       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1869   Holders.push_back(CallInst::Create(
1870       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1871 }
1872 
1873 static void findLiveReferences(
1874     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1875     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1876   GCPtrLivenessData OriginalLivenessData;
1877   computeLiveInValues(DT, F, OriginalLivenessData);
1878   for (size_t i = 0; i < records.size(); i++) {
1879     struct PartiallyConstructedSafepointRecord &info = records[i];
1880     const CallSite &CS = toUpdate[i];
1881     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1882   }
1883 }
1884 
1885 // Helper function for the "rematerializeLiveValues". It walks use chain
1886 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1887 // values are visited (currently it is GEP's and casts). Returns true if it
1888 // successfully reached "BaseValue" and false otherwise.
1889 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1890 // recorded.
1891 static bool findRematerializableChainToBasePointer(
1892   SmallVectorImpl<Instruction*> &ChainToBase,
1893   Value *CurrentValue, Value *BaseValue) {
1894 
1895   // We have found a base value
1896   if (CurrentValue == BaseValue) {
1897     return true;
1898   }
1899 
1900   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1901     ChainToBase.push_back(GEP);
1902     return findRematerializableChainToBasePointer(ChainToBase,
1903                                                   GEP->getPointerOperand(),
1904                                                   BaseValue);
1905   }
1906 
1907   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1908     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1909       return false;
1910 
1911     ChainToBase.push_back(CI);
1912     return findRematerializableChainToBasePointer(ChainToBase,
1913                                                   CI->getOperand(0), BaseValue);
1914   }
1915 
1916   // Not supported instruction in the chain
1917   return false;
1918 }
1919 
1920 // Helper function for the "rematerializeLiveValues". Compute cost of the use
1921 // chain we are going to rematerialize.
1922 static unsigned
1923 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1924                        TargetTransformInfo &TTI) {
1925   unsigned Cost = 0;
1926 
1927   for (Instruction *Instr : Chain) {
1928     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1929       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1930              "non noop cast is found during rematerialization");
1931 
1932       Type *SrcTy = CI->getOperand(0)->getType();
1933       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1934 
1935     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1936       // Cost of the address calculation
1937       Type *ValTy = GEP->getSourceElementType();
1938       Cost += TTI.getAddressComputationCost(ValTy);
1939 
1940       // And cost of the GEP itself
1941       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1942       //       allowed for the external usage)
1943       if (!GEP->hasAllConstantIndices())
1944         Cost += 2;
1945 
1946     } else {
1947       llvm_unreachable("unsupported instruciton type during rematerialization");
1948     }
1949   }
1950 
1951   return Cost;
1952 }
1953 
1954 // From the statepoint live set pick values that are cheaper to recompute then
1955 // to relocate. Remove this values from the live set, rematerialize them after
1956 // statepoint and record them in "Info" structure. Note that similar to
1957 // relocated values we don't do any user adjustments here.
1958 static void rematerializeLiveValues(CallSite CS,
1959                                     PartiallyConstructedSafepointRecord &Info,
1960                                     TargetTransformInfo &TTI) {
1961   const unsigned int ChainLengthThreshold = 10;
1962 
1963   // Record values we are going to delete from this statepoint live set.
1964   // We can not di this in following loop due to iterator invalidation.
1965   SmallVector<Value *, 32> LiveValuesToBeDeleted;
1966 
1967   for (Value *LiveValue: Info.LiveSet) {
1968     // For each live pointer find it's defining chain
1969     SmallVector<Instruction *, 3> ChainToBase;
1970     assert(Info.PointerToBase.count(LiveValue));
1971     bool FoundChain =
1972       findRematerializableChainToBasePointer(ChainToBase,
1973                                              LiveValue,
1974                                              Info.PointerToBase[LiveValue]);
1975     // Nothing to do, or chain is too long
1976     if (!FoundChain ||
1977         ChainToBase.size() == 0 ||
1978         ChainToBase.size() > ChainLengthThreshold)
1979       continue;
1980 
1981     // Compute cost of this chain
1982     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1983     // TODO: We can also account for cases when we will be able to remove some
1984     //       of the rematerialized values by later optimization passes. I.e if
1985     //       we rematerialized several intersecting chains. Or if original values
1986     //       don't have any uses besides this statepoint.
1987 
1988     // For invokes we need to rematerialize each chain twice - for normal and
1989     // for unwind basic blocks. Model this by multiplying cost by two.
1990     if (CS.isInvoke()) {
1991       Cost *= 2;
1992     }
1993     // If it's too expensive - skip it
1994     if (Cost >= RematerializationThreshold)
1995       continue;
1996 
1997     // Remove value from the live set
1998     LiveValuesToBeDeleted.push_back(LiveValue);
1999 
2000     // Clone instructions and record them inside "Info" structure
2001 
2002     // Walk backwards to visit top-most instructions first
2003     std::reverse(ChainToBase.begin(), ChainToBase.end());
2004 
2005     // Utility function which clones all instructions from "ChainToBase"
2006     // and inserts them before "InsertBefore". Returns rematerialized value
2007     // which should be used after statepoint.
2008     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2009       Instruction *LastClonedValue = nullptr;
2010       Instruction *LastValue = nullptr;
2011       for (Instruction *Instr: ChainToBase) {
2012         // Only GEP's and casts are suported as we need to be careful to not
2013         // introduce any new uses of pointers not in the liveset.
2014         // Note that it's fine to introduce new uses of pointers which were
2015         // otherwise not used after this statepoint.
2016         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2017 
2018         Instruction *ClonedValue = Instr->clone();
2019         ClonedValue->insertBefore(InsertBefore);
2020         ClonedValue->setName(Instr->getName() + ".remat");
2021 
2022         // If it is not first instruction in the chain then it uses previously
2023         // cloned value. We should update it to use cloned value.
2024         if (LastClonedValue) {
2025           assert(LastValue);
2026           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2027 #ifndef NDEBUG
2028           // Assert that cloned instruction does not use any instructions from
2029           // this chain other than LastClonedValue
2030           for (auto OpValue : ClonedValue->operand_values()) {
2031             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2032                        ChainToBase.end() &&
2033                    "incorrect use in rematerialization chain");
2034           }
2035 #endif
2036         }
2037 
2038         LastClonedValue = ClonedValue;
2039         LastValue = Instr;
2040       }
2041       assert(LastClonedValue);
2042       return LastClonedValue;
2043     };
2044 
2045     // Different cases for calls and invokes. For invokes we need to clone
2046     // instructions both on normal and unwind path.
2047     if (CS.isCall()) {
2048       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2049       assert(InsertBefore);
2050       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2051       Info.RematerializedValues[RematerializedValue] = LiveValue;
2052     } else {
2053       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2054 
2055       Instruction *NormalInsertBefore =
2056           &*Invoke->getNormalDest()->getFirstInsertionPt();
2057       Instruction *UnwindInsertBefore =
2058           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2059 
2060       Instruction *NormalRematerializedValue =
2061           rematerializeChain(NormalInsertBefore);
2062       Instruction *UnwindRematerializedValue =
2063           rematerializeChain(UnwindInsertBefore);
2064 
2065       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2066       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2067     }
2068   }
2069 
2070   // Remove rematerializaed values from the live set
2071   for (auto LiveValue: LiveValuesToBeDeleted) {
2072     Info.LiveSet.erase(LiveValue);
2073   }
2074 }
2075 
2076 static bool insertParsePoints(Function &F, DominatorTree &DT,
2077                               TargetTransformInfo &TTI,
2078                               SmallVectorImpl<CallSite> &ToUpdate) {
2079 #ifndef NDEBUG
2080   // sanity check the input
2081   std::set<CallSite> Uniqued;
2082   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2083   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2084 
2085   for (CallSite CS : ToUpdate)
2086     assert(CS.getInstruction()->getFunction() == &F);
2087 #endif
2088 
2089   // When inserting gc.relocates for invokes, we need to be able to insert at
2090   // the top of the successor blocks.  See the comment on
2091   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2092   // may restructure the CFG.
2093   for (CallSite CS : ToUpdate) {
2094     if (!CS.isInvoke())
2095       continue;
2096     auto *II = cast<InvokeInst>(CS.getInstruction());
2097     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2098     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2099   }
2100 
2101   // A list of dummy calls added to the IR to keep various values obviously
2102   // live in the IR.  We'll remove all of these when done.
2103   SmallVector<CallInst *, 64> Holders;
2104 
2105   // Insert a dummy call with all of the arguments to the vm_state we'll need
2106   // for the actual safepoint insertion.  This ensures reference arguments in
2107   // the deopt argument list are considered live through the safepoint (and
2108   // thus makes sure they get relocated.)
2109   for (CallSite CS : ToUpdate) {
2110     SmallVector<Value *, 64> DeoptValues;
2111 
2112     for (Value *Arg : GetDeoptBundleOperands(CS)) {
2113       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2114              "support for FCA unimplemented");
2115       if (isHandledGCPointerType(Arg->getType()))
2116         DeoptValues.push_back(Arg);
2117     }
2118 
2119     insertUseHolderAfter(CS, DeoptValues, Holders);
2120   }
2121 
2122   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2123 
2124   // A) Identify all gc pointers which are statically live at the given call
2125   // site.
2126   findLiveReferences(F, DT, ToUpdate, Records);
2127 
2128   // B) Find the base pointers for each live pointer
2129   /* scope for caching */ {
2130     // Cache the 'defining value' relation used in the computation and
2131     // insertion of base phis and selects.  This ensures that we don't insert
2132     // large numbers of duplicate base_phis.
2133     DefiningValueMapTy DVCache;
2134 
2135     for (size_t i = 0; i < Records.size(); i++) {
2136       PartiallyConstructedSafepointRecord &info = Records[i];
2137       findBasePointers(DT, DVCache, ToUpdate[i], info);
2138     }
2139   } // end of cache scope
2140 
2141   // The base phi insertion logic (for any safepoint) may have inserted new
2142   // instructions which are now live at some safepoint.  The simplest such
2143   // example is:
2144   // loop:
2145   //   phi a  <-- will be a new base_phi here
2146   //   safepoint 1 <-- that needs to be live here
2147   //   gep a + 1
2148   //   safepoint 2
2149   //   br loop
2150   // We insert some dummy calls after each safepoint to definitely hold live
2151   // the base pointers which were identified for that safepoint.  We'll then
2152   // ask liveness for _every_ base inserted to see what is now live.  Then we
2153   // remove the dummy calls.
2154   Holders.reserve(Holders.size() + Records.size());
2155   for (size_t i = 0; i < Records.size(); i++) {
2156     PartiallyConstructedSafepointRecord &Info = Records[i];
2157 
2158     SmallVector<Value *, 128> Bases;
2159     for (auto Pair : Info.PointerToBase)
2160       Bases.push_back(Pair.second);
2161 
2162     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2163   }
2164 
2165   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2166   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2167   // not the key issue.
2168   recomputeLiveInValues(F, DT, ToUpdate, Records);
2169 
2170   if (PrintBasePointers) {
2171     for (auto &Info : Records) {
2172       errs() << "Base Pairs: (w/Relocation)\n";
2173       for (auto Pair : Info.PointerToBase) {
2174         errs() << " derived ";
2175         Pair.first->printAsOperand(errs(), false);
2176         errs() << " base ";
2177         Pair.second->printAsOperand(errs(), false);
2178         errs() << "\n";
2179       }
2180     }
2181   }
2182 
2183   // It is possible that non-constant live variables have a constant base.  For
2184   // example, a GEP with a variable offset from a global.  In this case we can
2185   // remove it from the liveset.  We already don't add constants to the liveset
2186   // because we assume they won't move at runtime and the GC doesn't need to be
2187   // informed about them.  The same reasoning applies if the base is constant.
2188   // Note that the relocation placement code relies on this filtering for
2189   // correctness as it expects the base to be in the liveset, which isn't true
2190   // if the base is constant.
2191   for (auto &Info : Records)
2192     for (auto &BasePair : Info.PointerToBase)
2193       if (isa<Constant>(BasePair.second))
2194         Info.LiveSet.erase(BasePair.first);
2195 
2196   for (CallInst *CI : Holders)
2197     CI->eraseFromParent();
2198 
2199   Holders.clear();
2200 
2201   // In order to reduce live set of statepoint we might choose to rematerialize
2202   // some values instead of relocating them. This is purely an optimization and
2203   // does not influence correctness.
2204   for (size_t i = 0; i < Records.size(); i++)
2205     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2206 
2207   // We need this to safely RAUW and delete call or invoke return values that
2208   // may themselves be live over a statepoint.  For details, please see usage in
2209   // makeStatepointExplicitImpl.
2210   std::vector<DeferredReplacement> Replacements;
2211 
2212   // Now run through and replace the existing statepoints with new ones with
2213   // the live variables listed.  We do not yet update uses of the values being
2214   // relocated. We have references to live variables that need to
2215   // survive to the last iteration of this loop.  (By construction, the
2216   // previous statepoint can not be a live variable, thus we can and remove
2217   // the old statepoint calls as we go.)
2218   for (size_t i = 0; i < Records.size(); i++)
2219     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
2220 
2221   ToUpdate.clear(); // prevent accident use of invalid CallSites
2222 
2223   for (auto &PR : Replacements)
2224     PR.doReplacement();
2225 
2226   Replacements.clear();
2227 
2228   for (auto &Info : Records) {
2229     // These live sets may contain state Value pointers, since we replaced calls
2230     // with operand bundles with calls wrapped in gc.statepoint, and some of
2231     // those calls may have been def'ing live gc pointers.  Clear these out to
2232     // avoid accidentally using them.
2233     //
2234     // TODO: We should create a separate data structure that does not contain
2235     // these live sets, and migrate to using that data structure from this point
2236     // onward.
2237     Info.LiveSet.clear();
2238     Info.PointerToBase.clear();
2239   }
2240 
2241   // Do all the fixups of the original live variables to their relocated selves
2242   SmallVector<Value *, 128> Live;
2243   for (size_t i = 0; i < Records.size(); i++) {
2244     PartiallyConstructedSafepointRecord &Info = Records[i];
2245 
2246     // We can't simply save the live set from the original insertion.  One of
2247     // the live values might be the result of a call which needs a safepoint.
2248     // That Value* no longer exists and we need to use the new gc_result.
2249     // Thankfully, the live set is embedded in the statepoint (and updated), so
2250     // we just grab that.
2251     Statepoint Statepoint(Info.StatepointToken);
2252     Live.insert(Live.end(), Statepoint.gc_args_begin(),
2253                 Statepoint.gc_args_end());
2254 #ifndef NDEBUG
2255     // Do some basic sanity checks on our liveness results before performing
2256     // relocation.  Relocation can and will turn mistakes in liveness results
2257     // into non-sensical code which is must harder to debug.
2258     // TODO: It would be nice to test consistency as well
2259     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2260            "statepoint must be reachable or liveness is meaningless");
2261     for (Value *V : Statepoint.gc_args()) {
2262       if (!isa<Instruction>(V))
2263         // Non-instruction values trivial dominate all possible uses
2264         continue;
2265       auto *LiveInst = cast<Instruction>(V);
2266       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2267              "unreachable values should never be live");
2268       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2269              "basic SSA liveness expectation violated by liveness analysis");
2270     }
2271 #endif
2272   }
2273   unique_unsorted(Live);
2274 
2275 #ifndef NDEBUG
2276   // sanity check
2277   for (auto *Ptr : Live)
2278     assert(isHandledGCPointerType(Ptr->getType()) &&
2279            "must be a gc pointer type");
2280 #endif
2281 
2282   relocationViaAlloca(F, DT, Live, Records);
2283   return !Records.empty();
2284 }
2285 
2286 // Handles both return values and arguments for Functions and CallSites.
2287 template <typename AttrHolder>
2288 static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2289                                       unsigned Index) {
2290   AttrBuilder R;
2291   if (AH.getDereferenceableBytes(Index))
2292     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2293                                   AH.getDereferenceableBytes(Index)));
2294   if (AH.getDereferenceableOrNullBytes(Index))
2295     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2296                                   AH.getDereferenceableOrNullBytes(Index)));
2297   if (AH.doesNotAlias(Index))
2298     R.addAttribute(Attribute::NoAlias);
2299 
2300   if (!R.empty())
2301     AH.setAttributes(AH.getAttributes().removeAttributes(
2302         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2303 }
2304 
2305 void
2306 RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
2307   LLVMContext &Ctx = F.getContext();
2308 
2309   for (Argument &A : F.args())
2310     if (isa<PointerType>(A.getType()))
2311       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2312 
2313   if (isa<PointerType>(F.getReturnType()))
2314     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2315 }
2316 
2317 void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
2318   if (F.empty())
2319     return;
2320 
2321   LLVMContext &Ctx = F.getContext();
2322   MDBuilder Builder(Ctx);
2323 
2324   for (Instruction &I : instructions(F)) {
2325     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2326       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2327       bool IsImmutableTBAA =
2328           MD->getNumOperands() == 4 &&
2329           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2330 
2331       if (!IsImmutableTBAA)
2332         continue; // no work to do, MD_tbaa is already marked mutable
2333 
2334       MDNode *Base = cast<MDNode>(MD->getOperand(0));
2335       MDNode *Access = cast<MDNode>(MD->getOperand(1));
2336       uint64_t Offset =
2337           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2338 
2339       MDNode *MutableTBAA =
2340           Builder.createTBAAStructTagNode(Base, Access, Offset);
2341       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2342     }
2343 
2344     if (CallSite CS = CallSite(&I)) {
2345       for (int i = 0, e = CS.arg_size(); i != e; i++)
2346         if (isa<PointerType>(CS.getArgument(i)->getType()))
2347           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
2348       if (isa<PointerType>(CS.getType()))
2349         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2350     }
2351   }
2352 }
2353 
2354 /// Returns true if this function should be rewritten by this pass.  The main
2355 /// point of this function is as an extension point for custom logic.
2356 static bool shouldRewriteStatepointsIn(Function &F) {
2357   // TODO: This should check the GCStrategy
2358   if (F.hasGC()) {
2359     const auto &FunctionGCName = F.getGC();
2360     const StringRef StatepointExampleName("statepoint-example");
2361     const StringRef CoreCLRName("coreclr");
2362     return (StatepointExampleName == FunctionGCName) ||
2363            (CoreCLRName == FunctionGCName);
2364   } else
2365     return false;
2366 }
2367 
2368 void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
2369 #ifndef NDEBUG
2370   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2371          "precondition!");
2372 #endif
2373 
2374   for (Function &F : M)
2375     stripNonValidAttributesFromPrototype(F);
2376 
2377   for (Function &F : M)
2378     stripNonValidAttributesFromBody(F);
2379 }
2380 
2381 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2382   // Nothing to do for declarations.
2383   if (F.isDeclaration() || F.empty())
2384     return false;
2385 
2386   // Policy choice says not to rewrite - the most common reason is that we're
2387   // compiling code without a GCStrategy.
2388   if (!shouldRewriteStatepointsIn(F))
2389     return false;
2390 
2391   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2392   TargetTransformInfo &TTI =
2393       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2394 
2395   auto NeedsRewrite = [](Instruction &I) {
2396     if (ImmutableCallSite CS = ImmutableCallSite(&I))
2397       return !callsGCLeafFunction(CS) && !isStatepoint(CS);
2398     return false;
2399   };
2400 
2401   // Gather all the statepoints which need rewritten.  Be careful to only
2402   // consider those in reachable code since we need to ask dominance queries
2403   // when rewriting.  We'll delete the unreachable ones in a moment.
2404   SmallVector<CallSite, 64> ParsePointNeeded;
2405   bool HasUnreachableStatepoint = false;
2406   for (Instruction &I : instructions(F)) {
2407     // TODO: only the ones with the flag set!
2408     if (NeedsRewrite(I)) {
2409       if (DT.isReachableFromEntry(I.getParent()))
2410         ParsePointNeeded.push_back(CallSite(&I));
2411       else
2412         HasUnreachableStatepoint = true;
2413     }
2414   }
2415 
2416   bool MadeChange = false;
2417 
2418   // Delete any unreachable statepoints so that we don't have unrewritten
2419   // statepoints surviving this pass.  This makes testing easier and the
2420   // resulting IR less confusing to human readers.  Rather than be fancy, we
2421   // just reuse a utility function which removes the unreachable blocks.
2422   if (HasUnreachableStatepoint)
2423     MadeChange |= removeUnreachableBlocks(F);
2424 
2425   // Return early if no work to do.
2426   if (ParsePointNeeded.empty())
2427     return MadeChange;
2428 
2429   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2430   // These are created by LCSSA.  They have the effect of increasing the size
2431   // of liveness sets for no good reason.  It may be harder to do this post
2432   // insertion since relocations and base phis can confuse things.
2433   for (BasicBlock &BB : F)
2434     if (BB.getUniquePredecessor()) {
2435       MadeChange = true;
2436       FoldSingleEntryPHINodes(&BB);
2437     }
2438 
2439   // Before we start introducing relocations, we want to tweak the IR a bit to
2440   // avoid unfortunate code generation effects.  The main example is that we
2441   // want to try to make sure the comparison feeding a branch is after any
2442   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
2443   // values feeding a branch after relocation.  This is semantically correct,
2444   // but results in extra register pressure since both the pre-relocation and
2445   // post-relocation copies must be available in registers.  For code without
2446   // relocations this is handled elsewhere, but teaching the scheduler to
2447   // reverse the transform we're about to do would be slightly complex.
2448   // Note: This may extend the live range of the inputs to the icmp and thus
2449   // increase the liveset of any statepoint we move over.  This is profitable
2450   // as long as all statepoints are in rare blocks.  If we had in-register
2451   // lowering for live values this would be a much safer transform.
2452   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2453     if (auto *BI = dyn_cast<BranchInst>(TI))
2454       if (BI->isConditional())
2455         return dyn_cast<Instruction>(BI->getCondition());
2456     // TODO: Extend this to handle switches
2457     return nullptr;
2458   };
2459   for (BasicBlock &BB : F) {
2460     TerminatorInst *TI = BB.getTerminator();
2461     if (auto *Cond = getConditionInst(TI))
2462       // TODO: Handle more than just ICmps here.  We should be able to move
2463       // most instructions without side effects or memory access.
2464       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2465         MadeChange = true;
2466         Cond->moveBefore(TI);
2467       }
2468   }
2469 
2470   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2471   return MadeChange;
2472 }
2473 
2474 // liveness computation via standard dataflow
2475 // -------------------------------------------------------------------
2476 
2477 // TODO: Consider using bitvectors for liveness, the set of potentially
2478 // interesting values should be small and easy to pre-compute.
2479 
2480 /// Compute the live-in set for the location rbegin starting from
2481 /// the live-out set of the basic block
2482 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2483                                 BasicBlock::reverse_iterator rend,
2484                                 DenseSet<Value *> &LiveTmp) {
2485 
2486   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2487     Instruction *I = &*ritr;
2488 
2489     // KILL/Def - Remove this definition from LiveIn
2490     LiveTmp.erase(I);
2491 
2492     // Don't consider *uses* in PHI nodes, we handle their contribution to
2493     // predecessor blocks when we seed the LiveOut sets
2494     if (isa<PHINode>(I))
2495       continue;
2496 
2497     // USE - Add to the LiveIn set for this instruction
2498     for (Value *V : I->operands()) {
2499       assert(!isUnhandledGCPointerType(V->getType()) &&
2500              "support for FCA unimplemented");
2501       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2502         // The choice to exclude all things constant here is slightly subtle.
2503         // There are two independent reasons:
2504         // - We assume that things which are constant (from LLVM's definition)
2505         // do not move at runtime.  For example, the address of a global
2506         // variable is fixed, even though it's contents may not be.
2507         // - Second, we can't disallow arbitrary inttoptr constants even
2508         // if the language frontend does.  Optimization passes are free to
2509         // locally exploit facts without respect to global reachability.  This
2510         // can create sections of code which are dynamically unreachable and
2511         // contain just about anything.  (see constants.ll in tests)
2512         LiveTmp.insert(V);
2513       }
2514     }
2515   }
2516 }
2517 
2518 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2519 
2520   for (BasicBlock *Succ : successors(BB)) {
2521     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2522     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2523       PHINode *Phi = cast<PHINode>(&*I);
2524       Value *V = Phi->getIncomingValueForBlock(BB);
2525       assert(!isUnhandledGCPointerType(V->getType()) &&
2526              "support for FCA unimplemented");
2527       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2528         LiveTmp.insert(V);
2529       }
2530     }
2531   }
2532 }
2533 
2534 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2535   DenseSet<Value *> KillSet;
2536   for (Instruction &I : *BB)
2537     if (isHandledGCPointerType(I.getType()))
2538       KillSet.insert(&I);
2539   return KillSet;
2540 }
2541 
2542 #ifndef NDEBUG
2543 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2544 /// sanity check for the liveness computation.
2545 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2546                           TerminatorInst *TI, bool TermOkay = false) {
2547   for (Value *V : Live) {
2548     if (auto *I = dyn_cast<Instruction>(V)) {
2549       // The terminator can be a member of the LiveOut set.  LLVM's definition
2550       // of instruction dominance states that V does not dominate itself.  As
2551       // such, we need to special case this to allow it.
2552       if (TermOkay && TI == I)
2553         continue;
2554       assert(DT.dominates(I, TI) &&
2555              "basic SSA liveness expectation violated by liveness analysis");
2556     }
2557   }
2558 }
2559 
2560 /// Check that all the liveness sets used during the computation of liveness
2561 /// obey basic SSA properties.  This is useful for finding cases where we miss
2562 /// a def.
2563 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2564                           BasicBlock &BB) {
2565   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2566   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2567   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2568 }
2569 #endif
2570 
2571 static void computeLiveInValues(DominatorTree &DT, Function &F,
2572                                 GCPtrLivenessData &Data) {
2573 
2574   SmallSetVector<BasicBlock *, 32> Worklist;
2575   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2576     // We use a SetVector so that we don't have duplicates in the worklist.
2577     Worklist.insert(pred_begin(BB), pred_end(BB));
2578   };
2579   auto NextItem = [&]() {
2580     BasicBlock *BB = Worklist.back();
2581     Worklist.pop_back();
2582     return BB;
2583   };
2584 
2585   // Seed the liveness for each individual block
2586   for (BasicBlock &BB : F) {
2587     Data.KillSet[&BB] = computeKillSet(&BB);
2588     Data.LiveSet[&BB].clear();
2589     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2590 
2591 #ifndef NDEBUG
2592     for (Value *Kill : Data.KillSet[&BB])
2593       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2594 #endif
2595 
2596     Data.LiveOut[&BB] = DenseSet<Value *>();
2597     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2598     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2599     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2600     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2601     if (!Data.LiveIn[&BB].empty())
2602       AddPredsToWorklist(&BB);
2603   }
2604 
2605   // Propagate that liveness until stable
2606   while (!Worklist.empty()) {
2607     BasicBlock *BB = NextItem();
2608 
2609     // Compute our new liveout set, then exit early if it hasn't changed
2610     // despite the contribution of our successor.
2611     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2612     const auto OldLiveOutSize = LiveOut.size();
2613     for (BasicBlock *Succ : successors(BB)) {
2614       assert(Data.LiveIn.count(Succ));
2615       set_union(LiveOut, Data.LiveIn[Succ]);
2616     }
2617     // assert OutLiveOut is a subset of LiveOut
2618     if (OldLiveOutSize == LiveOut.size()) {
2619       // If the sets are the same size, then we didn't actually add anything
2620       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2621       // hasn't changed.
2622       continue;
2623     }
2624     Data.LiveOut[BB] = LiveOut;
2625 
2626     // Apply the effects of this basic block
2627     DenseSet<Value *> LiveTmp = LiveOut;
2628     set_union(LiveTmp, Data.LiveSet[BB]);
2629     set_subtract(LiveTmp, Data.KillSet[BB]);
2630 
2631     assert(Data.LiveIn.count(BB));
2632     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2633     // assert: OldLiveIn is a subset of LiveTmp
2634     if (OldLiveIn.size() != LiveTmp.size()) {
2635       Data.LiveIn[BB] = LiveTmp;
2636       AddPredsToWorklist(BB);
2637     }
2638   } // while( !worklist.empty() )
2639 
2640 #ifndef NDEBUG
2641   // Sanity check our output against SSA properties.  This helps catch any
2642   // missing kills during the above iteration.
2643   for (BasicBlock &BB : F) {
2644     checkBasicSSA(DT, Data, BB);
2645   }
2646 #endif
2647 }
2648 
2649 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2650                               StatepointLiveSetTy &Out) {
2651 
2652   BasicBlock *BB = Inst->getParent();
2653 
2654   // Note: The copy is intentional and required
2655   assert(Data.LiveOut.count(BB));
2656   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2657 
2658   // We want to handle the statepoint itself oddly.  It's
2659   // call result is not live (normal), nor are it's arguments
2660   // (unless they're used again later).  This adjustment is
2661   // specifically what we need to relocate
2662   BasicBlock::reverse_iterator rend(Inst->getIterator());
2663   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2664   LiveOut.erase(Inst);
2665   Out.insert(LiveOut.begin(), LiveOut.end());
2666 }
2667 
2668 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2669                                   const CallSite &CS,
2670                                   PartiallyConstructedSafepointRecord &Info) {
2671   Instruction *Inst = CS.getInstruction();
2672   StatepointLiveSetTy Updated;
2673   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2674 
2675 #ifndef NDEBUG
2676   DenseSet<Value *> Bases;
2677   for (auto KVPair : Info.PointerToBase) {
2678     Bases.insert(KVPair.second);
2679   }
2680 #endif
2681   // We may have base pointers which are now live that weren't before.  We need
2682   // to update the PointerToBase structure to reflect this.
2683   for (auto V : Updated)
2684     if (!Info.PointerToBase.count(V)) {
2685       assert(Bases.count(V) && "can't find base for unexpected live value");
2686       Info.PointerToBase[V] = V;
2687       continue;
2688     }
2689 
2690 #ifndef NDEBUG
2691   for (auto V : Updated) {
2692     assert(Info.PointerToBase.count(V) &&
2693            "must be able to find base for live value");
2694   }
2695 #endif
2696 
2697   // Remove any stale base mappings - this can happen since our liveness is
2698   // more precise then the one inherent in the base pointer analysis
2699   DenseSet<Value *> ToErase;
2700   for (auto KVPair : Info.PointerToBase)
2701     if (!Updated.count(KVPair.first))
2702       ToErase.insert(KVPair.first);
2703   for (auto V : ToErase)
2704     Info.PointerToBase.erase(V);
2705 
2706 #ifndef NDEBUG
2707   for (auto KVPair : Info.PointerToBase)
2708     assert(Updated.count(KVPair.first) && "record for non-live value");
2709 #endif
2710 
2711   Info.LiveSet = Updated;
2712 }
2713