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