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