RewriteStatepointsForGC::PhiState: Remove explicit copy ctor in favor of the Rule...
[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/ADT/SetOperations.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InstIterator.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Statepoint.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
40
41 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
42
43 using namespace llvm;
44
45 // Print tracing output
46 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
47                               cl::init(false));
48
49 // Print the liveset found at the insert location
50 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
51                                   cl::init(false));
52 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size",
53                                       cl::Hidden, cl::init(false));
54 // Print out the base pointers for debugging
55 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers",
56                                        cl::Hidden, cl::init(false));
57
58 namespace {
59 struct RewriteStatepointsForGC : public FunctionPass {
60   static char ID; // Pass identification, replacement for typeid
61
62   RewriteStatepointsForGC() : FunctionPass(ID) {
63     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
64   }
65   bool runOnFunction(Function &F) override;
66
67   void getAnalysisUsage(AnalysisUsage &AU) const override {
68     // We add and rewrite a bunch of instructions, but don't really do much
69     // else.  We could in theory preserve a lot more analyses here.
70     AU.addRequired<DominatorTreeWrapperPass>();
71   }
72 };
73 } // namespace
74
75 char RewriteStatepointsForGC::ID = 0;
76
77 FunctionPass *llvm::createRewriteStatepointsForGCPass() {
78   return new RewriteStatepointsForGC();
79 }
80
81 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
82                       "Make relocations explicit at statepoints", false, false)
83 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
84 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
85                     "Make relocations explicit at statepoints", false, false)
86
87 namespace {
88 // The type of the internal cache used inside the findBasePointers family
89 // of functions.  From the callers perspective, this is an opaque type and
90 // should not be inspected.
91 //
92 // In the actual implementation this caches two relations:
93 // - The base relation itself (i.e. this pointer is based on that one)
94 // - The base defining value relation (i.e. before base_phi insertion)
95 // Generally, after the execution of a full findBasePointer call, only the
96 // base relation will remain.  Internally, we add a mixture of the two
97 // types, then update all the second type to the first type
98 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
99 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
100
101 struct PartiallyConstructedSafepointRecord {
102   /// The set of values known to be live accross this safepoint
103   StatepointLiveSetTy liveset;
104
105   /// Mapping from live pointers to a base-defining-value
106   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
107
108   /// Any new values which were added to the IR during base pointer analysis
109   /// for this safepoint
110   DenseSet<llvm::Value *> NewInsertedDefs;
111
112   /// The *new* gc.statepoint instruction itself.  This produces the token
113   /// that normal path gc.relocates and the gc.result are tied to.
114   Instruction *StatepointToken;
115
116   /// Instruction to which exceptional gc relocates are attached
117   /// Makes it easier to iterate through them during relocationViaAlloca.
118   Instruction *UnwindToken;
119 };
120 }
121
122 // TODO: Once we can get to the GCStrategy, this becomes
123 // Optional<bool> isGCManagedPointer(const Value *V) const override {
124
125 static bool isGCPointerType(const Type *T) {
126   if (const PointerType *PT = dyn_cast<PointerType>(T))
127     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
128     // GC managed heap.  We know that a pointer into this heap needs to be
129     // updated and that no other pointer does.
130     return (1 == PT->getAddressSpace());
131   return false;
132 }
133
134 /// Return true if the Value is a gc reference type which is potentially used
135 /// after the instruction 'loc'.  This is only used with the edge reachability
136 /// liveness code.  Note: It is assumed the V dominates loc.
137 static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT,
138                                 LoopInfo *LI) {
139   if (!isGCPointerType(V.getType()))
140     return false;
141
142   if (V.use_empty())
143     return false;
144
145   // Given assumption that V dominates loc, this may be live
146   return true;
147 }
148
149 #ifndef NDEBUG
150 static bool isAggWhichContainsGCPtrType(Type *Ty) {
151   if (VectorType *VT = dyn_cast<VectorType>(Ty))
152     return isGCPointerType(VT->getScalarType());
153   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
154     return isGCPointerType(AT->getElementType()) ||
155            isAggWhichContainsGCPtrType(AT->getElementType());
156   if (StructType *ST = dyn_cast<StructType>(Ty))
157     return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
158                        [](Type *SubType) {
159                          return isGCPointerType(SubType) ||
160                                 isAggWhichContainsGCPtrType(SubType);
161                        });
162   return false;
163 }
164 #endif
165
166 // Conservatively identifies any definitions which might be live at the
167 // given instruction. The  analysis is performed immediately before the
168 // given instruction. Values defined by that instruction are not considered
169 // live.  Values used by that instruction are considered live.
170 //
171 // preconditions: valid IR graph, term is either a terminator instruction or
172 // a call instruction, pred is the basic block of term, DT, LI are valid
173 //
174 // side effects: none, does not mutate IR
175 //
176 //  postconditions: populates liveValues as discussed above
177 static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred,
178                                    DominatorTree &DT, LoopInfo *LI,
179                                    StatepointLiveSetTy &liveValues) {
180   liveValues.clear();
181
182   assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator());
183
184   Function *F = pred->getParent();
185
186   auto is_live_gc_reference =
187       [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); };
188
189   // Are there any gc pointer arguments live over this point?  This needs to be
190   // special cased since arguments aren't defined in basic blocks.
191   for (Argument &arg : F->args()) {
192     assert(!isAggWhichContainsGCPtrType(arg.getType()) &&
193            "support for FCA unimplemented");
194
195     if (is_live_gc_reference(arg)) {
196       liveValues.insert(&arg);
197     }
198   }
199
200   // Walk through all dominating blocks - the ones which can contain
201   // definitions used in this block - and check to see if any of the values
202   // they define are used in locations potentially reachable from the
203   // interesting instruction.
204   BasicBlock *BBI = pred;
205   while (true) {
206     if (TraceLSP) {
207       errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n";
208     }
209     assert(DT.dominates(BBI, pred));
210     assert(isPotentiallyReachable(BBI, pred, &DT) &&
211            "dominated block must be reachable");
212
213     // Walk through the instructions in dominating blocks and keep any
214     // that have a use potentially reachable from the block we're
215     // considering putting the safepoint in
216     for (Instruction &inst : *BBI) {
217       if (TraceLSP) {
218         errs() << "[LSP] Looking at instruction ";
219         inst.dump();
220       }
221
222       if (pred == BBI && (&inst) == term) {
223         if (TraceLSP) {
224           errs() << "[LSP] stopped because we encountered the safepoint "
225                     "instruction.\n";
226         }
227
228         // If we're in the block which defines the interesting instruction,
229         // we don't want to include any values as live which are defined
230         // _after_ the interesting line or as part of the line itself
231         // i.e. "term" is the call instruction for a call safepoint, the
232         // results of the call should not be considered live in that stackmap
233         break;
234       }
235
236       assert(!isAggWhichContainsGCPtrType(inst.getType()) &&
237              "support for FCA unimplemented");
238
239       if (is_live_gc_reference(inst)) {
240         if (TraceLSP) {
241           errs() << "[LSP] found live value for this safepoint ";
242           inst.dump();
243           term->dump();
244         }
245         liveValues.insert(&inst);
246       }
247     }
248     if (!DT.getNode(BBI)->getIDom()) {
249       assert(BBI == &F->getEntryBlock() &&
250              "failed to find a dominator for something other than "
251              "the entry block");
252       break;
253     }
254     BBI = DT.getNode(BBI)->getIDom()->getBlock();
255   }
256 }
257
258 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
259   if (a->hasName() && b->hasName()) {
260     return -1 == a->getName().compare(b->getName());
261   } else if (a->hasName() && !b->hasName()) {
262     return true;
263   } else if (!a->hasName() && b->hasName()) {
264     return false;
265   } else {
266     // Better than nothing, but not stable
267     return a < b;
268   }
269 }
270
271 /// Find the initial live set. Note that due to base pointer
272 /// insertion, the live set may be incomplete.
273 static void
274 analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS,
275                           PartiallyConstructedSafepointRecord &result) {
276   Instruction *inst = CS.getInstruction();
277
278   BasicBlock *BB = inst->getParent();
279   StatepointLiveSetTy liveset;
280   findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset);
281
282   if (PrintLiveSet) {
283     // Note: This output is used by several of the test cases
284     // The order of elemtns in a set is not stable, put them in a vec and sort
285     // by name
286     SmallVector<Value *, 64> temp;
287     temp.insert(temp.end(), liveset.begin(), liveset.end());
288     std::sort(temp.begin(), temp.end(), order_by_name);
289     errs() << "Live Variables:\n";
290     for (Value *V : temp) {
291       errs() << " " << V->getName(); // no newline
292       V->dump();
293     }
294   }
295   if (PrintLiveSetSize) {
296     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
297     errs() << "Number live values: " << liveset.size() << "\n";
298   }
299   result.liveset = liveset;
300 }
301
302 /// True iff this value is the null pointer constant (of any pointer type)
303 static bool LLVM_ATTRIBUTE_UNUSED isNullConstant(Value *V) {
304   return isa<Constant>(V) && isa<PointerType>(V->getType()) &&
305          cast<Constant>(V)->isNullValue();
306 }
307
308 /// Helper function for findBasePointer - Will return a value which either a)
309 /// defines the base pointer for the input or b) blocks the simple search
310 /// (i.e. a PHI or Select of two derived pointers)
311 static Value *findBaseDefiningValue(Value *I) {
312   assert(I->getType()->isPointerTy() &&
313          "Illegal to ask for the base pointer of a non-pointer type");
314
315   // There are instructions which can never return gc pointer values.  Sanity
316   // check
317   // that this is actually true.
318   assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
319          !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers");
320   assert((!isa<Instruction>(I) || isa<InvokeInst>(I) ||
321           !cast<Instruction>(I)->isTerminator()) &&
322          "With the exception of invoke terminators don't define values");
323   assert(!isa<StoreInst>(I) && !isa<FenceInst>(I) &&
324          "Can't be definitions to start with");
325   assert(!isa<ICmpInst>(I) && !isa<FCmpInst>(I) &&
326          "Comparisons don't give ops");
327   // There's a bunch of instructions which just don't make sense to apply to
328   // a pointer.  The only valid reason for this would be pointer bit
329   // twiddling which we're just not going to support.
330   assert((!isa<Instruction>(I) || !cast<Instruction>(I)->isBinaryOp()) &&
331          "Binary ops on pointer values are meaningless.  Unless your "
332          "bit-twiddling which we don't support");
333
334   if (Argument *Arg = dyn_cast<Argument>(I)) {
335     // An incoming argument to the function is a base pointer
336     // We should have never reached here if this argument isn't an gc value
337     assert(Arg->getType()->isPointerTy() &&
338            "Base for pointer must be another pointer");
339     return Arg;
340   }
341
342   if (GlobalVariable *global = dyn_cast<GlobalVariable>(I)) {
343     // base case
344     assert(global->getType()->isPointerTy() &&
345            "Base for pointer must be another pointer");
346     return global;
347   }
348
349   // inlining could possibly introduce phi node that contains
350   // undef if callee has multiple returns
351   if (UndefValue *undef = dyn_cast<UndefValue>(I)) {
352     assert(undef->getType()->isPointerTy() &&
353            "Base for pointer must be another pointer");
354     return undef; // utterly meaningless, but useful for dealing with
355                   // partially optimized code.
356   }
357
358   // Due to inheritance, this must be _after_ the global variable and undef
359   // checks
360   if (Constant *con = dyn_cast<Constant>(I)) {
361     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
362            "order of checks wrong!");
363     // Note: Finding a constant base for something marked for relocation
364     // doesn't really make sense.  The most likely case is either a) some
365     // screwed up the address space usage or b) your validating against
366     // compiled C++ code w/o the proper separation.  The only real exception
367     // is a null pointer.  You could have generic code written to index of
368     // off a potentially null value and have proven it null.  We also use
369     // null pointers in dead paths of relocation phis (which we might later
370     // want to find a base pointer for).
371     assert(con->getType()->isPointerTy() &&
372            "Base for pointer must be another pointer");
373     assert(con->isNullValue() && "null is the only case which makes sense");
374     return con;
375   }
376
377   if (CastInst *CI = dyn_cast<CastInst>(I)) {
378     Value *def = CI->stripPointerCasts();
379     assert(def->getType()->isPointerTy() &&
380            "Base for pointer must be another pointer");
381     // If we find a cast instruction here, it means we've found a cast which is
382     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
383     // handle int->ptr conversion.
384     assert(!isa<CastInst>(def) && "shouldn't find another cast here");
385     return findBaseDefiningValue(def);
386   }
387
388   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
389     if (LI->getType()->isPointerTy()) {
390       Value *Op = LI->getOperand(0);
391       (void)Op;
392       // Has to be a pointer to an gc object, or possibly an array of such?
393       assert(Op->getType()->isPointerTy());
394       return LI; // The value loaded is an gc base itself
395     }
396   }
397   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
398     Value *Op = GEP->getOperand(0);
399     if (Op->getType()->isPointerTy()) {
400       return findBaseDefiningValue(Op); // The base of this GEP is the base
401     }
402   }
403
404   if (AllocaInst *alloc = dyn_cast<AllocaInst>(I)) {
405     // An alloca represents a conceptual stack slot.  It's the slot itself
406     // that the GC needs to know about, not the value in the slot.
407     assert(alloc->getType()->isPointerTy() &&
408            "Base for pointer must be another pointer");
409     return alloc;
410   }
411
412   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
413     switch (II->getIntrinsicID()) {
414     default:
415       // fall through to general call handling
416       break;
417     case Intrinsic::experimental_gc_statepoint:
418     case Intrinsic::experimental_gc_result_float:
419     case Intrinsic::experimental_gc_result_int:
420       llvm_unreachable("these don't produce pointers");
421     case Intrinsic::experimental_gc_result_ptr:
422       // This is just a special case of the CallInst check below to handle a
423       // statepoint with deopt args which hasn't been rewritten for GC yet.
424       // TODO: Assert that the statepoint isn't rewritten yet.
425       return II;
426     case Intrinsic::experimental_gc_relocate: {
427       // Rerunning safepoint insertion after safepoints are already
428       // inserted is not supported.  It could probably be made to work,
429       // but why are you doing this?  There's no good reason.
430       llvm_unreachable("repeat safepoint insertion is not supported");
431     }
432     case Intrinsic::gcroot:
433       // Currently, this mechanism hasn't been extended to work with gcroot.
434       // There's no reason it couldn't be, but I haven't thought about the
435       // implications much.
436       llvm_unreachable(
437           "interaction with the gcroot mechanism is not supported");
438     }
439   }
440   // We assume that functions in the source language only return base
441   // pointers.  This should probably be generalized via attributes to support
442   // both source language and internal functions.
443   if (CallInst *call = dyn_cast<CallInst>(I)) {
444     assert(call->getType()->isPointerTy() &&
445            "Base for pointer must be another pointer");
446     return call;
447   }
448   if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
449     assert(invoke->getType()->isPointerTy() &&
450            "Base for pointer must be another pointer");
451     return invoke;
452   }
453
454   // I have absolutely no idea how to implement this part yet.  It's not
455   // neccessarily hard, I just haven't really looked at it yet.
456   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
457
458   if (AtomicCmpXchgInst *cas = dyn_cast<AtomicCmpXchgInst>(I)) {
459     // A CAS is effectively a atomic store and load combined under a
460     // predicate.  From the perspective of base pointers, we just treat it
461     // like a load.  We loaded a pointer from a address in memory, that value
462     // had better be a valid base pointer.
463     return cas->getPointerOperand();
464   }
465   if (AtomicRMWInst *atomic = dyn_cast<AtomicRMWInst>(I)) {
466     assert(AtomicRMWInst::Xchg == atomic->getOperation() &&
467            "All others are binary ops which don't apply to base pointers");
468     // semantically, a load, store pair.  Treat it the same as a standard load
469     return atomic->getPointerOperand();
470   }
471
472   // The aggregate ops.  Aggregates can either be in the heap or on the
473   // stack, but in either case, this is simply a field load.  As a result,
474   // this is a defining definition of the base just like a load is.
475   if (ExtractValueInst *ev = dyn_cast<ExtractValueInst>(I)) {
476     return ev;
477   }
478
479   // We should never see an insert vector since that would require we be
480   // tracing back a struct value not a pointer value.
481   assert(!isa<InsertValueInst>(I) &&
482          "Base pointer for a struct is meaningless");
483
484   // The last two cases here don't return a base pointer.  Instead, they
485   // return a value which dynamically selects from amoung several base
486   // derived pointers (each with it's own base potentially).  It's the job of
487   // the caller to resolve these.
488   if (SelectInst *select = dyn_cast<SelectInst>(I)) {
489     return select;
490   }
491
492   return cast<PHINode>(I);
493 }
494
495 /// Returns the base defining value for this value.
496 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) {
497   Value *&Cached = cache[I];
498   if (!Cached) {
499     Cached = findBaseDefiningValue(I);
500   }
501   assert(cache[I] != nullptr);
502
503   if (TraceLSP) {
504     errs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
505            << "\n";
506   }
507   return Cached;
508 }
509
510 /// Return a base pointer for this value if known.  Otherwise, return it's
511 /// base defining value.
512 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) {
513   Value *def = findBaseDefiningValueCached(I, cache);
514   auto Found = cache.find(def);
515   if (Found != cache.end()) {
516     // Either a base-of relation, or a self reference.  Caller must check.
517     return Found->second;
518   }
519   // Only a BDV available
520   return def;
521 }
522
523 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
524 /// is it known to be a base pointer?  Or do we need to continue searching.
525 static bool isKnownBaseResult(Value *v) {
526   if (!isa<PHINode>(v) && !isa<SelectInst>(v)) {
527     // no recursion possible
528     return true;
529   }
530   if (cast<Instruction>(v)->getMetadata("is_base_value")) {
531     // This is a previously inserted base phi or select.  We know
532     // that this is a base value.
533     return true;
534   }
535
536   // We need to keep searching
537   return false;
538 }
539
540 // TODO: find a better name for this
541 namespace {
542 class PhiState {
543 public:
544   enum Status { Unknown, Base, Conflict };
545
546   PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
547     assert(status != Base || b);
548   }
549   PhiState(Value *b) : status(Base), base(b) {}
550   PhiState() : status(Unknown), base(nullptr) {}
551
552   Status getStatus() const { return status; }
553   Value *getBase() const { return base; }
554
555   bool isBase() const { return getStatus() == Base; }
556   bool isUnknown() const { return getStatus() == Unknown; }
557   bool isConflict() const { return getStatus() == Conflict; }
558
559   bool operator==(const PhiState &other) const {
560     return base == other.base && status == other.status;
561   }
562
563   bool operator!=(const PhiState &other) const { return !(*this == other); }
564
565   void dump() {
566     errs() << status << " (" << base << " - "
567            << (base ? base->getName() : "nullptr") << "): ";
568   }
569
570 private:
571   Status status;
572   Value *base; // non null only if status == base
573 };
574
575 typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
576 // Values of type PhiState form a lattice, and this is a helper
577 // class that implementes the meet operation.  The meat of the meet
578 // operation is implemented in MeetPhiStates::pureMeet
579 class MeetPhiStates {
580 public:
581   // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
582   explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
583       : phiStates(phiStates) {}
584
585   // Destructively meet the current result with the base V.  V can
586   // either be a merge instruction (SelectInst / PHINode), in which
587   // case its status is looked up in the phiStates map; or a regular
588   // SSA value, in which case it is assumed to be a base.
589   void meetWith(Value *V) {
590     PhiState otherState = getStateForBDV(V);
591     assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
592             MeetPhiStates::pureMeet(currentResult, otherState)) &&
593            "math is wrong: meet does not commute!");
594     currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
595   }
596
597   PhiState getResult() const { return currentResult; }
598
599 private:
600   const ConflictStateMapTy &phiStates;
601   PhiState currentResult;
602
603   /// Return a phi state for a base defining value.  We'll generate a new
604   /// base state for known bases and expect to find a cached state otherwise
605   PhiState getStateForBDV(Value *baseValue) {
606     if (isKnownBaseResult(baseValue)) {
607       return PhiState(baseValue);
608     } else {
609       return lookupFromMap(baseValue);
610     }
611   }
612
613   PhiState lookupFromMap(Value *V) {
614     auto I = phiStates.find(V);
615     assert(I != phiStates.end() && "lookup failed!");
616     return I->second;
617   }
618
619   static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
620     switch (stateA.getStatus()) {
621     case PhiState::Unknown:
622       return stateB;
623
624     case PhiState::Base:
625       assert(stateA.getBase() && "can't be null");
626       if (stateB.isUnknown())
627         return stateA;
628
629       if (stateB.isBase()) {
630         if (stateA.getBase() == stateB.getBase()) {
631           assert(stateA == stateB && "equality broken!");
632           return stateA;
633         }
634         return PhiState(PhiState::Conflict);
635       }
636       assert(stateB.isConflict() && "only three states!");
637       return PhiState(PhiState::Conflict);
638
639     case PhiState::Conflict:
640       return stateA;
641     }
642     llvm_unreachable("only three states!");
643   }
644 };
645 }
646 /// For a given value or instruction, figure out what base ptr it's derived
647 /// from.  For gc objects, this is simply itself.  On success, returns a value
648 /// which is the base pointer.  (This is reliable and can be used for
649 /// relocation.)  On failure, returns nullptr.
650 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
651                               DenseSet<llvm::Value *> &NewInsertedDefs) {
652   Value *def = findBaseOrBDV(I, cache);
653
654   if (isKnownBaseResult(def)) {
655     return def;
656   }
657
658   // Here's the rough algorithm:
659   // - For every SSA value, construct a mapping to either an actual base
660   //   pointer or a PHI which obscures the base pointer.
661   // - Construct a mapping from PHI to unknown TOP state.  Use an
662   //   optimistic algorithm to propagate base pointer information.  Lattice
663   //   looks like:
664   //   UNKNOWN
665   //   b1 b2 b3 b4
666   //   CONFLICT
667   //   When algorithm terminates, all PHIs will either have a single concrete
668   //   base or be in a conflict state.
669   // - For every conflict, insert a dummy PHI node without arguments.  Add
670   //   these to the base[Instruction] = BasePtr mapping.  For every
671   //   non-conflict, add the actual base.
672   //  - For every conflict, add arguments for the base[a] of each input
673   //   arguments.
674   //
675   // Note: A simpler form of this would be to add the conflict form of all
676   // PHIs without running the optimistic algorithm.  This would be
677   // analougous to pessimistic data flow and would likely lead to an
678   // overall worse solution.
679
680   ConflictStateMapTy states;
681   states[def] = PhiState();
682   // Recursively fill in all phis & selects reachable from the initial one
683   // for which we don't already know a definite base value for
684   // TODO: This should be rewritten with a worklist
685   bool done = false;
686   while (!done) {
687     done = true;
688     // Since we're adding elements to 'states' as we run, we can't keep
689     // iterators into the set.
690     SmallVector<Value*, 16> Keys;
691     Keys.reserve(states.size());
692     for (auto Pair : states) {
693       Value *V = Pair.first;
694       Keys.push_back(V);
695     }
696     for (Value *v : Keys) {
697       assert(!isKnownBaseResult(v) && "why did it get added?");
698       if (PHINode *phi = dyn_cast<PHINode>(v)) {
699         assert(phi->getNumIncomingValues() > 0 &&
700                "zero input phis are illegal");
701         for (Value *InVal : phi->incoming_values()) {
702           Value *local = findBaseOrBDV(InVal, cache);
703           if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
704             states[local] = PhiState();
705             done = false;
706           }
707         }
708       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
709         Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
710         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
711           states[local] = PhiState();
712           done = false;
713         }
714         local = findBaseOrBDV(sel->getFalseValue(), cache);
715         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
716           states[local] = PhiState();
717           done = false;
718         }
719       }
720     }
721   }
722
723   if (TraceLSP) {
724     errs() << "States after initialization:\n";
725     for (auto Pair : states) {
726       Instruction *v = cast<Instruction>(Pair.first);
727       PhiState state = Pair.second;
728       state.dump();
729       v->dump();
730     }
731   }
732
733   // TODO: come back and revisit the state transitions around inputs which
734   // have reached conflict state.  The current version seems too conservative.
735
736   bool progress = true;
737   while (progress) {
738 #ifndef NDEBUG
739     size_t oldSize = states.size();
740 #endif
741     progress = false;
742     // We're only changing keys in this loop, thus safe to keep iterators
743     for (auto Pair : states) {
744       MeetPhiStates calculateMeet(states);
745       Value *v = Pair.first;
746       assert(!isKnownBaseResult(v) && "why did it get added?");
747       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
748         calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
749         calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
750       } else
751         for (Value *Val : cast<PHINode>(v)->incoming_values())
752           calculateMeet.meetWith(findBaseOrBDV(Val, cache));
753
754       PhiState oldState = states[v];
755       PhiState newState = calculateMeet.getResult();
756       if (oldState != newState) {
757         progress = true;
758         states[v] = newState;
759       }
760     }
761
762     assert(oldSize <= states.size());
763     assert(oldSize == states.size() || progress);
764   }
765
766   if (TraceLSP) {
767     errs() << "States after meet iteration:\n";
768     for (auto Pair : states) {
769       Instruction *v = cast<Instruction>(Pair.first);
770       PhiState state = Pair.second;
771       state.dump();
772       v->dump();
773     }
774   }
775
776   // Insert Phis for all conflicts
777   // We want to keep naming deterministic in the loop that follows, so
778   // sort the keys before iteration.  This is useful in allowing us to
779   // write stable tests. Note that there is no invalidation issue here.
780   SmallVector<Value*, 16> Keys;
781   Keys.reserve(states.size());
782   for (auto Pair : states) {
783     Value *V = Pair.first;
784     Keys.push_back(V);
785   }
786   std::sort(Keys.begin(), Keys.end(), order_by_name);
787   // TODO: adjust naming patterns to avoid this order of iteration dependency
788   for (Value *V : Keys) {
789     Instruction *v = cast<Instruction>(V);
790     PhiState state = states[V];
791     assert(!isKnownBaseResult(v) && "why did it get added?");
792     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
793     if (!state.isConflict())
794       continue;
795     
796     if (isa<PHINode>(v)) {
797       int num_preds =
798           std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
799       assert(num_preds > 0 && "how did we reach here");
800       PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
801       NewInsertedDefs.insert(phi);
802       // Add metadata marking this as a base value
803       auto *const_1 = ConstantInt::get(
804           Type::getInt32Ty(
805               v->getParent()->getParent()->getParent()->getContext()),
806           1);
807       auto MDConst = ConstantAsMetadata::get(const_1);
808       MDNode *md = MDNode::get(
809           v->getParent()->getParent()->getParent()->getContext(), MDConst);
810       phi->setMetadata("is_base_value", md);
811       states[v] = PhiState(PhiState::Conflict, phi);
812     } else {
813       SelectInst *sel = cast<SelectInst>(v);
814       // The undef will be replaced later
815       UndefValue *undef = UndefValue::get(sel->getType());
816       SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
817                                                undef, "base_select", sel);
818       NewInsertedDefs.insert(basesel);
819       // Add metadata marking this as a base value
820       auto *const_1 = ConstantInt::get(
821           Type::getInt32Ty(
822               v->getParent()->getParent()->getParent()->getContext()),
823           1);
824       auto MDConst = ConstantAsMetadata::get(const_1);
825       MDNode *md = MDNode::get(
826           v->getParent()->getParent()->getParent()->getContext(), MDConst);
827       basesel->setMetadata("is_base_value", md);
828       states[v] = PhiState(PhiState::Conflict, basesel);
829     }
830   }
831
832   // Fixup all the inputs of the new PHIs
833   for (auto Pair : states) {
834     Instruction *v = cast<Instruction>(Pair.first);
835     PhiState state = Pair.second;
836
837     assert(!isKnownBaseResult(v) && "why did it get added?");
838     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
839     if (!state.isConflict())
840       continue;
841     
842     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
843       PHINode *phi = cast<PHINode>(v);
844       unsigned NumPHIValues = phi->getNumIncomingValues();
845       for (unsigned i = 0; i < NumPHIValues; i++) {
846         Value *InVal = phi->getIncomingValue(i);
847         BasicBlock *InBB = phi->getIncomingBlock(i);
848
849         // If we've already seen InBB, add the same incoming value
850         // we added for it earlier.  The IR verifier requires phi
851         // nodes with multiple entries from the same basic block
852         // to have the same incoming value for each of those
853         // entries.  If we don't do this check here and basephi
854         // has a different type than base, we'll end up adding two
855         // bitcasts (and hence two distinct values) as incoming
856         // values for the same basic block.
857
858         int blockIndex = basephi->getBasicBlockIndex(InBB);
859         if (blockIndex != -1) {
860           Value *oldBase = basephi->getIncomingValue(blockIndex);
861           basephi->addIncoming(oldBase, InBB);
862 #ifndef NDEBUG
863           Value *base = findBaseOrBDV(InVal, cache);
864           if (!isKnownBaseResult(base)) {
865             // Either conflict or base.
866             assert(states.count(base));
867             base = states[base].getBase();
868             assert(base != nullptr && "unknown PhiState!");
869             assert(NewInsertedDefs.count(base) &&
870                    "should have already added this in a prev. iteration!");
871           }
872
873           // In essense this assert states: the only way two
874           // values incoming from the same basic block may be
875           // different is by being different bitcasts of the same
876           // value.  A cleanup that remains TODO is changing
877           // findBaseOrBDV to return an llvm::Value of the correct
878           // type (and still remain pure).  This will remove the
879           // need to add bitcasts.
880           assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
881                  "sanity -- findBaseOrBDV should be pure!");
882 #endif
883           continue;
884         }
885
886         // Find either the defining value for the PHI or the normal base for
887         // a non-phi node
888         Value *base = findBaseOrBDV(InVal, cache);
889         if (!isKnownBaseResult(base)) {
890           // Either conflict or base.
891           assert(states.count(base));
892           base = states[base].getBase();
893           assert(base != nullptr && "unknown PhiState!");
894         }
895         assert(base && "can't be null");
896         // Must use original input BB since base may not be Instruction
897         // The cast is needed since base traversal may strip away bitcasts
898         if (base->getType() != basephi->getType()) {
899           base = new BitCastInst(base, basephi->getType(), "cast",
900                                  InBB->getTerminator());
901           NewInsertedDefs.insert(base);
902         }
903         basephi->addIncoming(base, InBB);
904       }
905       assert(basephi->getNumIncomingValues() == NumPHIValues);
906     } else {
907       SelectInst *basesel = cast<SelectInst>(state.getBase());
908       SelectInst *sel = cast<SelectInst>(v);
909       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
910       // something more safe and less hacky.
911       for (int i = 1; i <= 2; i++) {
912         Value *InVal = sel->getOperand(i);
913         // Find either the defining value for the PHI or the normal base for
914         // a non-phi node
915         Value *base = findBaseOrBDV(InVal, cache);
916         if (!isKnownBaseResult(base)) {
917           // Either conflict or base.
918           assert(states.count(base));
919           base = states[base].getBase();
920           assert(base != nullptr && "unknown PhiState!");
921         }
922         assert(base && "can't be null");
923         // Must use original input BB since base may not be Instruction
924         // The cast is needed since base traversal may strip away bitcasts
925         if (base->getType() != basesel->getType()) {
926           base = new BitCastInst(base, basesel->getType(), "cast", basesel);
927           NewInsertedDefs.insert(base);
928         }
929         basesel->setOperand(i, base);
930       }
931     }
932   }
933
934   // Cache all of our results so we can cheaply reuse them
935   // NOTE: This is actually two caches: one of the base defining value
936   // relation and one of the base pointer relation!  FIXME
937   for (auto item : states) {
938     Value *v = item.first;
939     Value *base = item.second.getBase();
940     assert(v && base);
941     assert(!isKnownBaseResult(v) && "why did it get added?");
942
943     if (TraceLSP) {
944       std::string fromstr =
945           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
946                          : "none";
947       errs() << "Updating base value cache"
948              << " for: " << (v->hasName() ? v->getName() : "")
949              << " from: " << fromstr
950              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
951     }
952
953     assert(isKnownBaseResult(base) &&
954            "must be something we 'know' is a base pointer");
955     if (cache.count(v)) {
956       // Once we transition from the BDV relation being store in the cache to
957       // the base relation being stored, it must be stable
958       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
959              "base relation should be stable");
960     }
961     cache[v] = base;
962   }
963   assert(cache.find(def) != cache.end());
964   return cache[def];
965 }
966
967 // For a set of live pointers (base and/or derived), identify the base
968 // pointer of the object which they are derived from.  This routine will
969 // mutate the IR graph as needed to make the 'base' pointer live at the
970 // definition site of 'derived'.  This ensures that any use of 'derived' can
971 // also use 'base'.  This may involve the insertion of a number of
972 // additional PHI nodes.
973 //
974 // preconditions: live is a set of pointer type Values
975 //
976 // side effects: may insert PHI nodes into the existing CFG, will preserve
977 // CFG, will not remove or mutate any existing nodes
978 //
979 // post condition: PointerToBase contains one (derived, base) pair for every
980 // pointer in live.  Note that derived can be equal to base if the original
981 // pointer was a base pointer.
982 static void findBasePointers(const StatepointLiveSetTy &live,
983                              DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
984                              DominatorTree *DT, DefiningValueMapTy &DVCache,
985                              DenseSet<llvm::Value *> &NewInsertedDefs) {
986   // For the naming of values inserted to be deterministic - which makes for
987   // much cleaner and more stable tests - we need to assign an order to the
988   // live values.  DenseSets do not provide a deterministic order across runs.
989   SmallVector<Value*, 64> Temp;
990   Temp.insert(Temp.end(), live.begin(), live.end());
991   std::sort(Temp.begin(), Temp.end(), order_by_name);
992   for (Value *ptr : Temp) {
993     Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
994     assert(base && "failed to find base pointer");
995     PointerToBase[ptr] = base;
996     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
997             DT->dominates(cast<Instruction>(base)->getParent(),
998                           cast<Instruction>(ptr)->getParent())) &&
999            "The base we found better dominate the derived pointer");
1000
1001     // If you see this trip and like to live really dangerously, the code should
1002     // be correct, just with idioms the verifier can't handle.  You can try
1003     // disabling the verifier at your own substaintial risk.
1004     assert(!isNullConstant(base) && "the relocation code needs adjustment to "
1005                                     "handle the relocation of a null pointer "
1006                                     "constant without causing false positives "
1007                                     "in the safepoint ir verifier.");
1008   }
1009 }
1010
1011 /// Find the required based pointers (and adjust the live set) for the given
1012 /// parse point.
1013 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1014                              const CallSite &CS,
1015                              PartiallyConstructedSafepointRecord &result) {
1016   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1017   DenseSet<llvm::Value *> NewInsertedDefs;
1018   findBasePointers(result.liveset, PointerToBase, &DT, DVCache, NewInsertedDefs);
1019
1020   if (PrintBasePointers) {
1021     // Note: Need to print these in a stable order since this is checked in
1022     // some tests.
1023     errs() << "Base Pairs (w/o Relocation):\n";
1024     SmallVector<Value*, 64> Temp;
1025     Temp.reserve(PointerToBase.size());
1026     for (auto Pair : PointerToBase) {
1027       Temp.push_back(Pair.first);
1028     }
1029     std::sort(Temp.begin(), Temp.end(), order_by_name);
1030     for (Value *Ptr : Temp) {
1031       Value *Base = PointerToBase[Ptr];
1032       errs() << " derived %" << Ptr->getName() << " base %"
1033              << Base->getName() << "\n";
1034     }
1035   }
1036
1037   result.PointerToBase = PointerToBase;
1038   result.NewInsertedDefs = NewInsertedDefs;
1039 }
1040
1041 /// Check for liveness of items in the insert defs and add them to the live
1042 /// and base pointer sets
1043 static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
1044                           const DenseSet<Value *> &allInsertedDefs,
1045                           PartiallyConstructedSafepointRecord &result) {
1046   Instruction *inst = CS.getInstruction();
1047
1048   auto liveset = result.liveset;
1049   auto PointerToBase = result.PointerToBase;
1050
1051   auto is_live_gc_reference =
1052       [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
1053
1054   // For each new definition, check to see if a) the definition dominates the
1055   // instruction we're interested in, and b) one of the uses of that definition
1056   // is edge-reachable from the instruction we're interested in.  This is the
1057   // same definition of liveness we used in the intial liveness analysis
1058   for (Value *newDef : allInsertedDefs) {
1059     if (liveset.count(newDef)) {
1060       // already live, no action needed
1061       continue;
1062     }
1063
1064     // PERF: Use DT to check instruction domination might not be good for
1065     // compilation time, and we could change to optimal solution if this
1066     // turn to be a issue
1067     if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1068       // can't possibly be live at inst
1069       continue;
1070     }
1071
1072     if (is_live_gc_reference(*newDef)) {
1073       // Add the live new defs into liveset and PointerToBase
1074       liveset.insert(newDef);
1075       PointerToBase[newDef] = newDef;
1076     }
1077   }
1078
1079   result.liveset = liveset;
1080   result.PointerToBase = PointerToBase;
1081 }
1082
1083 static void fixupLiveReferences(
1084     Function &F, DominatorTree &DT, Pass *P,
1085     const DenseSet<llvm::Value *> &allInsertedDefs,
1086     ArrayRef<CallSite> toUpdate,
1087     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1088   for (size_t i = 0; i < records.size(); i++) {
1089     struct PartiallyConstructedSafepointRecord &info = records[i];
1090     const CallSite &CS = toUpdate[i];
1091     fixupLiveness(DT, CS, allInsertedDefs, info);
1092   }
1093 }
1094
1095 // Normalize basic block to make it ready to be target of invoke statepoint.
1096 // It means spliting it to have single predecessor. Return newly created BB
1097 // ready to be successor of invoke statepoint.
1098 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1099                                                  BasicBlock *InvokeParent,
1100                                                  Pass *P) {
1101   BasicBlock *ret = BB;
1102
1103   if (!BB->getUniquePredecessor()) {
1104     ret = SplitBlockPredecessors(BB, InvokeParent, "");
1105   }
1106
1107   // Another requirement for such basic blocks is to not have any phi nodes.
1108   // Since we just ensured that new BB will have single predecessor,
1109   // all phi nodes in it will have one value. Here it would be naturall place
1110   // to
1111   // remove them all. But we can not do this because we are risking to remove
1112   // one of the values stored in liveset of another statepoint. We will do it
1113   // later after placing all safepoints.
1114
1115   return ret;
1116 }
1117
1118 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1119   auto itr = std::find(livevec.begin(), livevec.end(), val);
1120   assert(livevec.end() != itr);
1121   size_t index = std::distance(livevec.begin(), itr);
1122   assert(index < livevec.size());
1123   return index;
1124 }
1125
1126 // Create new attribute set containing only attributes which can be transfered
1127 // from original call to the safepoint.
1128 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1129   AttributeSet ret;
1130
1131   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1132     unsigned index = AS.getSlotIndex(Slot);
1133
1134     if (index == AttributeSet::ReturnIndex ||
1135         index == AttributeSet::FunctionIndex) {
1136
1137       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1138            ++it) {
1139         Attribute attr = *it;
1140
1141         // Do not allow certain attributes - just skip them
1142         // Safepoint can not be read only or read none.
1143         if (attr.hasAttribute(Attribute::ReadNone) ||
1144             attr.hasAttribute(Attribute::ReadOnly))
1145           continue;
1146
1147         ret = ret.addAttributes(
1148             AS.getContext(), index,
1149             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1150       }
1151     }
1152
1153     // Just skip parameter attributes for now
1154   }
1155
1156   return ret;
1157 }
1158
1159 /// Helper function to place all gc relocates necessary for the given
1160 /// statepoint.
1161 /// Inputs:
1162 ///   liveVariables - list of variables to be relocated.
1163 ///   liveStart - index of the first live variable.
1164 ///   basePtrs - base pointers.
1165 ///   statepointToken - statepoint instruction to which relocates should be
1166 ///   bound.
1167 ///   Builder - Llvm IR builder to be used to construct new calls.
1168 void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1169                        const int liveStart,
1170                        ArrayRef<llvm::Value *> basePtrs,
1171                        Instruction *statepointToken, IRBuilder<> Builder) {
1172
1173   SmallVector<Instruction *, 64> NewDefs;
1174   NewDefs.reserve(liveVariables.size());
1175
1176   Module *M = statepointToken->getParent()->getParent()->getParent();
1177
1178   for (unsigned i = 0; i < liveVariables.size(); i++) {
1179     // We generate a (potentially) unique declaration for every pointer type
1180     // combination.  This results is some blow up the function declarations in
1181     // the IR, but removes the need for argument bitcasts which shrinks the IR
1182     // greatly and makes it much more readable.
1183     SmallVector<Type *, 1> types;                    // one per 'any' type
1184     types.push_back(liveVariables[i]->getType()); // result type
1185     Value *gc_relocate_decl = Intrinsic::getDeclaration(
1186         M, Intrinsic::experimental_gc_relocate, types);
1187
1188     // Generate the gc.relocate call and save the result
1189     Value *baseIdx =
1190         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1191                          liveStart + find_index(liveVariables, basePtrs[i]));
1192     Value *liveIdx = ConstantInt::get(
1193         Type::getInt32Ty(M->getContext()),
1194         liveStart + find_index(liveVariables, liveVariables[i]));
1195
1196     // only specify a debug name if we can give a useful one
1197     Value *reloc = Builder.CreateCall3(
1198         gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1199         liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1200                                     : "");
1201     // Trick CodeGen into thinking there are lots of free registers at this
1202     // fake call.
1203     cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1204
1205     NewDefs.push_back(cast<Instruction>(reloc));
1206   }
1207   assert(NewDefs.size() == liveVariables.size() &&
1208          "missing or extra redefinition at safepoint");
1209 }
1210
1211 static void
1212 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1213                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1214                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1215                            Pass *P,
1216                            PartiallyConstructedSafepointRecord &result) {
1217   assert(basePtrs.size() == liveVariables.size());
1218   assert(isStatepoint(CS) &&
1219          "This method expects to be rewriting a statepoint");
1220
1221   BasicBlock *BB = CS.getInstruction()->getParent();
1222   assert(BB);
1223   Function *F = BB->getParent();
1224   assert(F && "must be set");
1225   Module *M = F->getParent();
1226   (void)M;
1227   assert(M && "must be set");
1228
1229   // We're not changing the function signature of the statepoint since the gc
1230   // arguments go into the var args section.
1231   Function *gc_statepoint_decl = CS.getCalledFunction();
1232
1233   // Then go ahead and use the builder do actually do the inserts.  We insert
1234   // immediately before the previous instruction under the assumption that all
1235   // arguments will be available here.  We can't insert afterwards since we may
1236   // be replacing a terminator.
1237   Instruction *insertBefore = CS.getInstruction();
1238   IRBuilder<> Builder(insertBefore);
1239   // Copy all of the arguments from the original statepoint - this includes the
1240   // target, call args, and deopt args
1241   SmallVector<llvm::Value *, 64> args;
1242   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1243   // TODO: Clear the 'needs rewrite' flag
1244
1245   // add all the pointers to be relocated (gc arguments)
1246   // Capture the start of the live variable list for use in the gc_relocates
1247   const int live_start = args.size();
1248   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1249
1250   // Create the statepoint given all the arguments
1251   Instruction *token = nullptr;
1252   AttributeSet return_attributes;
1253   if (CS.isCall()) {
1254     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1255     CallInst *call =
1256         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1257     call->setTailCall(toReplace->isTailCall());
1258     call->setCallingConv(toReplace->getCallingConv());
1259
1260     // Currently we will fail on parameter attributes and on certain
1261     // function attributes.
1262     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1263     // In case if we can handle this set of sttributes - set up function attrs
1264     // directly on statepoint and return attrs later for gc_result intrinsic.
1265     call->setAttributes(new_attrs.getFnAttributes());
1266     return_attributes = new_attrs.getRetAttributes();
1267
1268     token = call;
1269
1270     // Put the following gc_result and gc_relocate calls immediately after the
1271     // the old call (which we're about to delete)
1272     BasicBlock::iterator next(toReplace);
1273     assert(BB->end() != next && "not a terminator, must have next");
1274     next++;
1275     Instruction *IP = &*(next);
1276     Builder.SetInsertPoint(IP);
1277     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1278
1279   } else {
1280     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1281
1282     // Insert the new invoke into the old block.  We'll remove the old one in a
1283     // moment at which point this will become the new terminator for the
1284     // original block.
1285     InvokeInst *invoke = InvokeInst::Create(
1286         gc_statepoint_decl, toReplace->getNormalDest(),
1287         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1288     invoke->setCallingConv(toReplace->getCallingConv());
1289
1290     // Currently we will fail on parameter attributes and on certain
1291     // function attributes.
1292     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1293     // In case if we can handle this set of sttributes - set up function attrs
1294     // directly on statepoint and return attrs later for gc_result intrinsic.
1295     invoke->setAttributes(new_attrs.getFnAttributes());
1296     return_attributes = new_attrs.getRetAttributes();
1297
1298     token = invoke;
1299
1300     // Generate gc relocates in exceptional path
1301     BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1302         toReplace->getUnwindDest(), invoke->getParent(), P);
1303
1304     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1305     Builder.SetInsertPoint(IP);
1306     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1307
1308     // Extract second element from landingpad return value. We will attach
1309     // exceptional gc relocates to it.
1310     const unsigned idx = 1;
1311     Instruction *exceptional_token =
1312         cast<Instruction>(Builder.CreateExtractValue(
1313             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1314     result.UnwindToken = exceptional_token;
1315
1316     // Just throw away return value. We will use the one we got for normal
1317     // block.
1318     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1319                             exceptional_token, Builder);
1320
1321     // Generate gc relocates and returns for normal block
1322     BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1323         toReplace->getNormalDest(), invoke->getParent(), P);
1324
1325     IP = &*(normalDest->getFirstInsertionPt());
1326     Builder.SetInsertPoint(IP);
1327
1328     // gc relocates will be generated later as if it were regular call
1329     // statepoint
1330   }
1331   assert(token);
1332
1333   // Take the name of the original value call if it had one.
1334   token->takeName(CS.getInstruction());
1335
1336   // The GCResult is already inserted, we just need to find it
1337 #ifndef NDEBUG
1338   Instruction *toReplace = CS.getInstruction();
1339   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1340          "only valid use before rewrite is gc.result");
1341   assert(!toReplace->hasOneUse() ||
1342          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1343 #endif
1344
1345   // Update the gc.result of the original statepoint (if any) to use the newly
1346   // inserted statepoint.  This is safe to do here since the token can't be
1347   // considered a live reference.
1348   CS.getInstruction()->replaceAllUsesWith(token);
1349
1350   result.StatepointToken = token;
1351
1352   // Second, create a gc.relocate for every live variable
1353   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1354
1355 }
1356
1357 namespace {
1358 struct name_ordering {
1359   Value *base;
1360   Value *derived;
1361   bool operator()(name_ordering const &a, name_ordering const &b) {
1362     return -1 == a.derived->getName().compare(b.derived->getName());
1363   }
1364 };
1365 }
1366 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1367                            SmallVectorImpl<Value *> &livevec) {
1368   assert(basevec.size() == livevec.size());
1369
1370   SmallVector<name_ordering, 64> temp;
1371   for (size_t i = 0; i < basevec.size(); i++) {
1372     name_ordering v;
1373     v.base = basevec[i];
1374     v.derived = livevec[i];
1375     temp.push_back(v);
1376   }
1377   std::sort(temp.begin(), temp.end(), name_ordering());
1378   for (size_t i = 0; i < basevec.size(); i++) {
1379     basevec[i] = temp[i].base;
1380     livevec[i] = temp[i].derived;
1381   }
1382 }
1383
1384 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1385 // which make the relocations happening at this safepoint explicit.
1386 // 
1387 // WARNING: Does not do any fixup to adjust users of the original live
1388 // values.  That's the callers responsibility.
1389 static void
1390 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1391                        PartiallyConstructedSafepointRecord &result) {
1392   auto liveset = result.liveset;
1393   auto PointerToBase = result.PointerToBase;
1394
1395   // Convert to vector for efficient cross referencing.
1396   SmallVector<Value *, 64> basevec, livevec;
1397   livevec.reserve(liveset.size());
1398   basevec.reserve(liveset.size());
1399   for (Value *L : liveset) {
1400     livevec.push_back(L);
1401
1402     assert(PointerToBase.find(L) != PointerToBase.end());
1403     Value *base = PointerToBase[L];
1404     basevec.push_back(base);
1405   }
1406   assert(livevec.size() == basevec.size());
1407
1408   // To make the output IR slightly more stable (for use in diffs), ensure a
1409   // fixed order of the values in the safepoint (by sorting the value name).
1410   // The order is otherwise meaningless.
1411   stablize_order(basevec, livevec);
1412
1413   // Do the actual rewriting and delete the old statepoint
1414   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1415   CS.getInstruction()->eraseFromParent();
1416 }
1417
1418 // Helper function for the relocationViaAlloca.
1419 // It receives iterator to the statepoint gc relocates and emits store to the
1420 // assigned
1421 // location (via allocaMap) for the each one of them.
1422 // Add visited values into the visitedLiveValues set we will later use them
1423 // for sanity check.
1424 static void
1425 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1426                        DenseMap<Value *, Value *> &allocaMap,
1427                        DenseSet<Value *> &visitedLiveValues) {
1428
1429   for (User *U : gcRelocs) {
1430     if (!isa<IntrinsicInst>(U))
1431       continue;
1432
1433     IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1434
1435     // We only care about relocates
1436     if (relocatedValue->getIntrinsicID() !=
1437         Intrinsic::experimental_gc_relocate) {
1438       continue;
1439     }
1440
1441     GCRelocateOperands relocateOperands(relocatedValue);
1442     Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1443     assert(allocaMap.count(originalValue));
1444     Value *alloca = allocaMap[originalValue];
1445
1446     // Emit store into the related alloca
1447     StoreInst *store = new StoreInst(relocatedValue, alloca);
1448     store->insertAfter(relocatedValue);
1449
1450 #ifndef NDEBUG
1451     visitedLiveValues.insert(originalValue);
1452 #endif
1453   }
1454 }
1455
1456 /// do all the relocation update via allocas and mem2reg
1457 static void relocationViaAlloca(
1458     Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1459     ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1460 #ifndef NDEBUG
1461   int initialAllocaNum = 0;
1462
1463   // record initial number of allocas
1464   for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1465        itr++) {
1466     if (isa<AllocaInst>(*itr))
1467       initialAllocaNum++;
1468   }
1469 #endif
1470
1471   // TODO-PERF: change data structures, reserve
1472   DenseMap<Value *, Value *> allocaMap;
1473   SmallVector<AllocaInst *, 200> PromotableAllocas;
1474   PromotableAllocas.reserve(live.size());
1475
1476   // emit alloca for each live gc pointer
1477   for (unsigned i = 0; i < live.size(); i++) {
1478     Value *liveValue = live[i];
1479     AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1480                                         F.getEntryBlock().getFirstNonPHI());
1481     allocaMap[liveValue] = alloca;
1482     PromotableAllocas.push_back(alloca);
1483   }
1484
1485   // The next two loops are part of the same conceptual operation.  We need to
1486   // insert a store to the alloca after the original def and at each
1487   // redefinition.  We need to insert a load before each use.  These are split
1488   // into distinct loops for performance reasons.
1489
1490   // update gc pointer after each statepoint
1491   // either store a relocated value or null (if no relocated value found for
1492   // this gc pointer and it is not a gc_result)
1493   // this must happen before we update the statepoint with load of alloca
1494   // otherwise we lose the link between statepoint and old def
1495   for (size_t i = 0; i < records.size(); i++) {
1496     const struct PartiallyConstructedSafepointRecord &info = records[i];
1497     Value *Statepoint = info.StatepointToken;
1498
1499     // This will be used for consistency check
1500     DenseSet<Value *> visitedLiveValues;
1501
1502     // Insert stores for normal statepoint gc relocates
1503     insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
1504
1505     // In case if it was invoke statepoint
1506     // we will insert stores for exceptional path gc relocates.
1507     if (isa<InvokeInst>(Statepoint)) {
1508       insertRelocationStores(info.UnwindToken->users(),
1509                              allocaMap, visitedLiveValues);
1510     }
1511
1512 #ifndef NDEBUG
1513     // As a debuging aid, pretend that an unrelocated pointer becomes null at
1514     // the gc.statepoint.  This will turn some subtle GC problems into slightly
1515     // easier to debug SEGVs
1516     SmallVector<AllocaInst *, 64> ToClobber;
1517     for (auto Pair : allocaMap) {
1518       Value *Def = Pair.first;
1519       AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1520
1521       // This value was relocated
1522       if (visitedLiveValues.count(Def)) {
1523         continue;
1524       }
1525       ToClobber.push_back(Alloca);
1526     }
1527
1528     auto InsertClobbersAt = [&](Instruction *IP) {
1529       for (auto *AI : ToClobber) {
1530         auto AIType = cast<PointerType>(AI->getType());
1531         auto PT = cast<PointerType>(AIType->getElementType());
1532         Constant *CPN = ConstantPointerNull::get(PT);
1533         StoreInst *store = new StoreInst(CPN, AI);
1534         store->insertBefore(IP);
1535       }
1536     };
1537
1538     // Insert the clobbering stores.  These may get intermixed with the
1539     // gc.results and gc.relocates, but that's fine.  
1540     if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1541       InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1542       InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1543     } else {
1544       BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1545       Next++;
1546       InsertClobbersAt(Next);
1547     }
1548 #endif
1549   }
1550   // update use with load allocas and add store for gc_relocated
1551   for (auto Pair : allocaMap) {
1552     Value *def = Pair.first;
1553     Value *alloca = Pair.second;
1554
1555     // we pre-record the uses of allocas so that we dont have to worry about
1556     // later update
1557     // that change the user information.
1558     SmallVector<Instruction *, 20> uses;
1559     // PERF: trade a linear scan for repeated reallocation
1560     uses.reserve(std::distance(def->user_begin(), def->user_end()));
1561     for (User *U : def->users()) {
1562       if (!isa<ConstantExpr>(U)) {
1563         // If the def has a ConstantExpr use, then the def is either a
1564         // ConstantExpr use itself or null.  In either case
1565         // (recursively in the first, directly in the second), the oop
1566         // it is ultimately dependent on is null and this particular
1567         // use does not need to be fixed up.
1568         uses.push_back(cast<Instruction>(U));
1569       }
1570     }
1571
1572     std::sort(uses.begin(), uses.end());
1573     auto last = std::unique(uses.begin(), uses.end());
1574     uses.erase(last, uses.end());
1575
1576     for (Instruction *use : uses) {
1577       if (isa<PHINode>(use)) {
1578         PHINode *phi = cast<PHINode>(use);
1579         for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1580           if (def == phi->getIncomingValue(i)) {
1581             LoadInst *load = new LoadInst(
1582                 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1583             phi->setIncomingValue(i, load);
1584           }
1585         }
1586       } else {
1587         LoadInst *load = new LoadInst(alloca, "", use);
1588         use->replaceUsesOfWith(def, load);
1589       }
1590     }
1591
1592     // emit store for the initial gc value
1593     // store must be inserted after load, otherwise store will be in alloca's
1594     // use list and an extra load will be inserted before it
1595     StoreInst *store = new StoreInst(def, alloca);
1596     if (isa<Instruction>(def)) {
1597       store->insertAfter(cast<Instruction>(def));
1598     } else {
1599       assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1600               (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1601              "Must be argument or global");
1602       store->insertAfter(cast<Instruction>(alloca));
1603     }
1604   }
1605
1606   assert(PromotableAllocas.size() == live.size() &&
1607          "we must have the same allocas with lives");
1608   if (!PromotableAllocas.empty()) {
1609     // apply mem2reg to promote alloca to SSA
1610     PromoteMemToReg(PromotableAllocas, DT);
1611   }
1612
1613 #ifndef NDEBUG
1614   for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1615        itr++) {
1616     if (isa<AllocaInst>(*itr))
1617       initialAllocaNum--;
1618   }
1619   assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1620 #endif
1621 }
1622
1623 /// Implement a unique function which doesn't require we sort the input
1624 /// vector.  Doing so has the effect of changing the output of a couple of
1625 /// tests in ways which make them less useful in testing fused safepoints.
1626 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1627   DenseSet<T> Seen;
1628   SmallVector<T, 128> TempVec;
1629   TempVec.reserve(Vec.size());
1630   for (auto Element : Vec)
1631     TempVec.push_back(Element);
1632   Vec.clear();
1633   for (auto V : TempVec) {
1634     if (Seen.insert(V).second) {
1635       Vec.push_back(V);
1636     }
1637   }
1638 }
1639
1640 static Function *getUseHolder(Module &M) {
1641   FunctionType *ftype =
1642       FunctionType::get(Type::getVoidTy(M.getContext()), true);
1643   Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1644   return Func;
1645 }
1646
1647 /// Insert holders so that each Value is obviously live through the entire
1648 /// liftetime of the call.
1649 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1650                                  SmallVectorImpl<CallInst *> &holders) {
1651   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1652   Function *Func = getUseHolder(*M);
1653   if (CS.isCall()) {
1654     // For call safepoints insert dummy calls right after safepoint
1655     BasicBlock::iterator next(CS.getInstruction());
1656     next++;
1657     CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1658     holders.push_back(base_holder);
1659   } else if (CS.isInvoke()) {
1660     // For invoke safepooints insert dummy calls both in normal and
1661     // exceptional destination blocks
1662     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1663     CallInst *normal_holder = CallInst::Create(
1664         Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1665     CallInst *unwind_holder = CallInst::Create(
1666         Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1667     holders.push_back(normal_holder);
1668     holders.push_back(unwind_holder);
1669   } else
1670     llvm_unreachable("unsupported call type");
1671 }
1672
1673 static void findLiveReferences(
1674     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1675     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1676   for (size_t i = 0; i < records.size(); i++) {
1677     struct PartiallyConstructedSafepointRecord &info = records[i];
1678     const CallSite &CS = toUpdate[i];
1679     analyzeParsePointLiveness(DT, CS, info);
1680   }
1681 }
1682
1683 static void addBasesAsLiveValues(StatepointLiveSetTy &liveset,
1684                                  DenseMap<Value *, Value *> &PointerToBase) {
1685   // Identify any base pointers which are used in this safepoint, but not
1686   // themselves relocated.  We need to relocate them so that later inserted
1687   // safepoints can get the properly relocated base register.
1688   DenseSet<Value *> missing;
1689   for (Value *L : liveset) {
1690     assert(PointerToBase.find(L) != PointerToBase.end());
1691     Value *base = PointerToBase[L];
1692     assert(base);
1693     if (liveset.find(base) == liveset.end()) {
1694       assert(PointerToBase.find(base) == PointerToBase.end());
1695       // uniqued by set insert
1696       missing.insert(base);
1697     }
1698   }
1699
1700   // Note that we want these at the end of the list, otherwise
1701   // register placement gets screwed up once we lower to STATEPOINT
1702   // instructions.  This is an utter hack, but there doesn't seem to be a
1703   // better one.
1704   for (Value *base : missing) {
1705     assert(base);
1706     liveset.insert(base);
1707     PointerToBase[base] = base;
1708   }
1709   assert(liveset.size() == PointerToBase.size());
1710 }
1711
1712 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1713                               SmallVectorImpl<CallSite> &toUpdate) {
1714 #ifndef NDEBUG
1715   // sanity check the input
1716   std::set<CallSite> uniqued;
1717   uniqued.insert(toUpdate.begin(), toUpdate.end());
1718   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1719
1720   for (size_t i = 0; i < toUpdate.size(); i++) {
1721     CallSite &CS = toUpdate[i];
1722     assert(CS.getInstruction()->getParent()->getParent() == &F);
1723     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1724   }
1725 #endif
1726
1727   // A list of dummy calls added to the IR to keep various values obviously
1728   // live in the IR.  We'll remove all of these when done.
1729   SmallVector<CallInst *, 64> holders;
1730
1731   // Insert a dummy call with all of the arguments to the vm_state we'll need
1732   // for the actual safepoint insertion.  This ensures reference arguments in
1733   // the deopt argument list are considered live through the safepoint (and
1734   // thus makes sure they get relocated.)
1735   for (size_t i = 0; i < toUpdate.size(); i++) {
1736     CallSite &CS = toUpdate[i];
1737     Statepoint StatepointCS(CS);
1738
1739     SmallVector<Value *, 64> DeoptValues;
1740     for (Use &U : StatepointCS.vm_state_args()) {
1741       Value *Arg = cast<Value>(&U);
1742       if (isGCPointerType(Arg->getType()))
1743         DeoptValues.push_back(Arg);
1744     }
1745     insertUseHolderAfter(CS, DeoptValues, holders);
1746   }
1747
1748   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
1749   records.reserve(toUpdate.size());
1750   for (size_t i = 0; i < toUpdate.size(); i++) {
1751     struct PartiallyConstructedSafepointRecord info;
1752     records.push_back(info);
1753   }
1754   assert(records.size() == toUpdate.size());
1755
1756   // A) Identify all gc pointers which are staticly live at the given call
1757   // site.
1758   findLiveReferences(F, DT, P, toUpdate, records);
1759
1760   // B) Find the base pointers for each live pointer
1761   /* scope for caching */ {
1762     // Cache the 'defining value' relation used in the computation and
1763     // insertion of base phis and selects.  This ensures that we don't insert
1764     // large numbers of duplicate base_phis.
1765     DefiningValueMapTy DVCache;
1766
1767     for (size_t i = 0; i < records.size(); i++) {
1768       struct PartiallyConstructedSafepointRecord &info = records[i];
1769       CallSite &CS = toUpdate[i];
1770       findBasePointers(DT, DVCache, CS, info);
1771     }
1772   } // end of cache scope
1773
1774   // The base phi insertion logic (for any safepoint) may have inserted new
1775   // instructions which are now live at some safepoint.  The simplest such
1776   // example is:
1777   // loop:
1778   //   phi a  <-- will be a new base_phi here
1779   //   safepoint 1 <-- that needs to be live here
1780   //   gep a + 1
1781   //   safepoint 2
1782   //   br loop
1783   DenseSet<llvm::Value *> allInsertedDefs;
1784   for (size_t i = 0; i < records.size(); i++) {
1785     struct PartiallyConstructedSafepointRecord &info = records[i];
1786     allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1787                            info.NewInsertedDefs.end());
1788   }
1789
1790   // We insert some dummy calls after each safepoint to definitely hold live
1791   // the base pointers which were identified for that safepoint.  We'll then
1792   // ask liveness for _every_ base inserted to see what is now live.  Then we
1793   // remove the dummy calls.
1794   holders.reserve(holders.size() + records.size());
1795   for (size_t i = 0; i < records.size(); i++) {
1796     struct PartiallyConstructedSafepointRecord &info = records[i];
1797     CallSite &CS = toUpdate[i];
1798
1799     SmallVector<Value *, 128> Bases;
1800     for (auto Pair : info.PointerToBase) {
1801       Bases.push_back(Pair.second);
1802     }
1803     insertUseHolderAfter(CS, Bases, holders);
1804   }
1805
1806   // Add the bases explicitly to the live vector set.  This may result in a few
1807   // extra relocations, but the base has to be available whenever a pointer
1808   // derived from it is used.  Thus, we need it to be part of the statepoint's
1809   // gc arguments list.  TODO: Introduce an explicit notion (in the following
1810   // code) of the GC argument list as seperate from the live Values at a
1811   // given statepoint.
1812   for (size_t i = 0; i < records.size(); i++) {
1813     struct PartiallyConstructedSafepointRecord &info = records[i];
1814     addBasesAsLiveValues(info.liveset, info.PointerToBase);
1815   }
1816
1817   // If we inserted any new values, we need to adjust our notion of what is
1818   // live at a particular safepoint.
1819   if (!allInsertedDefs.empty()) {
1820     fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1821   }
1822   if (PrintBasePointers) {
1823     for (size_t i = 0; i < records.size(); i++) {
1824       struct PartiallyConstructedSafepointRecord &info = records[i];
1825       errs() << "Base Pairs: (w/Relocation)\n";
1826       for (auto Pair : info.PointerToBase) {
1827         errs() << " derived %" << Pair.first->getName() << " base %"
1828                << Pair.second->getName() << "\n";
1829       }
1830     }
1831   }
1832   for (size_t i = 0; i < holders.size(); i++) {
1833     holders[i]->eraseFromParent();
1834     holders[i] = nullptr;
1835   }
1836   holders.clear();
1837
1838   // Now run through and replace the existing statepoints with new ones with
1839   // the live variables listed.  We do not yet update uses of the values being
1840   // relocated. We have references to live variables that need to
1841   // survive to the last iteration of this loop.  (By construction, the
1842   // previous statepoint can not be a live variable, thus we can and remove
1843   // the old statepoint calls as we go.)
1844   for (size_t i = 0; i < records.size(); i++) {
1845     struct PartiallyConstructedSafepointRecord &info = records[i];
1846     CallSite &CS = toUpdate[i];
1847     makeStatepointExplicit(DT, CS, P, info);
1848   }
1849   toUpdate.clear(); // prevent accident use of invalid CallSites
1850
1851   // In case if we inserted relocates in a different basic block than the
1852   // original safepoint (this can happen for invokes). We need to be sure that
1853   // original values were not used in any of the phi nodes at the
1854   // beginning of basic block containing them. Because we know that all such
1855   // blocks will have single predecessor we can safely assume that all phi
1856   // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1857   // Just remove them all here.
1858   for (size_t i = 0; i < records.size(); i++) {
1859     Instruction *I = records[i].StatepointToken;
1860
1861     if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1862       FoldSingleEntryPHINodes(invoke->getNormalDest());
1863       assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1864
1865       FoldSingleEntryPHINodes(invoke->getUnwindDest());
1866       assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1867     }
1868   }
1869
1870   // Do all the fixups of the original live variables to their relocated selves
1871   SmallVector<Value *, 128> live;
1872   for (size_t i = 0; i < records.size(); i++) {
1873     struct PartiallyConstructedSafepointRecord &info = records[i];
1874     // We can't simply save the live set from the original insertion.  One of
1875     // the live values might be the result of a call which needs a safepoint.
1876     // That Value* no longer exists and we need to use the new gc_result.
1877     // Thankfully, the liveset is embedded in the statepoint (and updated), so
1878     // we just grab that.
1879     Statepoint statepoint(info.StatepointToken);
1880     live.insert(live.end(), statepoint.gc_args_begin(),
1881                 statepoint.gc_args_end());
1882   }
1883   unique_unsorted(live);
1884
1885 #ifndef NDEBUG
1886   // sanity check
1887   for (auto ptr : live) {
1888     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1889   }
1890 #endif
1891
1892   relocationViaAlloca(F, DT, live, records);
1893   return !records.empty();
1894 }
1895
1896 /// Returns true if this function should be rewritten by this pass.  The main
1897 /// point of this function is as an extension point for custom logic.
1898 static bool shouldRewriteStatepointsIn(Function &F) {
1899   // TODO: This should check the GCStrategy
1900   if (F.hasGC()) {
1901     const std::string StatepointExampleName("statepoint-example");
1902     return StatepointExampleName == F.getGC();
1903   } else
1904     return false;
1905 }
1906
1907 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1908   // Nothing to do for declarations.
1909   if (F.isDeclaration() || F.empty())
1910     return false;
1911
1912   // Policy choice says not to rewrite - the most common reason is that we're
1913   // compiling code without a GCStrategy.
1914   if (!shouldRewriteStatepointsIn(F))
1915     return false;
1916
1917   // Gather all the statepoints which need rewritten.
1918   SmallVector<CallSite, 64> ParsePointNeeded;
1919   for (Instruction &I : inst_range(F)) {
1920     // TODO: only the ones with the flag set!
1921     if (isStatepoint(I))
1922       ParsePointNeeded.push_back(CallSite(&I));
1923   }
1924
1925   // Return early if no work to do.
1926   if (ParsePointNeeded.empty())
1927     return false;
1928
1929   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1930   return insertParsePoints(F, DT, this, ParsePointNeeded);
1931 }