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