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