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