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