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