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