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
1621 insertRematerializationStores(
1622   RematerializedValueMapTy RematerializedValues,
1623   DenseMap<Value *, Value *> &AllocaMap,
1624   DenseSet<Value *> &VisitedLiveValues) {
1625 
1626   for (auto RematerializedValuePair: RematerializedValues) {
1627     Instruction *RematerializedValue = RematerializedValuePair.first;
1628     Value *OriginalValue = RematerializedValuePair.second;
1629 
1630     assert(AllocaMap.count(OriginalValue) &&
1631            "Can not find alloca for rematerialized value");
1632     Value *Alloca = AllocaMap[OriginalValue];
1633 
1634     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1635     Store->insertAfter(RematerializedValue);
1636 
1637 #ifndef NDEBUG
1638     VisitedLiveValues.insert(OriginalValue);
1639 #endif
1640   }
1641 }
1642 
1643 /// Do all the relocation update via allocas and mem2reg
1644 static void relocationViaAlloca(
1645     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1646     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1647 #ifndef NDEBUG
1648   // record initial number of (static) allocas; we'll check we have the same
1649   // number when we get done.
1650   int InitialAllocaNum = 0;
1651   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1652        I++)
1653     if (isa<AllocaInst>(*I))
1654       InitialAllocaNum++;
1655 #endif
1656 
1657   // TODO-PERF: change data structures, reserve
1658   DenseMap<Value *, Value *> AllocaMap;
1659   SmallVector<AllocaInst *, 200> PromotableAllocas;
1660   // Used later to chack that we have enough allocas to store all values
1661   std::size_t NumRematerializedValues = 0;
1662   PromotableAllocas.reserve(Live.size());
1663 
1664   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1665   // "PromotableAllocas"
1666   auto emitAllocaFor = [&](Value *LiveValue) {
1667     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1668                                         F.getEntryBlock().getFirstNonPHI());
1669     AllocaMap[LiveValue] = Alloca;
1670     PromotableAllocas.push_back(Alloca);
1671   };
1672 
1673   // Emit alloca for each live gc pointer
1674   for (Value *V : Live)
1675     emitAllocaFor(V);
1676 
1677   // Emit allocas for rematerialized values
1678   for (const auto &Info : Records)
1679     for (auto RematerializedValuePair : Info.RematerializedValues) {
1680       Value *OriginalValue = RematerializedValuePair.second;
1681       if (AllocaMap.count(OriginalValue) != 0)
1682         continue;
1683 
1684       emitAllocaFor(OriginalValue);
1685       ++NumRematerializedValues;
1686     }
1687 
1688   // The next two loops are part of the same conceptual operation.  We need to
1689   // insert a store to the alloca after the original def and at each
1690   // redefinition.  We need to insert a load before each use.  These are split
1691   // into distinct loops for performance reasons.
1692 
1693   // Update gc pointer after each statepoint: either store a relocated value or
1694   // null (if no relocated value was found for this gc pointer and it is not a
1695   // gc_result).  This must happen before we update the statepoint with load of
1696   // alloca otherwise we lose the link between statepoint and old def.
1697   for (const auto &Info : Records) {
1698     Value *Statepoint = Info.StatepointToken;
1699 
1700     // This will be used for consistency check
1701     DenseSet<Value *> VisitedLiveValues;
1702 
1703     // Insert stores for normal statepoint gc relocates
1704     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1705 
1706     // In case if it was invoke statepoint
1707     // we will insert stores for exceptional path gc relocates.
1708     if (isa<InvokeInst>(Statepoint)) {
1709       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1710                              VisitedLiveValues);
1711     }
1712 
1713     // Do similar thing with rematerialized values
1714     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1715                                   VisitedLiveValues);
1716 
1717     if (ClobberNonLive) {
1718       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1719       // the gc.statepoint.  This will turn some subtle GC problems into
1720       // slightly easier to debug SEGVs.  Note that on large IR files with
1721       // lots of gc.statepoints this is extremely costly both memory and time
1722       // wise.
1723       SmallVector<AllocaInst *, 64> ToClobber;
1724       for (auto Pair : AllocaMap) {
1725         Value *Def = Pair.first;
1726         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1727 
1728         // This value was relocated
1729         if (VisitedLiveValues.count(Def)) {
1730           continue;
1731         }
1732         ToClobber.push_back(Alloca);
1733       }
1734 
1735       auto InsertClobbersAt = [&](Instruction *IP) {
1736         for (auto *AI : ToClobber) {
1737           auto PT = cast<PointerType>(AI->getAllocatedType());
1738           Constant *CPN = ConstantPointerNull::get(PT);
1739           StoreInst *Store = new StoreInst(CPN, AI);
1740           Store->insertBefore(IP);
1741         }
1742       };
1743 
1744       // Insert the clobbering stores.  These may get intermixed with the
1745       // gc.results and gc.relocates, but that's fine.
1746       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1747         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1748         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1749       } else {
1750         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1751       }
1752     }
1753   }
1754 
1755   // Update use with load allocas and add store for gc_relocated.
1756   for (auto Pair : AllocaMap) {
1757     Value *Def = Pair.first;
1758     Value *Alloca = Pair.second;
1759 
1760     // We pre-record the uses of allocas so that we dont have to worry about
1761     // later update that changes the user information..
1762 
1763     SmallVector<Instruction *, 20> Uses;
1764     // PERF: trade a linear scan for repeated reallocation
1765     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1766     for (User *U : Def->users()) {
1767       if (!isa<ConstantExpr>(U)) {
1768         // If the def has a ConstantExpr use, then the def is either a
1769         // ConstantExpr use itself or null.  In either case
1770         // (recursively in the first, directly in the second), the oop
1771         // it is ultimately dependent on is null and this particular
1772         // use does not need to be fixed up.
1773         Uses.push_back(cast<Instruction>(U));
1774       }
1775     }
1776 
1777     std::sort(Uses.begin(), Uses.end());
1778     auto Last = std::unique(Uses.begin(), Uses.end());
1779     Uses.erase(Last, Uses.end());
1780 
1781     for (Instruction *Use : Uses) {
1782       if (isa<PHINode>(Use)) {
1783         PHINode *Phi = cast<PHINode>(Use);
1784         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1785           if (Def == Phi->getIncomingValue(i)) {
1786             LoadInst *Load = new LoadInst(
1787                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1788             Phi->setIncomingValue(i, Load);
1789           }
1790         }
1791       } else {
1792         LoadInst *Load = new LoadInst(Alloca, "", Use);
1793         Use->replaceUsesOfWith(Def, Load);
1794       }
1795     }
1796 
1797     // Emit store for the initial gc value.  Store must be inserted after load,
1798     // otherwise store will be in alloca's use list and an extra load will be
1799     // inserted before it.
1800     StoreInst *Store = new StoreInst(Def, Alloca);
1801     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1802       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1803         // InvokeInst is a TerminatorInst so the store need to be inserted
1804         // into its normal destination block.
1805         BasicBlock *NormalDest = Invoke->getNormalDest();
1806         Store->insertBefore(NormalDest->getFirstNonPHI());
1807       } else {
1808         assert(!Inst->isTerminator() &&
1809                "The only TerminatorInst that can produce a value is "
1810                "InvokeInst which is handled above.");
1811         Store->insertAfter(Inst);
1812       }
1813     } else {
1814       assert(isa<Argument>(Def));
1815       Store->insertAfter(cast<Instruction>(Alloca));
1816     }
1817   }
1818 
1819   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1820          "we must have the same allocas with lives");
1821   if (!PromotableAllocas.empty()) {
1822     // Apply mem2reg to promote alloca to SSA
1823     PromoteMemToReg(PromotableAllocas, DT);
1824   }
1825 
1826 #ifndef NDEBUG
1827   for (auto &I : F.getEntryBlock())
1828     if (isa<AllocaInst>(I))
1829       InitialAllocaNum--;
1830   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1831 #endif
1832 }
1833 
1834 /// Implement a unique function which doesn't require we sort the input
1835 /// vector.  Doing so has the effect of changing the output of a couple of
1836 /// tests in ways which make them less useful in testing fused safepoints.
1837 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1838   SmallSet<T, 8> Seen;
1839   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1840               return !Seen.insert(V).second;
1841             }), Vec.end());
1842 }
1843 
1844 /// Insert holders so that each Value is obviously live through the entire
1845 /// lifetime of the call.
1846 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1847                                  SmallVectorImpl<CallInst *> &Holders) {
1848   if (Values.empty())
1849     // No values to hold live, might as well not insert the empty holder
1850     return;
1851 
1852   Module *M = CS.getInstruction()->getModule();
1853   // Use a dummy vararg function to actually hold the values live
1854   Function *Func = cast<Function>(M->getOrInsertFunction(
1855       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1856   if (CS.isCall()) {
1857     // For call safepoints insert dummy calls right after safepoint
1858     Holders.push_back(CallInst::Create(Func, Values, "",
1859                                        &*++CS.getInstruction()->getIterator()));
1860     return;
1861   }
1862   // For invoke safepooints insert dummy calls both in normal and
1863   // exceptional destination blocks
1864   auto *II = cast<InvokeInst>(CS.getInstruction());
1865   Holders.push_back(CallInst::Create(
1866       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1867   Holders.push_back(CallInst::Create(
1868       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1869 }
1870 
1871 static void findLiveReferences(
1872     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1873     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1874   GCPtrLivenessData OriginalLivenessData;
1875   computeLiveInValues(DT, F, OriginalLivenessData);
1876   for (size_t i = 0; i < records.size(); i++) {
1877     struct PartiallyConstructedSafepointRecord &info = records[i];
1878     const CallSite &CS = toUpdate[i];
1879     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1880   }
1881 }
1882 
1883 /// Remove any vector of pointers from the live set by scalarizing them over the
1884 /// statepoint instruction.  Adds the scalarized pieces to the live set.  It
1885 /// would be preferable to include the vector in the statepoint itself, but
1886 /// the lowering code currently does not handle that.  Extending it would be
1887 /// slightly non-trivial since it requires a format change.  Given how rare
1888 /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1889 static void splitVectorValues(Instruction *StatepointInst,
1890                               StatepointLiveSetTy &LiveSet,
1891                               DenseMap<Value *, Value *>& PointerToBase,
1892                               DominatorTree &DT) {
1893   SmallVector<Value *, 16> ToSplit;
1894   for (Value *V : LiveSet)
1895     if (isa<VectorType>(V->getType()))
1896       ToSplit.push_back(V);
1897 
1898   if (ToSplit.empty())
1899     return;
1900 
1901   DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1902 
1903   Function &F = *(StatepointInst->getParent()->getParent());
1904 
1905   DenseMap<Value *, AllocaInst *> AllocaMap;
1906   // First is normal return, second is exceptional return (invoke only)
1907   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1908   for (Value *V : ToSplit) {
1909     AllocaInst *Alloca =
1910         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1911     AllocaMap[V] = Alloca;
1912 
1913     VectorType *VT = cast<VectorType>(V->getType());
1914     IRBuilder<> Builder(StatepointInst);
1915     SmallVector<Value *, 16> Elements;
1916     for (unsigned i = 0; i < VT->getNumElements(); i++)
1917       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1918     ElementMapping[V] = Elements;
1919 
1920     auto InsertVectorReform = [&](Instruction *IP) {
1921       Builder.SetInsertPoint(IP);
1922       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1923       Value *ResultVec = UndefValue::get(VT);
1924       for (unsigned i = 0; i < VT->getNumElements(); i++)
1925         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1926                                                 Builder.getInt32(i));
1927       return ResultVec;
1928     };
1929 
1930     if (isa<CallInst>(StatepointInst)) {
1931       BasicBlock::iterator Next(StatepointInst);
1932       Next++;
1933       Instruction *IP = &*(Next);
1934       Replacements[V].first = InsertVectorReform(IP);
1935       Replacements[V].second = nullptr;
1936     } else {
1937       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1938       // We've already normalized - check that we don't have shared destination
1939       // blocks
1940       BasicBlock *NormalDest = Invoke->getNormalDest();
1941       assert(!isa<PHINode>(NormalDest->begin()));
1942       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1943       assert(!isa<PHINode>(UnwindDest->begin()));
1944       // Insert insert element sequences in both successors
1945       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1946       Replacements[V].first = InsertVectorReform(IP);
1947       IP = &*(UnwindDest->getFirstInsertionPt());
1948       Replacements[V].second = InsertVectorReform(IP);
1949     }
1950   }
1951 
1952   for (Value *V : ToSplit) {
1953     AllocaInst *Alloca = AllocaMap[V];
1954 
1955     // Capture all users before we start mutating use lists
1956     SmallVector<Instruction *, 16> Users;
1957     for (User *U : V->users())
1958       Users.push_back(cast<Instruction>(U));
1959 
1960     for (Instruction *I : Users) {
1961       if (auto Phi = dyn_cast<PHINode>(I)) {
1962         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1963           if (V == Phi->getIncomingValue(i)) {
1964             LoadInst *Load = new LoadInst(
1965                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1966             Phi->setIncomingValue(i, Load);
1967           }
1968       } else {
1969         LoadInst *Load = new LoadInst(Alloca, "", I);
1970         I->replaceUsesOfWith(V, Load);
1971       }
1972     }
1973 
1974     // Store the original value and the replacement value into the alloca
1975     StoreInst *Store = new StoreInst(V, Alloca);
1976     if (auto I = dyn_cast<Instruction>(V))
1977       Store->insertAfter(I);
1978     else
1979       Store->insertAfter(Alloca);
1980 
1981     // Normal return for invoke, or call return
1982     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1983     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1984     // Unwind return for invoke only
1985     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1986     if (Replacement)
1987       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1988   }
1989 
1990   // apply mem2reg to promote alloca to SSA
1991   SmallVector<AllocaInst *, 16> Allocas;
1992   for (Value *V : ToSplit)
1993     Allocas.push_back(AllocaMap[V]);
1994   PromoteMemToReg(Allocas, DT);
1995 
1996   // Update our tracking of live pointers and base mappings to account for the
1997   // changes we just made.
1998   for (Value *V : ToSplit) {
1999     auto &Elements = ElementMapping[V];
2000 
2001     LiveSet.erase(V);
2002     LiveSet.insert(Elements.begin(), Elements.end());
2003     // We need to update the base mapping as well.
2004     assert(PointerToBase.count(V));
2005     Value *OldBase = PointerToBase[V];
2006     auto &BaseElements = ElementMapping[OldBase];
2007     PointerToBase.erase(V);
2008     assert(Elements.size() == BaseElements.size());
2009     for (unsigned i = 0; i < Elements.size(); i++) {
2010       Value *Elem = Elements[i];
2011       PointerToBase[Elem] = BaseElements[i];
2012     }
2013   }
2014 }
2015 
2016 // Helper function for the "rematerializeLiveValues". It walks use chain
2017 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2018 // values are visited (currently it is GEP's and casts). Returns true if it
2019 // successfully reached "BaseValue" and false otherwise.
2020 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2021 // recorded.
2022 static bool findRematerializableChainToBasePointer(
2023   SmallVectorImpl<Instruction*> &ChainToBase,
2024   Value *CurrentValue, Value *BaseValue) {
2025 
2026   // We have found a base value
2027   if (CurrentValue == BaseValue) {
2028     return true;
2029   }
2030 
2031   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2032     ChainToBase.push_back(GEP);
2033     return findRematerializableChainToBasePointer(ChainToBase,
2034                                                   GEP->getPointerOperand(),
2035                                                   BaseValue);
2036   }
2037 
2038   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2039     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2040       return false;
2041 
2042     ChainToBase.push_back(CI);
2043     return findRematerializableChainToBasePointer(ChainToBase,
2044                                                   CI->getOperand(0), BaseValue);
2045   }
2046 
2047   // Not supported instruction in the chain
2048   return false;
2049 }
2050 
2051 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2052 // chain we are going to rematerialize.
2053 static unsigned
2054 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2055                        TargetTransformInfo &TTI) {
2056   unsigned Cost = 0;
2057 
2058   for (Instruction *Instr : Chain) {
2059     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2060       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2061              "non noop cast is found during rematerialization");
2062 
2063       Type *SrcTy = CI->getOperand(0)->getType();
2064       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2065 
2066     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2067       // Cost of the address calculation
2068       Type *ValTy = GEP->getSourceElementType();
2069       Cost += TTI.getAddressComputationCost(ValTy);
2070 
2071       // And cost of the GEP itself
2072       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2073       //       allowed for the external usage)
2074       if (!GEP->hasAllConstantIndices())
2075         Cost += 2;
2076 
2077     } else {
2078       llvm_unreachable("unsupported instruciton type during rematerialization");
2079     }
2080   }
2081 
2082   return Cost;
2083 }
2084 
2085 // From the statepoint live set pick values that are cheaper to recompute then
2086 // to relocate. Remove this values from the live set, rematerialize them after
2087 // statepoint and record them in "Info" structure. Note that similar to
2088 // relocated values we don't do any user adjustments here.
2089 static void rematerializeLiveValues(CallSite CS,
2090                                     PartiallyConstructedSafepointRecord &Info,
2091                                     TargetTransformInfo &TTI) {
2092   const unsigned int ChainLengthThreshold = 10;
2093 
2094   // Record values we are going to delete from this statepoint live set.
2095   // We can not di this in following loop due to iterator invalidation.
2096   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2097 
2098   for (Value *LiveValue: Info.LiveSet) {
2099     // For each live pointer find it's defining chain
2100     SmallVector<Instruction *, 3> ChainToBase;
2101     assert(Info.PointerToBase.count(LiveValue));
2102     bool FoundChain =
2103       findRematerializableChainToBasePointer(ChainToBase,
2104                                              LiveValue,
2105                                              Info.PointerToBase[LiveValue]);
2106     // Nothing to do, or chain is too long
2107     if (!FoundChain ||
2108         ChainToBase.size() == 0 ||
2109         ChainToBase.size() > ChainLengthThreshold)
2110       continue;
2111 
2112     // Compute cost of this chain
2113     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2114     // TODO: We can also account for cases when we will be able to remove some
2115     //       of the rematerialized values by later optimization passes. I.e if
2116     //       we rematerialized several intersecting chains. Or if original values
2117     //       don't have any uses besides this statepoint.
2118 
2119     // For invokes we need to rematerialize each chain twice - for normal and
2120     // for unwind basic blocks. Model this by multiplying cost by two.
2121     if (CS.isInvoke()) {
2122       Cost *= 2;
2123     }
2124     // If it's too expensive - skip it
2125     if (Cost >= RematerializationThreshold)
2126       continue;
2127 
2128     // Remove value from the live set
2129     LiveValuesToBeDeleted.push_back(LiveValue);
2130 
2131     // Clone instructions and record them inside "Info" structure
2132 
2133     // Walk backwards to visit top-most instructions first
2134     std::reverse(ChainToBase.begin(), ChainToBase.end());
2135 
2136     // Utility function which clones all instructions from "ChainToBase"
2137     // and inserts them before "InsertBefore". Returns rematerialized value
2138     // which should be used after statepoint.
2139     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2140       Instruction *LastClonedValue = nullptr;
2141       Instruction *LastValue = nullptr;
2142       for (Instruction *Instr: ChainToBase) {
2143         // Only GEP's and casts are suported as we need to be careful to not
2144         // introduce any new uses of pointers not in the liveset.
2145         // Note that it's fine to introduce new uses of pointers which were
2146         // otherwise not used after this statepoint.
2147         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2148 
2149         Instruction *ClonedValue = Instr->clone();
2150         ClonedValue->insertBefore(InsertBefore);
2151         ClonedValue->setName(Instr->getName() + ".remat");
2152 
2153         // If it is not first instruction in the chain then it uses previously
2154         // cloned value. We should update it to use cloned value.
2155         if (LastClonedValue) {
2156           assert(LastValue);
2157           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2158 #ifndef NDEBUG
2159           // Assert that cloned instruction does not use any instructions from
2160           // this chain other than LastClonedValue
2161           for (auto OpValue : ClonedValue->operand_values()) {
2162             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2163                        ChainToBase.end() &&
2164                    "incorrect use in rematerialization chain");
2165           }
2166 #endif
2167         }
2168 
2169         LastClonedValue = ClonedValue;
2170         LastValue = Instr;
2171       }
2172       assert(LastClonedValue);
2173       return LastClonedValue;
2174     };
2175 
2176     // Different cases for calls and invokes. For invokes we need to clone
2177     // instructions both on normal and unwind path.
2178     if (CS.isCall()) {
2179       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2180       assert(InsertBefore);
2181       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2182       Info.RematerializedValues[RematerializedValue] = LiveValue;
2183     } else {
2184       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2185 
2186       Instruction *NormalInsertBefore =
2187           &*Invoke->getNormalDest()->getFirstInsertionPt();
2188       Instruction *UnwindInsertBefore =
2189           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2190 
2191       Instruction *NormalRematerializedValue =
2192           rematerializeChain(NormalInsertBefore);
2193       Instruction *UnwindRematerializedValue =
2194           rematerializeChain(UnwindInsertBefore);
2195 
2196       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2197       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2198     }
2199   }
2200 
2201   // Remove rematerializaed values from the live set
2202   for (auto LiveValue: LiveValuesToBeDeleted) {
2203     Info.LiveSet.erase(LiveValue);
2204   }
2205 }
2206 
2207 static bool insertParsePoints(Function &F, DominatorTree &DT,
2208                               TargetTransformInfo &TTI,
2209                               SmallVectorImpl<CallSite> &ToUpdate) {
2210 #ifndef NDEBUG
2211   // sanity check the input
2212   std::set<CallSite> Uniqued;
2213   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2214   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2215 
2216   for (CallSite CS : ToUpdate)
2217     assert(CS.getInstruction()->getFunction() == &F);
2218 #endif
2219 
2220   // When inserting gc.relocates for invokes, we need to be able to insert at
2221   // the top of the successor blocks.  See the comment on
2222   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2223   // may restructure the CFG.
2224   for (CallSite CS : ToUpdate) {
2225     if (!CS.isInvoke())
2226       continue;
2227     auto *II = cast<InvokeInst>(CS.getInstruction());
2228     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2229     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2230   }
2231 
2232   // A list of dummy calls added to the IR to keep various values obviously
2233   // live in the IR.  We'll remove all of these when done.
2234   SmallVector<CallInst *, 64> Holders;
2235 
2236   // Insert a dummy call with all of the arguments to the vm_state we'll need
2237   // for the actual safepoint insertion.  This ensures reference arguments in
2238   // the deopt argument list are considered live through the safepoint (and
2239   // thus makes sure they get relocated.)
2240   for (CallSite CS : ToUpdate) {
2241     SmallVector<Value *, 64> DeoptValues;
2242 
2243     for (Value *Arg : GetDeoptBundleOperands(CS)) {
2244       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2245              "support for FCA unimplemented");
2246       if (isHandledGCPointerType(Arg->getType()))
2247         DeoptValues.push_back(Arg);
2248     }
2249 
2250     insertUseHolderAfter(CS, DeoptValues, Holders);
2251   }
2252 
2253   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2254 
2255   // A) Identify all gc pointers which are statically live at the given call
2256   // site.
2257   findLiveReferences(F, DT, ToUpdate, Records);
2258 
2259   // B) Find the base pointers for each live pointer
2260   /* scope for caching */ {
2261     // Cache the 'defining value' relation used in the computation and
2262     // insertion of base phis and selects.  This ensures that we don't insert
2263     // large numbers of duplicate base_phis.
2264     DefiningValueMapTy DVCache;
2265 
2266     for (size_t i = 0; i < Records.size(); i++) {
2267       PartiallyConstructedSafepointRecord &info = Records[i];
2268       findBasePointers(DT, DVCache, ToUpdate[i], info);
2269     }
2270   } // end of cache scope
2271 
2272   // The base phi insertion logic (for any safepoint) may have inserted new
2273   // instructions which are now live at some safepoint.  The simplest such
2274   // example is:
2275   // loop:
2276   //   phi a  <-- will be a new base_phi here
2277   //   safepoint 1 <-- that needs to be live here
2278   //   gep a + 1
2279   //   safepoint 2
2280   //   br loop
2281   // We insert some dummy calls after each safepoint to definitely hold live
2282   // the base pointers which were identified for that safepoint.  We'll then
2283   // ask liveness for _every_ base inserted to see what is now live.  Then we
2284   // remove the dummy calls.
2285   Holders.reserve(Holders.size() + Records.size());
2286   for (size_t i = 0; i < Records.size(); i++) {
2287     PartiallyConstructedSafepointRecord &Info = Records[i];
2288 
2289     SmallVector<Value *, 128> Bases;
2290     for (auto Pair : Info.PointerToBase)
2291       Bases.push_back(Pair.second);
2292 
2293     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2294   }
2295 
2296   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2297   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2298   // not the key issue.
2299   recomputeLiveInValues(F, DT, ToUpdate, Records);
2300 
2301   if (PrintBasePointers) {
2302     for (auto &Info : Records) {
2303       errs() << "Base Pairs: (w/Relocation)\n";
2304       for (auto Pair : Info.PointerToBase) {
2305         errs() << " derived ";
2306         Pair.first->printAsOperand(errs(), false);
2307         errs() << " base ";
2308         Pair.second->printAsOperand(errs(), false);
2309         errs() << "\n";
2310       }
2311     }
2312   }
2313 
2314   // It is possible that non-constant live variables have a constant base.  For
2315   // example, a GEP with a variable offset from a global.  In this case we can
2316   // remove it from the liveset.  We already don't add constants to the liveset
2317   // because we assume they won't move at runtime and the GC doesn't need to be
2318   // informed about them.  The same reasoning applies if the base is constant.
2319   // Note that the relocation placement code relies on this filtering for
2320   // correctness as it expects the base to be in the liveset, which isn't true
2321   // if the base is constant.
2322   for (auto &Info : Records)
2323     for (auto &BasePair : Info.PointerToBase)
2324       if (isa<Constant>(BasePair.second))
2325         Info.LiveSet.erase(BasePair.first);
2326 
2327   for (CallInst *CI : Holders)
2328     CI->eraseFromParent();
2329 
2330   Holders.clear();
2331 
2332   // Do a limited scalarization of any live at safepoint vector values which
2333   // contain pointers.  This enables this pass to run after vectorization at
2334   // the cost of some possible performance loss.  Note: This is known to not
2335   // handle updating of the side tables correctly which can lead to relocation
2336   // bugs when the same vector is live at multiple statepoints.  We're in the
2337   // process of implementing the alternate lowering - relocating the
2338   // vector-of-pointers as first class item and updating the backend to
2339   // understand that - but that's not yet complete.
2340   if (UseVectorSplit)
2341     for (size_t i = 0; i < Records.size(); i++) {
2342       PartiallyConstructedSafepointRecord &Info = Records[i];
2343       Instruction *Statepoint = ToUpdate[i].getInstruction();
2344       splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2345                         Info.PointerToBase, DT);
2346     }
2347 
2348   // In order to reduce live set of statepoint we might choose to rematerialize
2349   // some values instead of relocating them. This is purely an optimization and
2350   // does not influence correctness.
2351   for (size_t i = 0; i < Records.size(); i++)
2352     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2353 
2354   // We need this to safely RAUW and delete call or invoke return values that
2355   // may themselves be live over a statepoint.  For details, please see usage in
2356   // makeStatepointExplicitImpl.
2357   std::vector<DeferredReplacement> Replacements;
2358 
2359   // Now run through and replace the existing statepoints with new ones with
2360   // the live variables listed.  We do not yet update uses of the values being
2361   // relocated. We have references to live variables that need to
2362   // survive to the last iteration of this loop.  (By construction, the
2363   // previous statepoint can not be a live variable, thus we can and remove
2364   // the old statepoint calls as we go.)
2365   for (size_t i = 0; i < Records.size(); i++)
2366     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
2367 
2368   ToUpdate.clear(); // prevent accident use of invalid CallSites
2369 
2370   for (auto &PR : Replacements)
2371     PR.doReplacement();
2372 
2373   Replacements.clear();
2374 
2375   for (auto &Info : Records) {
2376     // These live sets may contain state Value pointers, since we replaced calls
2377     // with operand bundles with calls wrapped in gc.statepoint, and some of
2378     // those calls may have been def'ing live gc pointers.  Clear these out to
2379     // avoid accidentally using them.
2380     //
2381     // TODO: We should create a separate data structure that does not contain
2382     // these live sets, and migrate to using that data structure from this point
2383     // onward.
2384     Info.LiveSet.clear();
2385     Info.PointerToBase.clear();
2386   }
2387 
2388   // Do all the fixups of the original live variables to their relocated selves
2389   SmallVector<Value *, 128> Live;
2390   for (size_t i = 0; i < Records.size(); i++) {
2391     PartiallyConstructedSafepointRecord &Info = Records[i];
2392 
2393     // We can't simply save the live set from the original insertion.  One of
2394     // the live values might be the result of a call which needs a safepoint.
2395     // That Value* no longer exists and we need to use the new gc_result.
2396     // Thankfully, the live set is embedded in the statepoint (and updated), so
2397     // we just grab that.
2398     Statepoint Statepoint(Info.StatepointToken);
2399     Live.insert(Live.end(), Statepoint.gc_args_begin(),
2400                 Statepoint.gc_args_end());
2401 #ifndef NDEBUG
2402     // Do some basic sanity checks on our liveness results before performing
2403     // relocation.  Relocation can and will turn mistakes in liveness results
2404     // into non-sensical code which is must harder to debug.
2405     // TODO: It would be nice to test consistency as well
2406     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2407            "statepoint must be reachable or liveness is meaningless");
2408     for (Value *V : Statepoint.gc_args()) {
2409       if (!isa<Instruction>(V))
2410         // Non-instruction values trivial dominate all possible uses
2411         continue;
2412       auto *LiveInst = cast<Instruction>(V);
2413       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2414              "unreachable values should never be live");
2415       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2416              "basic SSA liveness expectation violated by liveness analysis");
2417     }
2418 #endif
2419   }
2420   unique_unsorted(Live);
2421 
2422 #ifndef NDEBUG
2423   // sanity check
2424   for (auto *Ptr : Live)
2425     assert(isHandledGCPointerType(Ptr->getType()) &&
2426            "must be a gc pointer type");
2427 #endif
2428 
2429   relocationViaAlloca(F, DT, Live, Records);
2430   return !Records.empty();
2431 }
2432 
2433 // Handles both return values and arguments for Functions and CallSites.
2434 template <typename AttrHolder>
2435 static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2436                                       unsigned Index) {
2437   AttrBuilder R;
2438   if (AH.getDereferenceableBytes(Index))
2439     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2440                                   AH.getDereferenceableBytes(Index)));
2441   if (AH.getDereferenceableOrNullBytes(Index))
2442     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2443                                   AH.getDereferenceableOrNullBytes(Index)));
2444   if (AH.doesNotAlias(Index))
2445     R.addAttribute(Attribute::NoAlias);
2446 
2447   if (!R.empty())
2448     AH.setAttributes(AH.getAttributes().removeAttributes(
2449         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2450 }
2451 
2452 void
2453 RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
2454   LLVMContext &Ctx = F.getContext();
2455 
2456   for (Argument &A : F.args())
2457     if (isa<PointerType>(A.getType()))
2458       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2459 
2460   if (isa<PointerType>(F.getReturnType()))
2461     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2462 }
2463 
2464 void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
2465   if (F.empty())
2466     return;
2467 
2468   LLVMContext &Ctx = F.getContext();
2469   MDBuilder Builder(Ctx);
2470 
2471   for (Instruction &I : instructions(F)) {
2472     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2473       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2474       bool IsImmutableTBAA =
2475           MD->getNumOperands() == 4 &&
2476           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2477 
2478       if (!IsImmutableTBAA)
2479         continue; // no work to do, MD_tbaa is already marked mutable
2480 
2481       MDNode *Base = cast<MDNode>(MD->getOperand(0));
2482       MDNode *Access = cast<MDNode>(MD->getOperand(1));
2483       uint64_t Offset =
2484           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2485 
2486       MDNode *MutableTBAA =
2487           Builder.createTBAAStructTagNode(Base, Access, Offset);
2488       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2489     }
2490 
2491     if (CallSite CS = CallSite(&I)) {
2492       for (int i = 0, e = CS.arg_size(); i != e; i++)
2493         if (isa<PointerType>(CS.getArgument(i)->getType()))
2494           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
2495       if (isa<PointerType>(CS.getType()))
2496         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2497     }
2498   }
2499 }
2500 
2501 /// Returns true if this function should be rewritten by this pass.  The main
2502 /// point of this function is as an extension point for custom logic.
2503 static bool shouldRewriteStatepointsIn(Function &F) {
2504   // TODO: This should check the GCStrategy
2505   if (F.hasGC()) {
2506     const auto &FunctionGCName = F.getGC();
2507     const StringRef StatepointExampleName("statepoint-example");
2508     const StringRef CoreCLRName("coreclr");
2509     return (StatepointExampleName == FunctionGCName) ||
2510            (CoreCLRName == FunctionGCName);
2511   } else
2512     return false;
2513 }
2514 
2515 void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
2516 #ifndef NDEBUG
2517   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2518          "precondition!");
2519 #endif
2520 
2521   for (Function &F : M)
2522     stripNonValidAttributesFromPrototype(F);
2523 
2524   for (Function &F : M)
2525     stripNonValidAttributesFromBody(F);
2526 }
2527 
2528 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2529   // Nothing to do for declarations.
2530   if (F.isDeclaration() || F.empty())
2531     return false;
2532 
2533   // Policy choice says not to rewrite - the most common reason is that we're
2534   // compiling code without a GCStrategy.
2535   if (!shouldRewriteStatepointsIn(F))
2536     return false;
2537 
2538   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2539   TargetTransformInfo &TTI =
2540       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2541 
2542   auto NeedsRewrite = [](Instruction &I) {
2543     if (ImmutableCallSite CS = ImmutableCallSite(&I))
2544       return !callsGCLeafFunction(CS);
2545     return false;
2546   };
2547 
2548   // Gather all the statepoints which need rewritten.  Be careful to only
2549   // consider those in reachable code since we need to ask dominance queries
2550   // when rewriting.  We'll delete the unreachable ones in a moment.
2551   SmallVector<CallSite, 64> ParsePointNeeded;
2552   bool HasUnreachableStatepoint = false;
2553   for (Instruction &I : instructions(F)) {
2554     // TODO: only the ones with the flag set!
2555     if (NeedsRewrite(I)) {
2556       if (DT.isReachableFromEntry(I.getParent()))
2557         ParsePointNeeded.push_back(CallSite(&I));
2558       else
2559         HasUnreachableStatepoint = true;
2560     }
2561   }
2562 
2563   bool MadeChange = false;
2564 
2565   // Delete any unreachable statepoints so that we don't have unrewritten
2566   // statepoints surviving this pass.  This makes testing easier and the
2567   // resulting IR less confusing to human readers.  Rather than be fancy, we
2568   // just reuse a utility function which removes the unreachable blocks.
2569   if (HasUnreachableStatepoint)
2570     MadeChange |= removeUnreachableBlocks(F);
2571 
2572   // Return early if no work to do.
2573   if (ParsePointNeeded.empty())
2574     return MadeChange;
2575 
2576   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2577   // These are created by LCSSA.  They have the effect of increasing the size
2578   // of liveness sets for no good reason.  It may be harder to do this post
2579   // insertion since relocations and base phis can confuse things.
2580   for (BasicBlock &BB : F)
2581     if (BB.getUniquePredecessor()) {
2582       MadeChange = true;
2583       FoldSingleEntryPHINodes(&BB);
2584     }
2585 
2586   // Before we start introducing relocations, we want to tweak the IR a bit to
2587   // avoid unfortunate code generation effects.  The main example is that we
2588   // want to try to make sure the comparison feeding a branch is after any
2589   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
2590   // values feeding a branch after relocation.  This is semantically correct,
2591   // but results in extra register pressure since both the pre-relocation and
2592   // post-relocation copies must be available in registers.  For code without
2593   // relocations this is handled elsewhere, but teaching the scheduler to
2594   // reverse the transform we're about to do would be slightly complex.
2595   // Note: This may extend the live range of the inputs to the icmp and thus
2596   // increase the liveset of any statepoint we move over.  This is profitable
2597   // as long as all statepoints are in rare blocks.  If we had in-register
2598   // lowering for live values this would be a much safer transform.
2599   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2600     if (auto *BI = dyn_cast<BranchInst>(TI))
2601       if (BI->isConditional())
2602         return dyn_cast<Instruction>(BI->getCondition());
2603     // TODO: Extend this to handle switches
2604     return nullptr;
2605   };
2606   for (BasicBlock &BB : F) {
2607     TerminatorInst *TI = BB.getTerminator();
2608     if (auto *Cond = getConditionInst(TI))
2609       // TODO: Handle more than just ICmps here.  We should be able to move
2610       // most instructions without side effects or memory access.
2611       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2612         MadeChange = true;
2613         Cond->moveBefore(TI);
2614       }
2615   }
2616 
2617   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2618   return MadeChange;
2619 }
2620 
2621 // liveness computation via standard dataflow
2622 // -------------------------------------------------------------------
2623 
2624 // TODO: Consider using bitvectors for liveness, the set of potentially
2625 // interesting values should be small and easy to pre-compute.
2626 
2627 /// Compute the live-in set for the location rbegin starting from
2628 /// the live-out set of the basic block
2629 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2630                                 BasicBlock::reverse_iterator rend,
2631                                 DenseSet<Value *> &LiveTmp) {
2632 
2633   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2634     Instruction *I = &*ritr;
2635 
2636     // KILL/Def - Remove this definition from LiveIn
2637     LiveTmp.erase(I);
2638 
2639     // Don't consider *uses* in PHI nodes, we handle their contribution to
2640     // predecessor blocks when we seed the LiveOut sets
2641     if (isa<PHINode>(I))
2642       continue;
2643 
2644     // USE - Add to the LiveIn set for this instruction
2645     for (Value *V : I->operands()) {
2646       assert(!isUnhandledGCPointerType(V->getType()) &&
2647              "support for FCA unimplemented");
2648       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2649         // The choice to exclude all things constant here is slightly subtle.
2650         // There are two independent reasons:
2651         // - We assume that things which are constant (from LLVM's definition)
2652         // do not move at runtime.  For example, the address of a global
2653         // variable is fixed, even though it's contents may not be.
2654         // - Second, we can't disallow arbitrary inttoptr constants even
2655         // if the language frontend does.  Optimization passes are free to
2656         // locally exploit facts without respect to global reachability.  This
2657         // can create sections of code which are dynamically unreachable and
2658         // contain just about anything.  (see constants.ll in tests)
2659         LiveTmp.insert(V);
2660       }
2661     }
2662   }
2663 }
2664 
2665 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2666 
2667   for (BasicBlock *Succ : successors(BB)) {
2668     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2669     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2670       PHINode *Phi = cast<PHINode>(&*I);
2671       Value *V = Phi->getIncomingValueForBlock(BB);
2672       assert(!isUnhandledGCPointerType(V->getType()) &&
2673              "support for FCA unimplemented");
2674       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2675         LiveTmp.insert(V);
2676       }
2677     }
2678   }
2679 }
2680 
2681 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2682   DenseSet<Value *> KillSet;
2683   for (Instruction &I : *BB)
2684     if (isHandledGCPointerType(I.getType()))
2685       KillSet.insert(&I);
2686   return KillSet;
2687 }
2688 
2689 #ifndef NDEBUG
2690 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2691 /// sanity check for the liveness computation.
2692 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2693                           TerminatorInst *TI, bool TermOkay = false) {
2694   for (Value *V : Live) {
2695     if (auto *I = dyn_cast<Instruction>(V)) {
2696       // The terminator can be a member of the LiveOut set.  LLVM's definition
2697       // of instruction dominance states that V does not dominate itself.  As
2698       // such, we need to special case this to allow it.
2699       if (TermOkay && TI == I)
2700         continue;
2701       assert(DT.dominates(I, TI) &&
2702              "basic SSA liveness expectation violated by liveness analysis");
2703     }
2704   }
2705 }
2706 
2707 /// Check that all the liveness sets used during the computation of liveness
2708 /// obey basic SSA properties.  This is useful for finding cases where we miss
2709 /// a def.
2710 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2711                           BasicBlock &BB) {
2712   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2713   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2714   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2715 }
2716 #endif
2717 
2718 static void computeLiveInValues(DominatorTree &DT, Function &F,
2719                                 GCPtrLivenessData &Data) {
2720 
2721   SmallSetVector<BasicBlock *, 32> Worklist;
2722   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2723     // We use a SetVector so that we don't have duplicates in the worklist.
2724     Worklist.insert(pred_begin(BB), pred_end(BB));
2725   };
2726   auto NextItem = [&]() {
2727     BasicBlock *BB = Worklist.back();
2728     Worklist.pop_back();
2729     return BB;
2730   };
2731 
2732   // Seed the liveness for each individual block
2733   for (BasicBlock &BB : F) {
2734     Data.KillSet[&BB] = computeKillSet(&BB);
2735     Data.LiveSet[&BB].clear();
2736     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2737 
2738 #ifndef NDEBUG
2739     for (Value *Kill : Data.KillSet[&BB])
2740       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2741 #endif
2742 
2743     Data.LiveOut[&BB] = DenseSet<Value *>();
2744     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2745     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2746     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2747     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2748     if (!Data.LiveIn[&BB].empty())
2749       AddPredsToWorklist(&BB);
2750   }
2751 
2752   // Propagate that liveness until stable
2753   while (!Worklist.empty()) {
2754     BasicBlock *BB = NextItem();
2755 
2756     // Compute our new liveout set, then exit early if it hasn't changed
2757     // despite the contribution of our successor.
2758     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2759     const auto OldLiveOutSize = LiveOut.size();
2760     for (BasicBlock *Succ : successors(BB)) {
2761       assert(Data.LiveIn.count(Succ));
2762       set_union(LiveOut, Data.LiveIn[Succ]);
2763     }
2764     // assert OutLiveOut is a subset of LiveOut
2765     if (OldLiveOutSize == LiveOut.size()) {
2766       // If the sets are the same size, then we didn't actually add anything
2767       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2768       // hasn't changed.
2769       continue;
2770     }
2771     Data.LiveOut[BB] = LiveOut;
2772 
2773     // Apply the effects of this basic block
2774     DenseSet<Value *> LiveTmp = LiveOut;
2775     set_union(LiveTmp, Data.LiveSet[BB]);
2776     set_subtract(LiveTmp, Data.KillSet[BB]);
2777 
2778     assert(Data.LiveIn.count(BB));
2779     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2780     // assert: OldLiveIn is a subset of LiveTmp
2781     if (OldLiveIn.size() != LiveTmp.size()) {
2782       Data.LiveIn[BB] = LiveTmp;
2783       AddPredsToWorklist(BB);
2784     }
2785   } // while( !worklist.empty() )
2786 
2787 #ifndef NDEBUG
2788   // Sanity check our output against SSA properties.  This helps catch any
2789   // missing kills during the above iteration.
2790   for (BasicBlock &BB : F) {
2791     checkBasicSSA(DT, Data, BB);
2792   }
2793 #endif
2794 }
2795 
2796 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2797                               StatepointLiveSetTy &Out) {
2798 
2799   BasicBlock *BB = Inst->getParent();
2800 
2801   // Note: The copy is intentional and required
2802   assert(Data.LiveOut.count(BB));
2803   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2804 
2805   // We want to handle the statepoint itself oddly.  It's
2806   // call result is not live (normal), nor are it's arguments
2807   // (unless they're used again later).  This adjustment is
2808   // specifically what we need to relocate
2809   BasicBlock::reverse_iterator rend(Inst->getIterator());
2810   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2811   LiveOut.erase(Inst);
2812   Out.insert(LiveOut.begin(), LiveOut.end());
2813 }
2814 
2815 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2816                                   const CallSite &CS,
2817                                   PartiallyConstructedSafepointRecord &Info) {
2818   Instruction *Inst = CS.getInstruction();
2819   StatepointLiveSetTy Updated;
2820   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2821 
2822 #ifndef NDEBUG
2823   DenseSet<Value *> Bases;
2824   for (auto KVPair : Info.PointerToBase) {
2825     Bases.insert(KVPair.second);
2826   }
2827 #endif
2828   // We may have base pointers which are now live that weren't before.  We need
2829   // to update the PointerToBase structure to reflect this.
2830   for (auto V : Updated)
2831     if (!Info.PointerToBase.count(V)) {
2832       assert(Bases.count(V) && "can't find base for unexpected live value");
2833       Info.PointerToBase[V] = V;
2834       continue;
2835     }
2836 
2837 #ifndef NDEBUG
2838   for (auto V : Updated) {
2839     assert(Info.PointerToBase.count(V) &&
2840            "must be able to find base for live value");
2841   }
2842 #endif
2843 
2844   // Remove any stale base mappings - this can happen since our liveness is
2845   // more precise then the one inherent in the base pointer analysis
2846   DenseSet<Value *> ToErase;
2847   for (auto KVPair : Info.PointerToBase)
2848     if (!Updated.count(KVPair.first))
2849       ToErase.insert(KVPair.first);
2850   for (auto V : ToErase)
2851     Info.PointerToBase.erase(V);
2852 
2853 #ifndef NDEBUG
2854   for (auto KVPair : Info.PointerToBase)
2855     assert(Updated.count(KVPair.first) && "record for non-live value");
2856 #endif
2857 
2858   Info.LiveSet = Updated;
2859 }
2860