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