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