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