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