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