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