[NFCI] Change RewriteStatepointsForGC to a ModulePass.
[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/Analysis/TargetTransformInfo.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Statepoint.h"
34 #include "llvm/IR/Value.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Transforms/Utils/Cloning.h"
41 #include "llvm/Transforms/Utils/Local.h"
42 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
43
44 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
45
46 using namespace llvm;
47
48 // Print tracing output
49 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
50                               cl::init(false));
51
52 // Print the liveset found at the insert location
53 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
54                                   cl::init(false));
55 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
56                                       cl::init(false));
57 // Print out the base pointers for debugging
58 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
59                                        cl::init(false));
60
61 // Cost threshold measuring when it is profitable to rematerialize value instead
62 // of relocating it
63 static cl::opt<unsigned>
64 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
65                            cl::init(6));
66
67 #ifdef XDEBUG
68 static bool ClobberNonLive = true;
69 #else
70 static bool ClobberNonLive = false;
71 #endif
72 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
73                                                   cl::location(ClobberNonLive),
74                                                   cl::Hidden);
75
76 namespace {
77 struct RewriteStatepointsForGC : public ModulePass {
78   static char ID; // Pass identification, replacement for typeid
79
80   RewriteStatepointsForGC() : ModulePass(ID) {
81     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
82   }
83   bool runOnFunction(Function &F);
84   bool runOnModule(Module &M) override {
85     bool Changed = false;
86     for (Function &F : M)
87       Changed |= runOnFunction(F);
88     return Changed;
89   }
90
91   void getAnalysisUsage(AnalysisUsage &AU) const override {
92     // We add and rewrite a bunch of instructions, but don't really do much
93     // else.  We could in theory preserve a lot more analyses here.
94     AU.addRequired<DominatorTreeWrapperPass>();
95     AU.addRequired<TargetTransformInfoWrapperPass>();
96   }
97 };
98 } // namespace
99
100 char RewriteStatepointsForGC::ID = 0;
101
102 ModulePass *llvm::createRewriteStatepointsForGCPass() {
103   return new RewriteStatepointsForGC();
104 }
105
106 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
107                       "Make relocations explicit at statepoints", false, false)
108 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
109 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
110                     "Make relocations explicit at statepoints", false, false)
111
112 namespace {
113 struct GCPtrLivenessData {
114   /// Values defined in this block.
115   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
116   /// Values used in this block (and thus live); does not included values
117   /// killed within this block.
118   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
119
120   /// Values live into this basic block (i.e. used by any
121   /// instruction in this basic block or ones reachable from here)
122   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
123
124   /// Values live out of this basic block (i.e. live into
125   /// any successor block)
126   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
127 };
128
129 // The type of the internal cache used inside the findBasePointers family
130 // of functions.  From the callers perspective, this is an opaque type and
131 // should not be inspected.
132 //
133 // In the actual implementation this caches two relations:
134 // - The base relation itself (i.e. this pointer is based on that one)
135 // - The base defining value relation (i.e. before base_phi insertion)
136 // Generally, after the execution of a full findBasePointer call, only the
137 // base relation will remain.  Internally, we add a mixture of the two
138 // types, then update all the second type to the first type
139 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
140 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
141 typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
142
143 struct PartiallyConstructedSafepointRecord {
144   /// The set of values known to be live accross this safepoint
145   StatepointLiveSetTy liveset;
146
147   /// Mapping from live pointers to a base-defining-value
148   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
149
150   /// The *new* gc.statepoint instruction itself.  This produces the token
151   /// that normal path gc.relocates and the gc.result are tied to.
152   Instruction *StatepointToken;
153
154   /// Instruction to which exceptional gc relocates are attached
155   /// Makes it easier to iterate through them during relocationViaAlloca.
156   Instruction *UnwindToken;
157
158   /// Record live values we are rematerialized instead of relocating.
159   /// They are not included into 'liveset' field.
160   /// Maps rematerialized copy to it's original value.
161   RematerializedValueMapTy RematerializedValues;
162 };
163 }
164
165 /// Compute the live-in set for every basic block in the function
166 static void computeLiveInValues(DominatorTree &DT, Function &F,
167                                 GCPtrLivenessData &Data);
168
169 /// Given results from the dataflow liveness computation, find the set of live
170 /// Values at a particular instruction.
171 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
172                               StatepointLiveSetTy &out);
173
174 // TODO: Once we can get to the GCStrategy, this becomes
175 // Optional<bool> isGCManagedPointer(const Value *V) const override {
176
177 static bool isGCPointerType(const Type *T) {
178   if (const PointerType *PT = dyn_cast<PointerType>(T))
179     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
180     // GC managed heap.  We know that a pointer into this heap needs to be
181     // updated and that no other pointer does.
182     return (1 == PT->getAddressSpace());
183   return false;
184 }
185
186 // Return true if this type is one which a) is a gc pointer or contains a GC
187 // pointer and b) is of a type this code expects to encounter as a live value.
188 // (The insertion code will assert that a type which matches (a) and not (b)
189 // is not encountered.)
190 static bool isHandledGCPointerType(Type *T) {
191   // We fully support gc pointers
192   if (isGCPointerType(T))
193     return true;
194   // We partially support vectors of gc pointers. The code will assert if it
195   // can't handle something.
196   if (auto VT = dyn_cast<VectorType>(T))
197     if (isGCPointerType(VT->getElementType()))
198       return true;
199   return false;
200 }
201
202 #ifndef NDEBUG
203 /// Returns true if this type contains a gc pointer whether we know how to
204 /// handle that type or not.
205 static bool containsGCPtrType(Type *Ty) {
206   if (isGCPointerType(Ty))
207     return true;
208   if (VectorType *VT = dyn_cast<VectorType>(Ty))
209     return isGCPointerType(VT->getScalarType());
210   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
211     return containsGCPtrType(AT->getElementType());
212   if (StructType *ST = dyn_cast<StructType>(Ty))
213     return std::any_of(
214         ST->subtypes().begin(), ST->subtypes().end(),
215         [](Type *SubType) { return containsGCPtrType(SubType); });
216   return false;
217 }
218
219 // Returns true if this is a type which a) is a gc pointer or contains a GC
220 // pointer and b) is of a type which the code doesn't expect (i.e. first class
221 // aggregates).  Used to trip assertions.
222 static bool isUnhandledGCPointerType(Type *Ty) {
223   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
224 }
225 #endif
226
227 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
228   if (a->hasName() && b->hasName()) {
229     return -1 == a->getName().compare(b->getName());
230   } else if (a->hasName() && !b->hasName()) {
231     return true;
232   } else if (!a->hasName() && b->hasName()) {
233     return false;
234   } else {
235     // Better than nothing, but not stable
236     return a < b;
237   }
238 }
239
240 // Conservatively identifies any definitions which might be live at the
241 // given instruction. The  analysis is performed immediately before the
242 // given instruction. Values defined by that instruction are not considered
243 // live.  Values used by that instruction are considered live.
244 static void analyzeParsePointLiveness(
245     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
246     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
247   Instruction *inst = CS.getInstruction();
248
249   StatepointLiveSetTy liveset;
250   findLiveSetAtInst(inst, OriginalLivenessData, liveset);
251
252   if (PrintLiveSet) {
253     // Note: This output is used by several of the test cases
254     // The order of elemtns in a set is not stable, put them in a vec and sort
255     // by name
256     SmallVector<Value *, 64> temp;
257     temp.insert(temp.end(), liveset.begin(), liveset.end());
258     std::sort(temp.begin(), temp.end(), order_by_name);
259     errs() << "Live Variables:\n";
260     for (Value *V : temp) {
261       errs() << " " << V->getName(); // no newline
262       V->dump();
263     }
264   }
265   if (PrintLiveSetSize) {
266     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
267     errs() << "Number live values: " << liveset.size() << "\n";
268   }
269   result.liveset = liveset;
270 }
271
272 static Value *findBaseDefiningValue(Value *I);
273
274 /// If we can trivially determine that the index specified in the given vector
275 /// is a base pointer, return it.  In cases where the entire vector is known to
276 /// consist of base pointers, the entire vector will be returned.  This
277 /// indicates that the relevant extractelement is a valid base pointer and
278 /// should be used directly.
279 static Value *findBaseOfVector(Value *I, Value *Index) {
280   assert(I->getType()->isVectorTy() &&
281          cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
282          "Illegal to ask for the base pointer of a non-pointer type");
283
284   // Each case parallels findBaseDefiningValue below, see that code for
285   // detailed motivation.
286
287   if (isa<Argument>(I))
288     // An incoming argument to the function is a base pointer
289     return I;
290
291   // We shouldn't see the address of a global as a vector value?
292   assert(!isa<GlobalVariable>(I) &&
293          "unexpected global variable found in base of vector");
294
295   // inlining could possibly introduce phi node that contains
296   // undef if callee has multiple returns
297   if (isa<UndefValue>(I))
298     // utterly meaningless, but useful for dealing with partially optimized
299     // code.
300     return I;
301
302   // Due to inheritance, this must be _after_ the global variable and undef
303   // checks
304   if (Constant *Con = dyn_cast<Constant>(I)) {
305     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
306            "order of checks wrong!");
307     assert(Con->isNullValue() && "null is the only case which makes sense");
308     return Con;
309   }
310
311   if (isa<LoadInst>(I))
312     return I;
313
314   // For an insert element, we might be able to look through it if we know
315   // something about the indexes, but if the indices are arbitrary values, we
316   // can't without much more extensive scalarization.
317   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
318     Value *InsertIndex = IEI->getOperand(2);
319     // This index is inserting the value, look for it's base
320     if (InsertIndex == Index)
321       return findBaseDefiningValue(IEI->getOperand(1));
322     // Both constant, and can't be equal per above. This insert is definitely
323     // not relevant, look back at the rest of the vector and keep trying.
324     if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
325       return findBaseOfVector(IEI->getOperand(0), Index);
326   }
327
328   // Note: This code is currently rather incomplete.  We are essentially only
329   // handling cases where the vector element is trivially a base pointer.  We
330   // need to update the entire base pointer construction algorithm to know how
331   // to track vector elements and potentially scalarize, but the case which
332   // would motivate the work hasn't shown up in real workloads yet.
333   llvm_unreachable("no base found for vector element");
334 }
335
336 /// Helper function for findBasePointer - Will return a value which either a)
337 /// defines the base pointer for the input or b) blocks the simple search
338 /// (i.e. a PHI or Select of two derived pointers)
339 static Value *findBaseDefiningValue(Value *I) {
340   assert(I->getType()->isPointerTy() &&
341          "Illegal to ask for the base pointer of a non-pointer type");
342
343   // This case is a bit of a hack - it only handles extracts from vectors which
344   // trivially contain only base pointers or cases where we can directly match
345   // the index of the original extract element to an insertion into the vector.
346   // See note inside the function for how to improve this.
347   if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
348     Value *VectorOperand = EEI->getVectorOperand();
349     Value *Index = EEI->getIndexOperand();
350     Value *VectorBase = findBaseOfVector(VectorOperand, Index);
351     // If the result returned is a vector, we know the entire vector must
352     // contain base pointers.  In that case, the extractelement is a valid base
353     // for this value.
354     if (VectorBase->getType()->isVectorTy())
355       return EEI;
356     // Otherwise, we needed to look through the vector to find the base for
357     // this particular element.
358     assert(VectorBase->getType()->isPointerTy());
359     return VectorBase;
360   }
361
362   if (isa<Argument>(I))
363     // An incoming argument to the function is a base pointer
364     // We should have never reached here if this argument isn't an gc value
365     return I;
366
367   if (isa<GlobalVariable>(I))
368     // base case
369     return I;
370
371   // inlining could possibly introduce phi node that contains
372   // undef if callee has multiple returns
373   if (isa<UndefValue>(I))
374     // utterly meaningless, but useful for dealing with
375     // partially optimized code.
376     return I;
377
378   // Due to inheritance, this must be _after_ the global variable and undef
379   // checks
380   if (Constant *Con = dyn_cast<Constant>(I)) {
381     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
382            "order of checks wrong!");
383     // Note: Finding a constant base for something marked for relocation
384     // doesn't really make sense.  The most likely case is either a) some
385     // screwed up the address space usage or b) your validating against
386     // compiled C++ code w/o the proper separation.  The only real exception
387     // is a null pointer.  You could have generic code written to index of
388     // off a potentially null value and have proven it null.  We also use
389     // null pointers in dead paths of relocation phis (which we might later
390     // want to find a base pointer for).
391     assert(isa<ConstantPointerNull>(Con) &&
392            "null is the only case which makes sense");
393     return Con;
394   }
395
396   if (CastInst *CI = dyn_cast<CastInst>(I)) {
397     Value *Def = CI->stripPointerCasts();
398     // If we find a cast instruction here, it means we've found a cast which is
399     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
400     // handle int->ptr conversion.
401     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
402     return findBaseDefiningValue(Def);
403   }
404
405   if (isa<LoadInst>(I))
406     return I; // The value loaded is an gc base itself
407
408   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
409     // The base of this GEP is the base
410     return findBaseDefiningValue(GEP->getPointerOperand());
411
412   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
413     switch (II->getIntrinsicID()) {
414     case Intrinsic::experimental_gc_result_ptr:
415     default:
416       // fall through to general call handling
417       break;
418     case Intrinsic::experimental_gc_statepoint:
419     case Intrinsic::experimental_gc_result_float:
420     case Intrinsic::experimental_gc_result_int:
421       llvm_unreachable("these don't produce pointers");
422     case Intrinsic::experimental_gc_relocate: {
423       // Rerunning safepoint insertion after safepoints are already
424       // inserted is not supported.  It could probably be made to work,
425       // but why are you doing this?  There's no good reason.
426       llvm_unreachable("repeat safepoint insertion is not supported");
427     }
428     case Intrinsic::gcroot:
429       // Currently, this mechanism hasn't been extended to work with gcroot.
430       // There's no reason it couldn't be, but I haven't thought about the
431       // implications much.
432       llvm_unreachable(
433           "interaction with the gcroot mechanism is not supported");
434     }
435   }
436   // We assume that functions in the source language only return base
437   // pointers.  This should probably be generalized via attributes to support
438   // both source language and internal functions.
439   if (isa<CallInst>(I) || isa<InvokeInst>(I))
440     return I;
441
442   // I have absolutely no idea how to implement this part yet.  It's not
443   // neccessarily hard, I just haven't really looked at it yet.
444   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
445
446   if (isa<AtomicCmpXchgInst>(I))
447     // A CAS is effectively a atomic store and load combined under a
448     // predicate.  From the perspective of base pointers, we just treat it
449     // like a load.
450     return I;
451
452   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
453                                    "binary ops which don't apply to pointers");
454
455   // The aggregate ops.  Aggregates can either be in the heap or on the
456   // stack, but in either case, this is simply a field load.  As a result,
457   // this is a defining definition of the base just like a load is.
458   if (isa<ExtractValueInst>(I))
459     return I;
460
461   // We should never see an insert vector since that would require we be
462   // tracing back a struct value not a pointer value.
463   assert(!isa<InsertValueInst>(I) &&
464          "Base pointer for a struct is meaningless");
465
466   // The last two cases here don't return a base pointer.  Instead, they
467   // return a value which dynamically selects from amoung several base
468   // derived pointers (each with it's own base potentially).  It's the job of
469   // the caller to resolve these.
470   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
471          "missing instruction case in findBaseDefiningValing");
472   return I;
473 }
474
475 /// Returns the base defining value for this value.
476 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
477   Value *&Cached = Cache[I];
478   if (!Cached) {
479     Cached = findBaseDefiningValue(I);
480   }
481   assert(Cache[I] != nullptr);
482
483   if (TraceLSP) {
484     dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
485            << "\n";
486   }
487   return Cached;
488 }
489
490 /// Return a base pointer for this value if known.  Otherwise, return it's
491 /// base defining value.
492 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
493   Value *Def = findBaseDefiningValueCached(I, Cache);
494   auto Found = Cache.find(Def);
495   if (Found != Cache.end()) {
496     // Either a base-of relation, or a self reference.  Caller must check.
497     return Found->second;
498   }
499   // Only a BDV available
500   return Def;
501 }
502
503 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
504 /// is it known to be a base pointer?  Or do we need to continue searching.
505 static bool isKnownBaseResult(Value *V) {
506   if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
507     // no recursion possible
508     return true;
509   }
510   if (isa<Instruction>(V) &&
511       cast<Instruction>(V)->getMetadata("is_base_value")) {
512     // This is a previously inserted base phi or select.  We know
513     // that this is a base value.
514     return true;
515   }
516
517   // We need to keep searching
518   return false;
519 }
520
521 // TODO: find a better name for this
522 namespace {
523 class PhiState {
524 public:
525   enum Status { Unknown, Base, Conflict };
526
527   PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
528     assert(status != Base || b);
529   }
530   PhiState(Value *b) : status(Base), base(b) {}
531   PhiState() : status(Unknown), base(nullptr) {}
532
533   Status getStatus() const { return status; }
534   Value *getBase() const { return base; }
535
536   bool isBase() const { return getStatus() == Base; }
537   bool isUnknown() const { return getStatus() == Unknown; }
538   bool isConflict() const { return getStatus() == Conflict; }
539
540   bool operator==(const PhiState &other) const {
541     return base == other.base && status == other.status;
542   }
543
544   bool operator!=(const PhiState &other) const { return !(*this == other); }
545
546   void dump() {
547     errs() << status << " (" << base << " - "
548            << (base ? base->getName() : "nullptr") << "): ";
549   }
550
551 private:
552   Status status;
553   Value *base; // non null only if status == base
554 };
555
556 typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
557 // Values of type PhiState form a lattice, and this is a helper
558 // class that implementes the meet operation.  The meat of the meet
559 // operation is implemented in MeetPhiStates::pureMeet
560 class MeetPhiStates {
561 public:
562   // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
563   explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
564       : phiStates(phiStates) {}
565
566   // Destructively meet the current result with the base V.  V can
567   // either be a merge instruction (SelectInst / PHINode), in which
568   // case its status is looked up in the phiStates map; or a regular
569   // SSA value, in which case it is assumed to be a base.
570   void meetWith(Value *V) {
571     PhiState otherState = getStateForBDV(V);
572     assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
573             MeetPhiStates::pureMeet(currentResult, otherState)) &&
574            "math is wrong: meet does not commute!");
575     currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
576   }
577
578   PhiState getResult() const { return currentResult; }
579
580 private:
581   const ConflictStateMapTy &phiStates;
582   PhiState currentResult;
583
584   /// Return a phi state for a base defining value.  We'll generate a new
585   /// base state for known bases and expect to find a cached state otherwise
586   PhiState getStateForBDV(Value *baseValue) {
587     if (isKnownBaseResult(baseValue)) {
588       return PhiState(baseValue);
589     } else {
590       return lookupFromMap(baseValue);
591     }
592   }
593
594   PhiState lookupFromMap(Value *V) {
595     auto I = phiStates.find(V);
596     assert(I != phiStates.end() && "lookup failed!");
597     return I->second;
598   }
599
600   static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
601     switch (stateA.getStatus()) {
602     case PhiState::Unknown:
603       return stateB;
604
605     case PhiState::Base:
606       assert(stateA.getBase() && "can't be null");
607       if (stateB.isUnknown())
608         return stateA;
609
610       if (stateB.isBase()) {
611         if (stateA.getBase() == stateB.getBase()) {
612           assert(stateA == stateB && "equality broken!");
613           return stateA;
614         }
615         return PhiState(PhiState::Conflict);
616       }
617       assert(stateB.isConflict() && "only three states!");
618       return PhiState(PhiState::Conflict);
619
620     case PhiState::Conflict:
621       return stateA;
622     }
623     llvm_unreachable("only three states!");
624   }
625 };
626 }
627 /// For a given value or instruction, figure out what base ptr it's derived
628 /// from.  For gc objects, this is simply itself.  On success, returns a value
629 /// which is the base pointer.  (This is reliable and can be used for
630 /// relocation.)  On failure, returns nullptr.
631 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
632   Value *def = findBaseOrBDV(I, cache);
633
634   if (isKnownBaseResult(def)) {
635     return def;
636   }
637
638   // Here's the rough algorithm:
639   // - For every SSA value, construct a mapping to either an actual base
640   //   pointer or a PHI which obscures the base pointer.
641   // - Construct a mapping from PHI to unknown TOP state.  Use an
642   //   optimistic algorithm to propagate base pointer information.  Lattice
643   //   looks like:
644   //   UNKNOWN
645   //   b1 b2 b3 b4
646   //   CONFLICT
647   //   When algorithm terminates, all PHIs will either have a single concrete
648   //   base or be in a conflict state.
649   // - For every conflict, insert a dummy PHI node without arguments.  Add
650   //   these to the base[Instruction] = BasePtr mapping.  For every
651   //   non-conflict, add the actual base.
652   //  - For every conflict, add arguments for the base[a] of each input
653   //   arguments.
654   //
655   // Note: A simpler form of this would be to add the conflict form of all
656   // PHIs without running the optimistic algorithm.  This would be
657   // analougous to pessimistic data flow and would likely lead to an
658   // overall worse solution.
659
660   ConflictStateMapTy states;
661   states[def] = PhiState();
662   // Recursively fill in all phis & selects reachable from the initial one
663   // for which we don't already know a definite base value for
664   // TODO: This should be rewritten with a worklist
665   bool done = false;
666   while (!done) {
667     done = true;
668     // Since we're adding elements to 'states' as we run, we can't keep
669     // iterators into the set.
670     SmallVector<Value *, 16> Keys;
671     Keys.reserve(states.size());
672     for (auto Pair : states) {
673       Value *V = Pair.first;
674       Keys.push_back(V);
675     }
676     for (Value *v : Keys) {
677       assert(!isKnownBaseResult(v) && "why did it get added?");
678       if (PHINode *phi = dyn_cast<PHINode>(v)) {
679         assert(phi->getNumIncomingValues() > 0 &&
680                "zero input phis are illegal");
681         for (Value *InVal : phi->incoming_values()) {
682           Value *local = findBaseOrBDV(InVal, cache);
683           if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
684             states[local] = PhiState();
685             done = false;
686           }
687         }
688       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
689         Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
690         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
691           states[local] = PhiState();
692           done = false;
693         }
694         local = findBaseOrBDV(sel->getFalseValue(), cache);
695         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
696           states[local] = PhiState();
697           done = false;
698         }
699       }
700     }
701   }
702
703   if (TraceLSP) {
704     errs() << "States after initialization:\n";
705     for (auto Pair : states) {
706       Instruction *v = cast<Instruction>(Pair.first);
707       PhiState state = Pair.second;
708       state.dump();
709       v->dump();
710     }
711   }
712
713   // TODO: come back and revisit the state transitions around inputs which
714   // have reached conflict state.  The current version seems too conservative.
715
716   bool progress = true;
717   while (progress) {
718 #ifndef NDEBUG
719     size_t oldSize = states.size();
720 #endif
721     progress = false;
722     // We're only changing keys in this loop, thus safe to keep iterators
723     for (auto Pair : states) {
724       MeetPhiStates calculateMeet(states);
725       Value *v = Pair.first;
726       assert(!isKnownBaseResult(v) && "why did it get added?");
727       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
728         calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
729         calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
730       } else
731         for (Value *Val : cast<PHINode>(v)->incoming_values())
732           calculateMeet.meetWith(findBaseOrBDV(Val, cache));
733
734       PhiState oldState = states[v];
735       PhiState newState = calculateMeet.getResult();
736       if (oldState != newState) {
737         progress = true;
738         states[v] = newState;
739       }
740     }
741
742     assert(oldSize <= states.size());
743     assert(oldSize == states.size() || progress);
744   }
745
746   if (TraceLSP) {
747     errs() << "States after meet iteration:\n";
748     for (auto Pair : states) {
749       Instruction *v = cast<Instruction>(Pair.first);
750       PhiState state = Pair.second;
751       state.dump();
752       v->dump();
753     }
754   }
755
756   // Insert Phis for all conflicts
757   // We want to keep naming deterministic in the loop that follows, so
758   // sort the keys before iteration.  This is useful in allowing us to
759   // write stable tests. Note that there is no invalidation issue here.
760   SmallVector<Value *, 16> Keys;
761   Keys.reserve(states.size());
762   for (auto Pair : states) {
763     Value *V = Pair.first;
764     Keys.push_back(V);
765   }
766   std::sort(Keys.begin(), Keys.end(), order_by_name);
767   // TODO: adjust naming patterns to avoid this order of iteration dependency
768   for (Value *V : Keys) {
769     Instruction *v = cast<Instruction>(V);
770     PhiState state = states[V];
771     assert(!isKnownBaseResult(v) && "why did it get added?");
772     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
773     if (!state.isConflict())
774       continue;
775
776     if (isa<PHINode>(v)) {
777       int num_preds =
778           std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
779       assert(num_preds > 0 && "how did we reach here");
780       PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
781       // Add metadata marking this as a base value
782       auto *const_1 = ConstantInt::get(
783           Type::getInt32Ty(
784               v->getParent()->getParent()->getParent()->getContext()),
785           1);
786       auto MDConst = ConstantAsMetadata::get(const_1);
787       MDNode *md = MDNode::get(
788           v->getParent()->getParent()->getParent()->getContext(), MDConst);
789       phi->setMetadata("is_base_value", md);
790       states[v] = PhiState(PhiState::Conflict, phi);
791     } else {
792       SelectInst *sel = cast<SelectInst>(v);
793       // The undef will be replaced later
794       UndefValue *undef = UndefValue::get(sel->getType());
795       SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
796                                                undef, "base_select", sel);
797       // Add metadata marking this as a base value
798       auto *const_1 = ConstantInt::get(
799           Type::getInt32Ty(
800               v->getParent()->getParent()->getParent()->getContext()),
801           1);
802       auto MDConst = ConstantAsMetadata::get(const_1);
803       MDNode *md = MDNode::get(
804           v->getParent()->getParent()->getParent()->getContext(), MDConst);
805       basesel->setMetadata("is_base_value", md);
806       states[v] = PhiState(PhiState::Conflict, basesel);
807     }
808   }
809
810   // Fixup all the inputs of the new PHIs
811   for (auto Pair : states) {
812     Instruction *v = cast<Instruction>(Pair.first);
813     PhiState state = Pair.second;
814
815     assert(!isKnownBaseResult(v) && "why did it get added?");
816     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
817     if (!state.isConflict())
818       continue;
819
820     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
821       PHINode *phi = cast<PHINode>(v);
822       unsigned NumPHIValues = phi->getNumIncomingValues();
823       for (unsigned i = 0; i < NumPHIValues; i++) {
824         Value *InVal = phi->getIncomingValue(i);
825         BasicBlock *InBB = phi->getIncomingBlock(i);
826
827         // If we've already seen InBB, add the same incoming value
828         // we added for it earlier.  The IR verifier requires phi
829         // nodes with multiple entries from the same basic block
830         // to have the same incoming value for each of those
831         // entries.  If we don't do this check here and basephi
832         // has a different type than base, we'll end up adding two
833         // bitcasts (and hence two distinct values) as incoming
834         // values for the same basic block.
835
836         int blockIndex = basephi->getBasicBlockIndex(InBB);
837         if (blockIndex != -1) {
838           Value *oldBase = basephi->getIncomingValue(blockIndex);
839           basephi->addIncoming(oldBase, InBB);
840 #ifndef NDEBUG
841           Value *base = findBaseOrBDV(InVal, cache);
842           if (!isKnownBaseResult(base)) {
843             // Either conflict or base.
844             assert(states.count(base));
845             base = states[base].getBase();
846             assert(base != nullptr && "unknown PhiState!");
847           }
848
849           // In essense this assert states: the only way two
850           // values incoming from the same basic block may be
851           // different is by being different bitcasts of the same
852           // value.  A cleanup that remains TODO is changing
853           // findBaseOrBDV to return an llvm::Value of the correct
854           // type (and still remain pure).  This will remove the
855           // need to add bitcasts.
856           assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
857                  "sanity -- findBaseOrBDV should be pure!");
858 #endif
859           continue;
860         }
861
862         // Find either the defining value for the PHI or the normal base for
863         // a non-phi node
864         Value *base = findBaseOrBDV(InVal, cache);
865         if (!isKnownBaseResult(base)) {
866           // Either conflict or base.
867           assert(states.count(base));
868           base = states[base].getBase();
869           assert(base != nullptr && "unknown PhiState!");
870         }
871         assert(base && "can't be null");
872         // Must use original input BB since base may not be Instruction
873         // The cast is needed since base traversal may strip away bitcasts
874         if (base->getType() != basephi->getType()) {
875           base = new BitCastInst(base, basephi->getType(), "cast",
876                                  InBB->getTerminator());
877         }
878         basephi->addIncoming(base, InBB);
879       }
880       assert(basephi->getNumIncomingValues() == NumPHIValues);
881     } else {
882       SelectInst *basesel = cast<SelectInst>(state.getBase());
883       SelectInst *sel = cast<SelectInst>(v);
884       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
885       // something more safe and less hacky.
886       for (int i = 1; i <= 2; i++) {
887         Value *InVal = sel->getOperand(i);
888         // Find either the defining value for the PHI or the normal base for
889         // a non-phi node
890         Value *base = findBaseOrBDV(InVal, cache);
891         if (!isKnownBaseResult(base)) {
892           // Either conflict or base.
893           assert(states.count(base));
894           base = states[base].getBase();
895           assert(base != nullptr && "unknown PhiState!");
896         }
897         assert(base && "can't be null");
898         // Must use original input BB since base may not be Instruction
899         // The cast is needed since base traversal may strip away bitcasts
900         if (base->getType() != basesel->getType()) {
901           base = new BitCastInst(base, basesel->getType(), "cast", basesel);
902         }
903         basesel->setOperand(i, base);
904       }
905     }
906   }
907
908   // Cache all of our results so we can cheaply reuse them
909   // NOTE: This is actually two caches: one of the base defining value
910   // relation and one of the base pointer relation!  FIXME
911   for (auto item : states) {
912     Value *v = item.first;
913     Value *base = item.second.getBase();
914     assert(v && base);
915     assert(!isKnownBaseResult(v) && "why did it get added?");
916
917     if (TraceLSP) {
918       std::string fromstr =
919           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
920                          : "none";
921       errs() << "Updating base value cache"
922              << " for: " << (v->hasName() ? v->getName() : "")
923              << " from: " << fromstr
924              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
925     }
926
927     assert(isKnownBaseResult(base) &&
928            "must be something we 'know' is a base pointer");
929     if (cache.count(v)) {
930       // Once we transition from the BDV relation being store in the cache to
931       // the base relation being stored, it must be stable
932       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
933              "base relation should be stable");
934     }
935     cache[v] = base;
936   }
937   assert(cache.find(def) != cache.end());
938   return cache[def];
939 }
940
941 // For a set of live pointers (base and/or derived), identify the base
942 // pointer of the object which they are derived from.  This routine will
943 // mutate the IR graph as needed to make the 'base' pointer live at the
944 // definition site of 'derived'.  This ensures that any use of 'derived' can
945 // also use 'base'.  This may involve the insertion of a number of
946 // additional PHI nodes.
947 //
948 // preconditions: live is a set of pointer type Values
949 //
950 // side effects: may insert PHI nodes into the existing CFG, will preserve
951 // CFG, will not remove or mutate any existing nodes
952 //
953 // post condition: PointerToBase contains one (derived, base) pair for every
954 // pointer in live.  Note that derived can be equal to base if the original
955 // pointer was a base pointer.
956 static void
957 findBasePointers(const StatepointLiveSetTy &live,
958                  DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
959                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
960   // For the naming of values inserted to be deterministic - which makes for
961   // much cleaner and more stable tests - we need to assign an order to the
962   // live values.  DenseSets do not provide a deterministic order across runs.
963   SmallVector<Value *, 64> Temp;
964   Temp.insert(Temp.end(), live.begin(), live.end());
965   std::sort(Temp.begin(), Temp.end(), order_by_name);
966   for (Value *ptr : Temp) {
967     Value *base = findBasePointer(ptr, DVCache);
968     assert(base && "failed to find base pointer");
969     PointerToBase[ptr] = base;
970     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
971             DT->dominates(cast<Instruction>(base)->getParent(),
972                           cast<Instruction>(ptr)->getParent())) &&
973            "The base we found better dominate the derived pointer");
974
975     // If you see this trip and like to live really dangerously, the code should
976     // be correct, just with idioms the verifier can't handle.  You can try
977     // disabling the verifier at your own substaintial risk.
978     assert(!isa<ConstantPointerNull>(base) &&
979            "the relocation code needs adjustment to handle the relocation of "
980            "a null pointer constant without causing false positives in the "
981            "safepoint ir verifier.");
982   }
983 }
984
985 /// Find the required based pointers (and adjust the live set) for the given
986 /// parse point.
987 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
988                              const CallSite &CS,
989                              PartiallyConstructedSafepointRecord &result) {
990   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
991   findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
992
993   if (PrintBasePointers) {
994     // Note: Need to print these in a stable order since this is checked in
995     // some tests.
996     errs() << "Base Pairs (w/o Relocation):\n";
997     SmallVector<Value *, 64> Temp;
998     Temp.reserve(PointerToBase.size());
999     for (auto Pair : PointerToBase) {
1000       Temp.push_back(Pair.first);
1001     }
1002     std::sort(Temp.begin(), Temp.end(), order_by_name);
1003     for (Value *Ptr : Temp) {
1004       Value *Base = PointerToBase[Ptr];
1005       errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1006              << "\n";
1007     }
1008   }
1009
1010   result.PointerToBase = PointerToBase;
1011 }
1012
1013 /// Given an updated version of the dataflow liveness results, update the
1014 /// liveset and base pointer maps for the call site CS.
1015 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1016                                   const CallSite &CS,
1017                                   PartiallyConstructedSafepointRecord &result);
1018
1019 static void recomputeLiveInValues(
1020     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1021     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1022   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1023   // again.  The old values are still live and will help it stablize quickly.
1024   GCPtrLivenessData RevisedLivenessData;
1025   computeLiveInValues(DT, F, RevisedLivenessData);
1026   for (size_t i = 0; i < records.size(); i++) {
1027     struct PartiallyConstructedSafepointRecord &info = records[i];
1028     const CallSite &CS = toUpdate[i];
1029     recomputeLiveInValues(RevisedLivenessData, CS, info);
1030   }
1031 }
1032
1033 // When inserting gc.relocate calls, we need to ensure there are no uses
1034 // of the original value between the gc.statepoint and the gc.relocate call.
1035 // One case which can arise is a phi node starting one of the successor blocks.
1036 // We also need to be able to insert the gc.relocates only on the path which
1037 // goes through the statepoint.  We might need to split an edge to make this
1038 // possible.
1039 static BasicBlock *
1040 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1041                             DominatorTree &DT) {
1042   BasicBlock *Ret = BB;
1043   if (!BB->getUniquePredecessor()) {
1044     Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, &DT);
1045   }
1046
1047   // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1048   // from it
1049   FoldSingleEntryPHINodes(Ret);
1050   assert(!isa<PHINode>(Ret->begin()));
1051
1052   // At this point, we can safely insert a gc.relocate as the first instruction
1053   // in Ret if needed.
1054   return Ret;
1055 }
1056
1057 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1058   auto itr = std::find(livevec.begin(), livevec.end(), val);
1059   assert(livevec.end() != itr);
1060   size_t index = std::distance(livevec.begin(), itr);
1061   assert(index < livevec.size());
1062   return index;
1063 }
1064
1065 // Create new attribute set containing only attributes which can be transfered
1066 // from original call to the safepoint.
1067 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1068   AttributeSet ret;
1069
1070   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1071     unsigned index = AS.getSlotIndex(Slot);
1072
1073     if (index == AttributeSet::ReturnIndex ||
1074         index == AttributeSet::FunctionIndex) {
1075
1076       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1077            ++it) {
1078         Attribute attr = *it;
1079
1080         // Do not allow certain attributes - just skip them
1081         // Safepoint can not be read only or read none.
1082         if (attr.hasAttribute(Attribute::ReadNone) ||
1083             attr.hasAttribute(Attribute::ReadOnly))
1084           continue;
1085
1086         ret = ret.addAttributes(
1087             AS.getContext(), index,
1088             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1089       }
1090     }
1091
1092     // Just skip parameter attributes for now
1093   }
1094
1095   return ret;
1096 }
1097
1098 /// Helper function to place all gc relocates necessary for the given
1099 /// statepoint.
1100 /// Inputs:
1101 ///   liveVariables - list of variables to be relocated.
1102 ///   liveStart - index of the first live variable.
1103 ///   basePtrs - base pointers.
1104 ///   statepointToken - statepoint instruction to which relocates should be
1105 ///   bound.
1106 ///   Builder - Llvm IR builder to be used to construct new calls.
1107 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1108                               const int LiveStart,
1109                               ArrayRef<llvm::Value *> BasePtrs,
1110                               Instruction *StatepointToken,
1111                               IRBuilder<> Builder) {
1112   SmallVector<Instruction *, 64> NewDefs;
1113   NewDefs.reserve(LiveVariables.size());
1114
1115   Module *M = StatepointToken->getParent()->getParent()->getParent();
1116
1117   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1118     // We generate a (potentially) unique declaration for every pointer type
1119     // combination.  This results is some blow up the function declarations in
1120     // the IR, but removes the need for argument bitcasts which shrinks the IR
1121     // greatly and makes it much more readable.
1122     SmallVector<Type *, 1> Types;                 // one per 'any' type
1123     // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1124     // cases where the actual value's type mangling is not supported by llvm. A
1125     // bitcast is added later to convert gc_relocate to the actual value's type.
1126     Types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1127     Value *GCRelocateDecl = Intrinsic::getDeclaration(
1128         M, Intrinsic::experimental_gc_relocate, Types);
1129
1130     // Generate the gc.relocate call and save the result
1131     Value *BaseIdx =
1132         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1133                          LiveStart + find_index(LiveVariables, BasePtrs[i]));
1134     Value *LiveIdx = ConstantInt::get(
1135         Type::getInt32Ty(M->getContext()),
1136         LiveStart + find_index(LiveVariables, LiveVariables[i]));
1137
1138     // only specify a debug name if we can give a useful one
1139     Value *Reloc = Builder.CreateCall(
1140         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1141         LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1142                                     : "");
1143     // Trick CodeGen into thinking there are lots of free registers at this
1144     // fake call.
1145     cast<CallInst>(Reloc)->setCallingConv(CallingConv::Cold);
1146
1147     NewDefs.push_back(cast<Instruction>(Reloc));
1148   }
1149   assert(NewDefs.size() == LiveVariables.size() &&
1150          "missing or extra redefinition at safepoint");
1151 }
1152
1153 static void
1154 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1155                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1156                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1157                            Pass *P,
1158                            PartiallyConstructedSafepointRecord &result) {
1159   assert(basePtrs.size() == liveVariables.size());
1160   assert(isStatepoint(CS) &&
1161          "This method expects to be rewriting a statepoint");
1162
1163   BasicBlock *BB = CS.getInstruction()->getParent();
1164   assert(BB);
1165   Function *F = BB->getParent();
1166   assert(F && "must be set");
1167   Module *M = F->getParent();
1168   (void)M;
1169   assert(M && "must be set");
1170
1171   // We're not changing the function signature of the statepoint since the gc
1172   // arguments go into the var args section.
1173   Function *gc_statepoint_decl = CS.getCalledFunction();
1174
1175   // Then go ahead and use the builder do actually do the inserts.  We insert
1176   // immediately before the previous instruction under the assumption that all
1177   // arguments will be available here.  We can't insert afterwards since we may
1178   // be replacing a terminator.
1179   Instruction *insertBefore = CS.getInstruction();
1180   IRBuilder<> Builder(insertBefore);
1181   // Copy all of the arguments from the original statepoint - this includes the
1182   // target, call args, and deopt args
1183   SmallVector<llvm::Value *, 64> args;
1184   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1185   // TODO: Clear the 'needs rewrite' flag
1186
1187   // add all the pointers to be relocated (gc arguments)
1188   // Capture the start of the live variable list for use in the gc_relocates
1189   const int live_start = args.size();
1190   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1191
1192   // Create the statepoint given all the arguments
1193   Instruction *token = nullptr;
1194   AttributeSet return_attributes;
1195   if (CS.isCall()) {
1196     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1197     CallInst *call =
1198         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1199     call->setTailCall(toReplace->isTailCall());
1200     call->setCallingConv(toReplace->getCallingConv());
1201
1202     // Currently we will fail on parameter attributes and on certain
1203     // function attributes.
1204     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1205     // In case if we can handle this set of sttributes - set up function attrs
1206     // directly on statepoint and return attrs later for gc_result intrinsic.
1207     call->setAttributes(new_attrs.getFnAttributes());
1208     return_attributes = new_attrs.getRetAttributes();
1209
1210     token = call;
1211
1212     // Put the following gc_result and gc_relocate calls immediately after the
1213     // the old call (which we're about to delete)
1214     BasicBlock::iterator next(toReplace);
1215     assert(BB->end() != next && "not a terminator, must have next");
1216     next++;
1217     Instruction *IP = &*(next);
1218     Builder.SetInsertPoint(IP);
1219     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1220
1221   } else {
1222     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1223
1224     // Insert the new invoke into the old block.  We'll remove the old one in a
1225     // moment at which point this will become the new terminator for the
1226     // original block.
1227     InvokeInst *invoke = InvokeInst::Create(
1228         gc_statepoint_decl, toReplace->getNormalDest(),
1229         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1230     invoke->setCallingConv(toReplace->getCallingConv());
1231
1232     // Currently we will fail on parameter attributes and on certain
1233     // function attributes.
1234     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1235     // In case if we can handle this set of sttributes - set up function attrs
1236     // directly on statepoint and return attrs later for gc_result intrinsic.
1237     invoke->setAttributes(new_attrs.getFnAttributes());
1238     return_attributes = new_attrs.getRetAttributes();
1239
1240     token = invoke;
1241
1242     // Generate gc relocates in exceptional path
1243     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1244     assert(!isa<PHINode>(unwindBlock->begin()) &&
1245            unwindBlock->getUniquePredecessor() &&
1246            "can't safely insert in this block!");
1247
1248     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1249     Builder.SetInsertPoint(IP);
1250     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1251
1252     // Extract second element from landingpad return value. We will attach
1253     // exceptional gc relocates to it.
1254     const unsigned idx = 1;
1255     Instruction *exceptional_token =
1256         cast<Instruction>(Builder.CreateExtractValue(
1257             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1258     result.UnwindToken = exceptional_token;
1259
1260     // Just throw away return value. We will use the one we got for normal
1261     // block.
1262     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1263                             exceptional_token, Builder);
1264
1265     // Generate gc relocates and returns for normal block
1266     BasicBlock *normalDest = toReplace->getNormalDest();
1267     assert(!isa<PHINode>(normalDest->begin()) &&
1268            normalDest->getUniquePredecessor() &&
1269            "can't safely insert in this block!");
1270
1271     IP = &*(normalDest->getFirstInsertionPt());
1272     Builder.SetInsertPoint(IP);
1273
1274     // gc relocates will be generated later as if it were regular call
1275     // statepoint
1276   }
1277   assert(token);
1278
1279   // Take the name of the original value call if it had one.
1280   token->takeName(CS.getInstruction());
1281
1282 // The GCResult is already inserted, we just need to find it
1283 #ifndef NDEBUG
1284   Instruction *toReplace = CS.getInstruction();
1285   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1286          "only valid use before rewrite is gc.result");
1287   assert(!toReplace->hasOneUse() ||
1288          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1289 #endif
1290
1291   // Update the gc.result of the original statepoint (if any) to use the newly
1292   // inserted statepoint.  This is safe to do here since the token can't be
1293   // considered a live reference.
1294   CS.getInstruction()->replaceAllUsesWith(token);
1295
1296   result.StatepointToken = token;
1297
1298   // Second, create a gc.relocate for every live variable
1299   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1300 }
1301
1302 namespace {
1303 struct name_ordering {
1304   Value *base;
1305   Value *derived;
1306   bool operator()(name_ordering const &a, name_ordering const &b) {
1307     return -1 == a.derived->getName().compare(b.derived->getName());
1308   }
1309 };
1310 }
1311 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1312                            SmallVectorImpl<Value *> &livevec) {
1313   assert(basevec.size() == livevec.size());
1314
1315   SmallVector<name_ordering, 64> temp;
1316   for (size_t i = 0; i < basevec.size(); i++) {
1317     name_ordering v;
1318     v.base = basevec[i];
1319     v.derived = livevec[i];
1320     temp.push_back(v);
1321   }
1322   std::sort(temp.begin(), temp.end(), name_ordering());
1323   for (size_t i = 0; i < basevec.size(); i++) {
1324     basevec[i] = temp[i].base;
1325     livevec[i] = temp[i].derived;
1326   }
1327 }
1328
1329 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1330 // which make the relocations happening at this safepoint explicit.
1331 //
1332 // WARNING: Does not do any fixup to adjust users of the original live
1333 // values.  That's the callers responsibility.
1334 static void
1335 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1336                        PartiallyConstructedSafepointRecord &result) {
1337   auto liveset = result.liveset;
1338   auto PointerToBase = result.PointerToBase;
1339
1340   // Convert to vector for efficient cross referencing.
1341   SmallVector<Value *, 64> basevec, livevec;
1342   livevec.reserve(liveset.size());
1343   basevec.reserve(liveset.size());
1344   for (Value *L : liveset) {
1345     livevec.push_back(L);
1346
1347     assert(PointerToBase.find(L) != PointerToBase.end());
1348     Value *base = PointerToBase[L];
1349     basevec.push_back(base);
1350   }
1351   assert(livevec.size() == basevec.size());
1352
1353   // To make the output IR slightly more stable (for use in diffs), ensure a
1354   // fixed order of the values in the safepoint (by sorting the value name).
1355   // The order is otherwise meaningless.
1356   stablize_order(basevec, livevec);
1357
1358   // Do the actual rewriting and delete the old statepoint
1359   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1360   CS.getInstruction()->eraseFromParent();
1361 }
1362
1363 // Helper function for the relocationViaAlloca.
1364 // It receives iterator to the statepoint gc relocates and emits store to the
1365 // assigned
1366 // location (via allocaMap) for the each one of them.
1367 // Add visited values into the visitedLiveValues set we will later use them
1368 // for sanity check.
1369 static void
1370 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1371                        DenseMap<Value *, Value *> &AllocaMap,
1372                        DenseSet<Value *> &VisitedLiveValues) {
1373
1374   for (User *U : GCRelocs) {
1375     if (!isa<IntrinsicInst>(U))
1376       continue;
1377
1378     IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1379
1380     // We only care about relocates
1381     if (RelocatedValue->getIntrinsicID() !=
1382         Intrinsic::experimental_gc_relocate) {
1383       continue;
1384     }
1385
1386     GCRelocateOperands RelocateOperands(RelocatedValue);
1387     Value *OriginalValue =
1388         const_cast<Value *>(RelocateOperands.getDerivedPtr());
1389     assert(AllocaMap.count(OriginalValue));
1390     Value *Alloca = AllocaMap[OriginalValue];
1391
1392     // Emit store into the related alloca
1393     // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1394     // the correct type according to alloca.
1395     assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1396     IRBuilder<> Builder(RelocatedValue->getNextNode());
1397     Value *CastedRelocatedValue =
1398         Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1399         RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1400
1401     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1402     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1403
1404 #ifndef NDEBUG
1405     VisitedLiveValues.insert(OriginalValue);
1406 #endif
1407   }
1408 }
1409
1410 // Helper function for the "relocationViaAlloca". Similar to the
1411 // "insertRelocationStores" but works for rematerialized values.
1412 static void
1413 insertRematerializationStores(
1414   RematerializedValueMapTy RematerializedValues,
1415   DenseMap<Value *, Value *> &AllocaMap,
1416   DenseSet<Value *> &VisitedLiveValues) {
1417
1418   for (auto RematerializedValuePair: RematerializedValues) {
1419     Instruction *RematerializedValue = RematerializedValuePair.first;
1420     Value *OriginalValue = RematerializedValuePair.second;
1421
1422     assert(AllocaMap.count(OriginalValue) &&
1423            "Can not find alloca for rematerialized value");
1424     Value *Alloca = AllocaMap[OriginalValue];
1425
1426     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1427     Store->insertAfter(RematerializedValue);
1428
1429 #ifndef NDEBUG
1430     VisitedLiveValues.insert(OriginalValue);
1431 #endif
1432   }
1433 }
1434
1435 /// do all the relocation update via allocas and mem2reg
1436 static void relocationViaAlloca(
1437     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1438     ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1439 #ifndef NDEBUG
1440   // record initial number of (static) allocas; we'll check we have the same
1441   // number when we get done.
1442   int InitialAllocaNum = 0;
1443   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1444        I++)
1445     if (isa<AllocaInst>(*I))
1446       InitialAllocaNum++;
1447 #endif
1448
1449   // TODO-PERF: change data structures, reserve
1450   DenseMap<Value *, Value *> AllocaMap;
1451   SmallVector<AllocaInst *, 200> PromotableAllocas;
1452   // Used later to chack that we have enough allocas to store all values
1453   std::size_t NumRematerializedValues = 0;
1454   PromotableAllocas.reserve(Live.size());
1455
1456   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1457   // "PromotableAllocas"
1458   auto emitAllocaFor = [&](Value *LiveValue) {
1459     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1460                                         F.getEntryBlock().getFirstNonPHI());
1461     AllocaMap[LiveValue] = Alloca;
1462     PromotableAllocas.push_back(Alloca);
1463   };
1464
1465   // emit alloca for each live gc pointer
1466   for (unsigned i = 0; i < Live.size(); i++) {
1467     emitAllocaFor(Live[i]);
1468   }
1469
1470   // emit allocas for rematerialized values
1471   for (size_t i = 0; i < Records.size(); i++) {
1472     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1473
1474     for (auto RematerializedValuePair : Info.RematerializedValues) {
1475       Value *OriginalValue = RematerializedValuePair.second;
1476       if (AllocaMap.count(OriginalValue) != 0)
1477         continue;
1478
1479       emitAllocaFor(OriginalValue);
1480       ++NumRematerializedValues;
1481     }
1482   }
1483
1484   // The next two loops are part of the same conceptual operation.  We need to
1485   // insert a store to the alloca after the original def and at each
1486   // redefinition.  We need to insert a load before each use.  These are split
1487   // into distinct loops for performance reasons.
1488
1489   // update gc pointer after each statepoint
1490   // either store a relocated value or null (if no relocated value found for
1491   // this gc pointer and it is not a gc_result)
1492   // this must happen before we update the statepoint with load of alloca
1493   // otherwise we lose the link between statepoint and old def
1494   for (size_t i = 0; i < Records.size(); i++) {
1495     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1496     Value *Statepoint = Info.StatepointToken;
1497
1498     // This will be used for consistency check
1499     DenseSet<Value *> VisitedLiveValues;
1500
1501     // Insert stores for normal statepoint gc relocates
1502     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1503
1504     // In case if it was invoke statepoint
1505     // we will insert stores for exceptional path gc relocates.
1506     if (isa<InvokeInst>(Statepoint)) {
1507       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1508                              VisitedLiveValues);
1509     }
1510
1511     // Do similar thing with rematerialized values
1512     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1513                                   VisitedLiveValues);
1514
1515     if (ClobberNonLive) {
1516       // As a debuging aid, pretend that an unrelocated pointer becomes null at
1517       // the gc.statepoint.  This will turn some subtle GC problems into
1518       // slightly easier to debug SEGVs.  Note that on large IR files with
1519       // lots of gc.statepoints this is extremely costly both memory and time
1520       // wise.
1521       SmallVector<AllocaInst *, 64> ToClobber;
1522       for (auto Pair : AllocaMap) {
1523         Value *Def = Pair.first;
1524         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1525
1526         // This value was relocated
1527         if (VisitedLiveValues.count(Def)) {
1528           continue;
1529         }
1530         ToClobber.push_back(Alloca);
1531       }
1532
1533       auto InsertClobbersAt = [&](Instruction *IP) {
1534         for (auto *AI : ToClobber) {
1535           auto AIType = cast<PointerType>(AI->getType());
1536           auto PT = cast<PointerType>(AIType->getElementType());
1537           Constant *CPN = ConstantPointerNull::get(PT);
1538           StoreInst *Store = new StoreInst(CPN, AI);
1539           Store->insertBefore(IP);
1540         }
1541       };
1542
1543       // Insert the clobbering stores.  These may get intermixed with the
1544       // gc.results and gc.relocates, but that's fine.
1545       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1546         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1547         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1548       } else {
1549         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1550         Next++;
1551         InsertClobbersAt(Next);
1552       }
1553     }
1554   }
1555   // update use with load allocas and add store for gc_relocated
1556   for (auto Pair : AllocaMap) {
1557     Value *Def = Pair.first;
1558     Value *Alloca = Pair.second;
1559
1560     // we pre-record the uses of allocas so that we dont have to worry about
1561     // later update
1562     // that change the user information.
1563     SmallVector<Instruction *, 20> Uses;
1564     // PERF: trade a linear scan for repeated reallocation
1565     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1566     for (User *U : Def->users()) {
1567       if (!isa<ConstantExpr>(U)) {
1568         // If the def has a ConstantExpr use, then the def is either a
1569         // ConstantExpr use itself or null.  In either case
1570         // (recursively in the first, directly in the second), the oop
1571         // it is ultimately dependent on is null and this particular
1572         // use does not need to be fixed up.
1573         Uses.push_back(cast<Instruction>(U));
1574       }
1575     }
1576
1577     std::sort(Uses.begin(), Uses.end());
1578     auto Last = std::unique(Uses.begin(), Uses.end());
1579     Uses.erase(Last, Uses.end());
1580
1581     for (Instruction *Use : Uses) {
1582       if (isa<PHINode>(Use)) {
1583         PHINode *Phi = cast<PHINode>(Use);
1584         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1585           if (Def == Phi->getIncomingValue(i)) {
1586             LoadInst *Load = new LoadInst(
1587                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1588             Phi->setIncomingValue(i, Load);
1589           }
1590         }
1591       } else {
1592         LoadInst *Load = new LoadInst(Alloca, "", Use);
1593         Use->replaceUsesOfWith(Def, Load);
1594       }
1595     }
1596
1597     // emit store for the initial gc value
1598     // store must be inserted after load, otherwise store will be in alloca's
1599     // use list and an extra load will be inserted before it
1600     StoreInst *Store = new StoreInst(Def, Alloca);
1601     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1602       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1603         // InvokeInst is a TerminatorInst so the store need to be inserted
1604         // into its normal destination block.
1605         BasicBlock *NormalDest = Invoke->getNormalDest();
1606         Store->insertBefore(NormalDest->getFirstNonPHI());
1607       } else {
1608         assert(!Inst->isTerminator() &&
1609                "The only TerminatorInst that can produce a value is "
1610                "InvokeInst which is handled above.");
1611         Store->insertAfter(Inst);
1612       }
1613     } else {
1614       assert(isa<Argument>(Def));
1615       Store->insertAfter(cast<Instruction>(Alloca));
1616     }
1617   }
1618
1619   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1620          "we must have the same allocas with lives");
1621   if (!PromotableAllocas.empty()) {
1622     // apply mem2reg to promote alloca to SSA
1623     PromoteMemToReg(PromotableAllocas, DT);
1624   }
1625
1626 #ifndef NDEBUG
1627   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1628        I++)
1629     if (isa<AllocaInst>(*I))
1630       InitialAllocaNum--;
1631   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1632 #endif
1633 }
1634
1635 /// Implement a unique function which doesn't require we sort the input
1636 /// vector.  Doing so has the effect of changing the output of a couple of
1637 /// tests in ways which make them less useful in testing fused safepoints.
1638 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1639   DenseSet<T> Seen;
1640   SmallVector<T, 128> TempVec;
1641   TempVec.reserve(Vec.size());
1642   for (auto Element : Vec)
1643     TempVec.push_back(Element);
1644   Vec.clear();
1645   for (auto V : TempVec) {
1646     if (Seen.insert(V).second) {
1647       Vec.push_back(V);
1648     }
1649   }
1650 }
1651
1652 /// Insert holders so that each Value is obviously live through the entire
1653 /// lifetime of the call.
1654 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1655                                  SmallVectorImpl<CallInst *> &Holders) {
1656   if (Values.empty())
1657     // No values to hold live, might as well not insert the empty holder
1658     return;
1659
1660   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1661   // Use a dummy vararg function to actually hold the values live
1662   Function *Func = cast<Function>(M->getOrInsertFunction(
1663       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1664   if (CS.isCall()) {
1665     // For call safepoints insert dummy calls right after safepoint
1666     BasicBlock::iterator Next(CS.getInstruction());
1667     Next++;
1668     Holders.push_back(CallInst::Create(Func, Values, "", Next));
1669     return;
1670   }
1671   // For invoke safepooints insert dummy calls both in normal and
1672   // exceptional destination blocks
1673   auto *II = cast<InvokeInst>(CS.getInstruction());
1674   Holders.push_back(CallInst::Create(
1675       Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1676   Holders.push_back(CallInst::Create(
1677       Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1678 }
1679
1680 static void findLiveReferences(
1681     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1682     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1683   GCPtrLivenessData OriginalLivenessData;
1684   computeLiveInValues(DT, F, OriginalLivenessData);
1685   for (size_t i = 0; i < records.size(); i++) {
1686     struct PartiallyConstructedSafepointRecord &info = records[i];
1687     const CallSite &CS = toUpdate[i];
1688     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1689   }
1690 }
1691
1692 /// Remove any vector of pointers from the liveset by scalarizing them over the
1693 /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1694 /// would be preferrable to include the vector in the statepoint itself, but
1695 /// the lowering code currently does not handle that.  Extending it would be
1696 /// slightly non-trivial since it requires a format change.  Given how rare
1697 /// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1698 static void splitVectorValues(Instruction *StatepointInst,
1699                               StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
1700   SmallVector<Value *, 16> ToSplit;
1701   for (Value *V : LiveSet)
1702     if (isa<VectorType>(V->getType()))
1703       ToSplit.push_back(V);
1704
1705   if (ToSplit.empty())
1706     return;
1707
1708   Function &F = *(StatepointInst->getParent()->getParent());
1709
1710   DenseMap<Value *, AllocaInst *> AllocaMap;
1711   // First is normal return, second is exceptional return (invoke only)
1712   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1713   for (Value *V : ToSplit) {
1714     LiveSet.erase(V);
1715
1716     AllocaInst *Alloca =
1717         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1718     AllocaMap[V] = Alloca;
1719
1720     VectorType *VT = cast<VectorType>(V->getType());
1721     IRBuilder<> Builder(StatepointInst);
1722     SmallVector<Value *, 16> Elements;
1723     for (unsigned i = 0; i < VT->getNumElements(); i++)
1724       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1725     LiveSet.insert(Elements.begin(), Elements.end());
1726
1727     auto InsertVectorReform = [&](Instruction *IP) {
1728       Builder.SetInsertPoint(IP);
1729       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1730       Value *ResultVec = UndefValue::get(VT);
1731       for (unsigned i = 0; i < VT->getNumElements(); i++)
1732         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1733                                                 Builder.getInt32(i));
1734       return ResultVec;
1735     };
1736
1737     if (isa<CallInst>(StatepointInst)) {
1738       BasicBlock::iterator Next(StatepointInst);
1739       Next++;
1740       Instruction *IP = &*(Next);
1741       Replacements[V].first = InsertVectorReform(IP);
1742       Replacements[V].second = nullptr;
1743     } else {
1744       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1745       // We've already normalized - check that we don't have shared destination
1746       // blocks
1747       BasicBlock *NormalDest = Invoke->getNormalDest();
1748       assert(!isa<PHINode>(NormalDest->begin()));
1749       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1750       assert(!isa<PHINode>(UnwindDest->begin()));
1751       // Insert insert element sequences in both successors
1752       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1753       Replacements[V].first = InsertVectorReform(IP);
1754       IP = &*(UnwindDest->getFirstInsertionPt());
1755       Replacements[V].second = InsertVectorReform(IP);
1756     }
1757   }
1758   for (Value *V : ToSplit) {
1759     AllocaInst *Alloca = AllocaMap[V];
1760
1761     // Capture all users before we start mutating use lists
1762     SmallVector<Instruction *, 16> Users;
1763     for (User *U : V->users())
1764       Users.push_back(cast<Instruction>(U));
1765
1766     for (Instruction *I : Users) {
1767       if (auto Phi = dyn_cast<PHINode>(I)) {
1768         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1769           if (V == Phi->getIncomingValue(i)) {
1770             LoadInst *Load = new LoadInst(
1771                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1772             Phi->setIncomingValue(i, Load);
1773           }
1774       } else {
1775         LoadInst *Load = new LoadInst(Alloca, "", I);
1776         I->replaceUsesOfWith(V, Load);
1777       }
1778     }
1779
1780     // Store the original value and the replacement value into the alloca
1781     StoreInst *Store = new StoreInst(V, Alloca);
1782     if (auto I = dyn_cast<Instruction>(V))
1783       Store->insertAfter(I);
1784     else
1785       Store->insertAfter(Alloca);
1786
1787     // Normal return for invoke, or call return
1788     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1789     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1790     // Unwind return for invoke only
1791     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1792     if (Replacement)
1793       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1794   }
1795
1796   // apply mem2reg to promote alloca to SSA
1797   SmallVector<AllocaInst *, 16> Allocas;
1798   for (Value *V : ToSplit)
1799     Allocas.push_back(AllocaMap[V]);
1800   PromoteMemToReg(Allocas, DT);
1801 }
1802
1803 // Helper function for the "rematerializeLiveValues". It walks use chain
1804 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1805 // values are visited (currently it is GEP's and casts). Returns true if it
1806 // sucessfully reached "BaseValue" and false otherwise.
1807 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1808 // recorded.
1809 static bool findRematerializableChainToBasePointer(
1810   SmallVectorImpl<Instruction*> &ChainToBase,
1811   Value *CurrentValue, Value *BaseValue) {
1812
1813   // We have found a base value
1814   if (CurrentValue == BaseValue) {
1815     return true;
1816   }
1817
1818   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1819     ChainToBase.push_back(GEP);
1820     return findRematerializableChainToBasePointer(ChainToBase,
1821                                                   GEP->getPointerOperand(),
1822                                                   BaseValue);
1823   }
1824
1825   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1826     Value *Def = CI->stripPointerCasts();
1827
1828     // This two checks are basically similar. First one is here for the
1829     // consistency with findBasePointers logic.
1830     assert(!isa<CastInst>(Def) && "not a pointer cast found");
1831     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1832       return false;
1833
1834     ChainToBase.push_back(CI);
1835     return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1836   }
1837
1838   // Not supported instruction in the chain
1839   return false;
1840 }
1841
1842 // Helper function for the "rematerializeLiveValues". Compute cost of the use
1843 // chain we are going to rematerialize.
1844 static unsigned
1845 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1846                        TargetTransformInfo &TTI) {
1847   unsigned Cost = 0;
1848
1849   for (Instruction *Instr : Chain) {
1850     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1851       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1852              "non noop cast is found during rematerialization");
1853
1854       Type *SrcTy = CI->getOperand(0)->getType();
1855       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1856
1857     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1858       // Cost of the address calculation
1859       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1860       Cost += TTI.getAddressComputationCost(ValTy);
1861
1862       // And cost of the GEP itself
1863       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1864       //       allowed for the external usage)
1865       if (!GEP->hasAllConstantIndices())
1866         Cost += 2;
1867
1868     } else {
1869       llvm_unreachable("unsupported instruciton type during rematerialization");
1870     }
1871   }
1872
1873   return Cost;
1874 }
1875
1876 // From the statepoint liveset pick values that are cheaper to recompute then to
1877 // relocate. Remove this values from the liveset, rematerialize them after
1878 // statepoint and record them in "Info" structure. Note that similar to
1879 // relocated values we don't do any user adjustments here.
1880 static void rematerializeLiveValues(CallSite CS,
1881                                     PartiallyConstructedSafepointRecord &Info,
1882                                     TargetTransformInfo &TTI) {
1883   const unsigned int ChainLengthThreshold = 10;
1884
1885   // Record values we are going to delete from this statepoint live set.
1886   // We can not di this in following loop due to iterator invalidation.
1887   SmallVector<Value *, 32> LiveValuesToBeDeleted;
1888
1889   for (Value *LiveValue: Info.liveset) {
1890     // For each live pointer find it's defining chain
1891     SmallVector<Instruction *, 3> ChainToBase;
1892     assert(Info.PointerToBase.find(LiveValue) != Info.PointerToBase.end());
1893     bool FoundChain =
1894       findRematerializableChainToBasePointer(ChainToBase,
1895                                              LiveValue,
1896                                              Info.PointerToBase[LiveValue]);
1897     // Nothing to do, or chain is too long
1898     if (!FoundChain ||
1899         ChainToBase.size() == 0 ||
1900         ChainToBase.size() > ChainLengthThreshold)
1901       continue;
1902
1903     // Compute cost of this chain
1904     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1905     // TODO: We can also account for cases when we will be able to remove some
1906     //       of the rematerialized values by later optimization passes. I.e if
1907     //       we rematerialized several intersecting chains. Or if original values
1908     //       don't have any uses besides this statepoint.
1909
1910     // For invokes we need to rematerialize each chain twice - for normal and
1911     // for unwind basic blocks. Model this by multiplying cost by two.
1912     if (CS.isInvoke()) {
1913       Cost *= 2;
1914     }
1915     // If it's too expensive - skip it
1916     if (Cost >= RematerializationThreshold)
1917       continue;
1918
1919     // Remove value from the live set
1920     LiveValuesToBeDeleted.push_back(LiveValue);
1921
1922     // Clone instructions and record them inside "Info" structure
1923
1924     // Walk backwards to visit top-most instructions first
1925     std::reverse(ChainToBase.begin(), ChainToBase.end());
1926
1927     // Utility function which clones all instructions from "ChainToBase"
1928     // and inserts them before "InsertBefore". Returns rematerialized value
1929     // which should be used after statepoint.
1930     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1931       Instruction *LastClonedValue = nullptr;
1932       Instruction *LastValue = nullptr;
1933       for (Instruction *Instr: ChainToBase) {
1934         // Only GEP's and casts are suported as we need to be careful to not
1935         // introduce any new uses of pointers not in the liveset.
1936         // Note that it's fine to introduce new uses of pointers which were
1937         // otherwise not used after this statepoint.
1938         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1939
1940         Instruction *ClonedValue = Instr->clone();
1941         ClonedValue->insertBefore(InsertBefore);
1942         ClonedValue->setName(Instr->getName() + ".remat");
1943
1944         // If it is not first instruction in the chain then it uses previously
1945         // cloned value. We should update it to use cloned value.
1946         if (LastClonedValue) {
1947           assert(LastValue);
1948           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1949 #ifndef NDEBUG
1950           // Assert that cloned instruction does not use any instructions from
1951           // this chain other than LastClonedValue
1952           for (auto OpValue : ClonedValue->operand_values()) {
1953             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1954                        ChainToBase.end() &&
1955                    "incorrect use in rematerialization chain");
1956           }
1957 #endif
1958         }
1959
1960         LastClonedValue = ClonedValue;
1961         LastValue = Instr;
1962       }
1963       assert(LastClonedValue);
1964       return LastClonedValue;
1965     };
1966
1967     // Different cases for calls and invokes. For invokes we need to clone
1968     // instructions both on normal and unwind path.
1969     if (CS.isCall()) {
1970       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1971       assert(InsertBefore);
1972       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1973       Info.RematerializedValues[RematerializedValue] = LiveValue;
1974     } else {
1975       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
1976
1977       Instruction *NormalInsertBefore =
1978           Invoke->getNormalDest()->getFirstInsertionPt();
1979       Instruction *UnwindInsertBefore =
1980           Invoke->getUnwindDest()->getFirstInsertionPt();
1981
1982       Instruction *NormalRematerializedValue =
1983           rematerializeChain(NormalInsertBefore);
1984       Instruction *UnwindRematerializedValue =
1985           rematerializeChain(UnwindInsertBefore);
1986
1987       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
1988       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
1989     }
1990   }
1991
1992   // Remove rematerializaed values from the live set
1993   for (auto LiveValue: LiveValuesToBeDeleted) {
1994     Info.liveset.erase(LiveValue);
1995   }
1996 }
1997
1998 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1999                               SmallVectorImpl<CallSite> &toUpdate) {
2000 #ifndef NDEBUG
2001   // sanity check the input
2002   std::set<CallSite> uniqued;
2003   uniqued.insert(toUpdate.begin(), toUpdate.end());
2004   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2005
2006   for (size_t i = 0; i < toUpdate.size(); i++) {
2007     CallSite &CS = toUpdate[i];
2008     assert(CS.getInstruction()->getParent()->getParent() == &F);
2009     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2010   }
2011 #endif
2012
2013   // When inserting gc.relocates for invokes, we need to be able to insert at
2014   // the top of the successor blocks.  See the comment on
2015   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2016   // may restructure the CFG.
2017   for (CallSite CS : toUpdate) {
2018     if (!CS.isInvoke())
2019       continue;
2020     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2021     normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2022                                 DT);
2023     normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2024                                 DT);
2025   }
2026
2027   // A list of dummy calls added to the IR to keep various values obviously
2028   // live in the IR.  We'll remove all of these when done.
2029   SmallVector<CallInst *, 64> holders;
2030
2031   // Insert a dummy call with all of the arguments to the vm_state we'll need
2032   // for the actual safepoint insertion.  This ensures reference arguments in
2033   // the deopt argument list are considered live through the safepoint (and
2034   // thus makes sure they get relocated.)
2035   for (size_t i = 0; i < toUpdate.size(); i++) {
2036     CallSite &CS = toUpdate[i];
2037     Statepoint StatepointCS(CS);
2038
2039     SmallVector<Value *, 64> DeoptValues;
2040     for (Use &U : StatepointCS.vm_state_args()) {
2041       Value *Arg = cast<Value>(&U);
2042       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2043              "support for FCA unimplemented");
2044       if (isHandledGCPointerType(Arg->getType()))
2045         DeoptValues.push_back(Arg);
2046     }
2047     insertUseHolderAfter(CS, DeoptValues, holders);
2048   }
2049
2050   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2051   records.reserve(toUpdate.size());
2052   for (size_t i = 0; i < toUpdate.size(); i++) {
2053     struct PartiallyConstructedSafepointRecord info;
2054     records.push_back(info);
2055   }
2056   assert(records.size() == toUpdate.size());
2057
2058   // A) Identify all gc pointers which are staticly live at the given call
2059   // site.
2060   findLiveReferences(F, DT, P, toUpdate, records);
2061
2062   // Do a limited scalarization of any live at safepoint vector values which
2063   // contain pointers.  This enables this pass to run after vectorization at
2064   // the cost of some possible performance loss.  TODO: it would be nice to
2065   // natively support vectors all the way through the backend so we don't need
2066   // to scalarize here.
2067   for (size_t i = 0; i < records.size(); i++) {
2068     struct PartiallyConstructedSafepointRecord &info = records[i];
2069     Instruction *statepoint = toUpdate[i].getInstruction();
2070     splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
2071   }
2072
2073   // B) Find the base pointers for each live pointer
2074   /* scope for caching */ {
2075     // Cache the 'defining value' relation used in the computation and
2076     // insertion of base phis and selects.  This ensures that we don't insert
2077     // large numbers of duplicate base_phis.
2078     DefiningValueMapTy DVCache;
2079
2080     for (size_t i = 0; i < records.size(); i++) {
2081       struct PartiallyConstructedSafepointRecord &info = records[i];
2082       CallSite &CS = toUpdate[i];
2083       findBasePointers(DT, DVCache, CS, info);
2084     }
2085   } // end of cache scope
2086
2087   // The base phi insertion logic (for any safepoint) may have inserted new
2088   // instructions which are now live at some safepoint.  The simplest such
2089   // example is:
2090   // loop:
2091   //   phi a  <-- will be a new base_phi here
2092   //   safepoint 1 <-- that needs to be live here
2093   //   gep a + 1
2094   //   safepoint 2
2095   //   br loop
2096   // We insert some dummy calls after each safepoint to definitely hold live
2097   // the base pointers which were identified for that safepoint.  We'll then
2098   // ask liveness for _every_ base inserted to see what is now live.  Then we
2099   // remove the dummy calls.
2100   holders.reserve(holders.size() + records.size());
2101   for (size_t i = 0; i < records.size(); i++) {
2102     struct PartiallyConstructedSafepointRecord &info = records[i];
2103     CallSite &CS = toUpdate[i];
2104
2105     SmallVector<Value *, 128> Bases;
2106     for (auto Pair : info.PointerToBase) {
2107       Bases.push_back(Pair.second);
2108     }
2109     insertUseHolderAfter(CS, Bases, holders);
2110   }
2111
2112   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2113   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2114   // not the key issue.
2115   recomputeLiveInValues(F, DT, P, toUpdate, records);
2116
2117   if (PrintBasePointers) {
2118     for (size_t i = 0; i < records.size(); i++) {
2119       struct PartiallyConstructedSafepointRecord &info = records[i];
2120       errs() << "Base Pairs: (w/Relocation)\n";
2121       for (auto Pair : info.PointerToBase) {
2122         errs() << " derived %" << Pair.first->getName() << " base %"
2123                << Pair.second->getName() << "\n";
2124       }
2125     }
2126   }
2127   for (size_t i = 0; i < holders.size(); i++) {
2128     holders[i]->eraseFromParent();
2129     holders[i] = nullptr;
2130   }
2131   holders.clear();
2132
2133   // In order to reduce live set of statepoint we might choose to rematerialize
2134   // some values instead of relocating them. This is purelly an optimization and
2135   // does not influence correctness.
2136   TargetTransformInfo &TTI =
2137     P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2138
2139   for (size_t i = 0; i < records.size(); i++) {
2140     struct PartiallyConstructedSafepointRecord &info = records[i];
2141     CallSite &CS = toUpdate[i];
2142
2143     rematerializeLiveValues(CS, info, TTI);
2144   }
2145
2146   // Now run through and replace the existing statepoints with new ones with
2147   // the live variables listed.  We do not yet update uses of the values being
2148   // relocated. We have references to live variables that need to
2149   // survive to the last iteration of this loop.  (By construction, the
2150   // previous statepoint can not be a live variable, thus we can and remove
2151   // the old statepoint calls as we go.)
2152   for (size_t i = 0; i < records.size(); i++) {
2153     struct PartiallyConstructedSafepointRecord &info = records[i];
2154     CallSite &CS = toUpdate[i];
2155     makeStatepointExplicit(DT, CS, P, info);
2156   }
2157   toUpdate.clear(); // prevent accident use of invalid CallSites
2158
2159   // Do all the fixups of the original live variables to their relocated selves
2160   SmallVector<Value *, 128> live;
2161   for (size_t i = 0; i < records.size(); i++) {
2162     struct PartiallyConstructedSafepointRecord &info = records[i];
2163     // We can't simply save the live set from the original insertion.  One of
2164     // the live values might be the result of a call which needs a safepoint.
2165     // That Value* no longer exists and we need to use the new gc_result.
2166     // Thankfully, the liveset is embedded in the statepoint (and updated), so
2167     // we just grab that.
2168     Statepoint statepoint(info.StatepointToken);
2169     live.insert(live.end(), statepoint.gc_args_begin(),
2170                 statepoint.gc_args_end());
2171 #ifndef NDEBUG
2172     // Do some basic sanity checks on our liveness results before performing
2173     // relocation.  Relocation can and will turn mistakes in liveness results
2174     // into non-sensical code which is must harder to debug.
2175     // TODO: It would be nice to test consistency as well
2176     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2177            "statepoint must be reachable or liveness is meaningless");
2178     for (Value *V : statepoint.gc_args()) {
2179       if (!isa<Instruction>(V))
2180         // Non-instruction values trivial dominate all possible uses
2181         continue;
2182       auto LiveInst = cast<Instruction>(V);
2183       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2184              "unreachable values should never be live");
2185       assert(DT.dominates(LiveInst, info.StatepointToken) &&
2186              "basic SSA liveness expectation violated by liveness analysis");
2187     }
2188 #endif
2189   }
2190   unique_unsorted(live);
2191
2192 #ifndef NDEBUG
2193   // sanity check
2194   for (auto ptr : live) {
2195     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2196   }
2197 #endif
2198
2199   relocationViaAlloca(F, DT, live, records);
2200   return !records.empty();
2201 }
2202
2203 /// Returns true if this function should be rewritten by this pass.  The main
2204 /// point of this function is as an extension point for custom logic.
2205 static bool shouldRewriteStatepointsIn(Function &F) {
2206   // TODO: This should check the GCStrategy
2207   if (F.hasGC()) {
2208     const char *FunctionGCName = F.getGC();
2209     const StringRef StatepointExampleName("statepoint-example");
2210     const StringRef CoreCLRName("coreclr");
2211     return (StatepointExampleName == FunctionGCName) ||
2212            (CoreCLRName == FunctionGCName);
2213   } else
2214     return false;
2215 }
2216
2217 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2218   // Nothing to do for declarations.
2219   if (F.isDeclaration() || F.empty())
2220     return false;
2221
2222   // Policy choice says not to rewrite - the most common reason is that we're
2223   // compiling code without a GCStrategy.
2224   if (!shouldRewriteStatepointsIn(F))
2225     return false;
2226
2227   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2228
2229   // Gather all the statepoints which need rewritten.  Be careful to only
2230   // consider those in reachable code since we need to ask dominance queries
2231   // when rewriting.  We'll delete the unreachable ones in a moment.
2232   SmallVector<CallSite, 64> ParsePointNeeded;
2233   bool HasUnreachableStatepoint = false;
2234   for (Instruction &I : inst_range(F)) {
2235     // TODO: only the ones with the flag set!
2236     if (isStatepoint(I)) {
2237       if (DT.isReachableFromEntry(I.getParent()))
2238         ParsePointNeeded.push_back(CallSite(&I));
2239       else
2240         HasUnreachableStatepoint = true;
2241     }
2242   }
2243
2244   bool MadeChange = false;
2245
2246   // Delete any unreachable statepoints so that we don't have unrewritten
2247   // statepoints surviving this pass.  This makes testing easier and the
2248   // resulting IR less confusing to human readers.  Rather than be fancy, we
2249   // just reuse a utility function which removes the unreachable blocks.
2250   if (HasUnreachableStatepoint)
2251     MadeChange |= removeUnreachableBlocks(F);
2252
2253   // Return early if no work to do.
2254   if (ParsePointNeeded.empty())
2255     return MadeChange;
2256
2257   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2258   // These are created by LCSSA.  They have the effect of increasing the size
2259   // of liveness sets for no good reason.  It may be harder to do this post
2260   // insertion since relocations and base phis can confuse things.
2261   for (BasicBlock &BB : F)
2262     if (BB.getUniquePredecessor()) {
2263       MadeChange = true;
2264       FoldSingleEntryPHINodes(&BB);
2265     }
2266
2267   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2268   return MadeChange;
2269 }
2270
2271 // liveness computation via standard dataflow
2272 // -------------------------------------------------------------------
2273
2274 // TODO: Consider using bitvectors for liveness, the set of potentially
2275 // interesting values should be small and easy to pre-compute.
2276
2277 /// Compute the live-in set for the location rbegin starting from
2278 /// the live-out set of the basic block
2279 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2280                                 BasicBlock::reverse_iterator rend,
2281                                 DenseSet<Value *> &LiveTmp) {
2282
2283   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2284     Instruction *I = &*ritr;
2285
2286     // KILL/Def - Remove this definition from LiveIn
2287     LiveTmp.erase(I);
2288
2289     // Don't consider *uses* in PHI nodes, we handle their contribution to
2290     // predecessor blocks when we seed the LiveOut sets
2291     if (isa<PHINode>(I))
2292       continue;
2293
2294     // USE - Add to the LiveIn set for this instruction
2295     for (Value *V : I->operands()) {
2296       assert(!isUnhandledGCPointerType(V->getType()) &&
2297              "support for FCA unimplemented");
2298       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2299         // The choice to exclude all things constant here is slightly subtle.
2300         // There are two idependent reasons:
2301         // - We assume that things which are constant (from LLVM's definition)
2302         // do not move at runtime.  For example, the address of a global
2303         // variable is fixed, even though it's contents may not be.
2304         // - Second, we can't disallow arbitrary inttoptr constants even
2305         // if the language frontend does.  Optimization passes are free to
2306         // locally exploit facts without respect to global reachability.  This
2307         // can create sections of code which are dynamically unreachable and
2308         // contain just about anything.  (see constants.ll in tests)
2309         LiveTmp.insert(V);
2310       }
2311     }
2312   }
2313 }
2314
2315 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2316
2317   for (BasicBlock *Succ : successors(BB)) {
2318     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2319     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2320       PHINode *Phi = cast<PHINode>(&*I);
2321       Value *V = Phi->getIncomingValueForBlock(BB);
2322       assert(!isUnhandledGCPointerType(V->getType()) &&
2323              "support for FCA unimplemented");
2324       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2325         LiveTmp.insert(V);
2326       }
2327     }
2328   }
2329 }
2330
2331 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2332   DenseSet<Value *> KillSet;
2333   for (Instruction &I : *BB)
2334     if (isHandledGCPointerType(I.getType()))
2335       KillSet.insert(&I);
2336   return KillSet;
2337 }
2338
2339 #ifndef NDEBUG
2340 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2341 /// sanity check for the liveness computation.
2342 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2343                           TerminatorInst *TI, bool TermOkay = false) {
2344   for (Value *V : Live) {
2345     if (auto *I = dyn_cast<Instruction>(V)) {
2346       // The terminator can be a member of the LiveOut set.  LLVM's definition
2347       // of instruction dominance states that V does not dominate itself.  As
2348       // such, we need to special case this to allow it.
2349       if (TermOkay && TI == I)
2350         continue;
2351       assert(DT.dominates(I, TI) &&
2352              "basic SSA liveness expectation violated by liveness analysis");
2353     }
2354   }
2355 }
2356
2357 /// Check that all the liveness sets used during the computation of liveness
2358 /// obey basic SSA properties.  This is useful for finding cases where we miss
2359 /// a def.
2360 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2361                           BasicBlock &BB) {
2362   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2363   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2364   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2365 }
2366 #endif
2367
2368 static void computeLiveInValues(DominatorTree &DT, Function &F,
2369                                 GCPtrLivenessData &Data) {
2370
2371   SmallSetVector<BasicBlock *, 200> Worklist;
2372   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2373     // We use a SetVector so that we don't have duplicates in the worklist.
2374     Worklist.insert(pred_begin(BB), pred_end(BB));
2375   };
2376   auto NextItem = [&]() {
2377     BasicBlock *BB = Worklist.back();
2378     Worklist.pop_back();
2379     return BB;
2380   };
2381
2382   // Seed the liveness for each individual block
2383   for (BasicBlock &BB : F) {
2384     Data.KillSet[&BB] = computeKillSet(&BB);
2385     Data.LiveSet[&BB].clear();
2386     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2387
2388 #ifndef NDEBUG
2389     for (Value *Kill : Data.KillSet[&BB])
2390       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2391 #endif
2392
2393     Data.LiveOut[&BB] = DenseSet<Value *>();
2394     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2395     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2396     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2397     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2398     if (!Data.LiveIn[&BB].empty())
2399       AddPredsToWorklist(&BB);
2400   }
2401
2402   // Propagate that liveness until stable
2403   while (!Worklist.empty()) {
2404     BasicBlock *BB = NextItem();
2405
2406     // Compute our new liveout set, then exit early if it hasn't changed
2407     // despite the contribution of our successor.
2408     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2409     const auto OldLiveOutSize = LiveOut.size();
2410     for (BasicBlock *Succ : successors(BB)) {
2411       assert(Data.LiveIn.count(Succ));
2412       set_union(LiveOut, Data.LiveIn[Succ]);
2413     }
2414     // assert OutLiveOut is a subset of LiveOut
2415     if (OldLiveOutSize == LiveOut.size()) {
2416       // If the sets are the same size, then we didn't actually add anything
2417       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2418       // hasn't changed.
2419       continue;
2420     }
2421     Data.LiveOut[BB] = LiveOut;
2422
2423     // Apply the effects of this basic block
2424     DenseSet<Value *> LiveTmp = LiveOut;
2425     set_union(LiveTmp, Data.LiveSet[BB]);
2426     set_subtract(LiveTmp, Data.KillSet[BB]);
2427
2428     assert(Data.LiveIn.count(BB));
2429     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2430     // assert: OldLiveIn is a subset of LiveTmp
2431     if (OldLiveIn.size() != LiveTmp.size()) {
2432       Data.LiveIn[BB] = LiveTmp;
2433       AddPredsToWorklist(BB);
2434     }
2435   } // while( !worklist.empty() )
2436
2437 #ifndef NDEBUG
2438   // Sanity check our ouput against SSA properties.  This helps catch any
2439   // missing kills during the above iteration.
2440   for (BasicBlock &BB : F) {
2441     checkBasicSSA(DT, Data, BB);
2442   }
2443 #endif
2444 }
2445
2446 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2447                               StatepointLiveSetTy &Out) {
2448
2449   BasicBlock *BB = Inst->getParent();
2450
2451   // Note: The copy is intentional and required
2452   assert(Data.LiveOut.count(BB));
2453   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2454
2455   // We want to handle the statepoint itself oddly.  It's
2456   // call result is not live (normal), nor are it's arguments
2457   // (unless they're used again later).  This adjustment is
2458   // specifically what we need to relocate
2459   BasicBlock::reverse_iterator rend(Inst);
2460   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2461   LiveOut.erase(Inst);
2462   Out.insert(LiveOut.begin(), LiveOut.end());
2463 }
2464
2465 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2466                                   const CallSite &CS,
2467                                   PartiallyConstructedSafepointRecord &Info) {
2468   Instruction *Inst = CS.getInstruction();
2469   StatepointLiveSetTy Updated;
2470   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2471
2472 #ifndef NDEBUG
2473   DenseSet<Value *> Bases;
2474   for (auto KVPair : Info.PointerToBase) {
2475     Bases.insert(KVPair.second);
2476   }
2477 #endif
2478   // We may have base pointers which are now live that weren't before.  We need
2479   // to update the PointerToBase structure to reflect this.
2480   for (auto V : Updated)
2481     if (!Info.PointerToBase.count(V)) {
2482       assert(Bases.count(V) && "can't find base for unexpected live value");
2483       Info.PointerToBase[V] = V;
2484       continue;
2485     }
2486
2487 #ifndef NDEBUG
2488   for (auto V : Updated) {
2489     assert(Info.PointerToBase.count(V) &&
2490            "must be able to find base for live value");
2491   }
2492 #endif
2493
2494   // Remove any stale base mappings - this can happen since our liveness is
2495   // more precise then the one inherent in the base pointer analysis
2496   DenseSet<Value *> ToErase;
2497   for (auto KVPair : Info.PointerToBase)
2498     if (!Updated.count(KVPair.first))
2499       ToErase.insert(KVPair.first);
2500   for (auto V : ToErase)
2501     Info.PointerToBase.erase(V);
2502
2503 #ifndef NDEBUG
2504   for (auto KVPair : Info.PointerToBase)
2505     assert(Updated.count(KVPair.first) && "record for non-live value");
2506 #endif
2507
2508   Info.liveset = Updated;
2509 }