[RewriteStatepointsForGC] Avoid inserting empty holder
[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/ADT/SetOperations.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InstIterator.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Statepoint.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
41
42 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
43
44 using namespace llvm;
45
46 // Print tracing output
47 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
48                               cl::init(false));
49
50 // Print the liveset found at the insert location
51 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52                                   cl::init(false));
53 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54                                       cl::init(false));
55 // Print out the base pointers for debugging
56 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57                                        cl::init(false));
58
59 #ifdef XDEBUG
60 static bool ClobberNonLive = true;
61 #else
62 static bool ClobberNonLive = false;
63 #endif
64 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
65                                                   cl::location(ClobberNonLive),
66                                                   cl::Hidden);
67
68 namespace {
69 struct RewriteStatepointsForGC : public FunctionPass {
70   static char ID; // Pass identification, replacement for typeid
71
72   RewriteStatepointsForGC() : FunctionPass(ID) {
73     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
74   }
75   bool runOnFunction(Function &F) override;
76
77   void getAnalysisUsage(AnalysisUsage &AU) const override {
78     // We add and rewrite a bunch of instructions, but don't really do much
79     // else.  We could in theory preserve a lot more analyses here.
80     AU.addRequired<DominatorTreeWrapperPass>();
81   }
82 };
83 } // namespace
84
85 char RewriteStatepointsForGC::ID = 0;
86
87 FunctionPass *llvm::createRewriteStatepointsForGCPass() {
88   return new RewriteStatepointsForGC();
89 }
90
91 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
92                       "Make relocations explicit at statepoints", false, false)
93 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
94 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
95                     "Make relocations explicit at statepoints", false, false)
96
97 namespace {
98 struct GCPtrLivenessData {
99   /// Values defined in this block.
100   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
101   /// Values used in this block (and thus live); does not included values
102   /// killed within this block.
103   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
104
105   /// Values live into this basic block (i.e. used by any
106   /// instruction in this basic block or ones reachable from here)
107   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
108
109   /// Values live out of this basic block (i.e. live into
110   /// any successor block)
111   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
112 };
113
114 // The type of the internal cache used inside the findBasePointers family
115 // of functions.  From the callers perspective, this is an opaque type and
116 // should not be inspected.
117 //
118 // In the actual implementation this caches two relations:
119 // - The base relation itself (i.e. this pointer is based on that one)
120 // - The base defining value relation (i.e. before base_phi insertion)
121 // Generally, after the execution of a full findBasePointer call, only the
122 // base relation will remain.  Internally, we add a mixture of the two
123 // types, then update all the second type to the first type
124 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
125 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
126
127 struct PartiallyConstructedSafepointRecord {
128   /// The set of values known to be live accross this safepoint
129   StatepointLiveSetTy liveset;
130
131   /// Mapping from live pointers to a base-defining-value
132   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
133
134   /// Any new values which were added to the IR during base pointer analysis
135   /// for this safepoint
136   DenseSet<llvm::Value *> NewInsertedDefs;
137
138   /// The *new* gc.statepoint instruction itself.  This produces the token
139   /// that normal path gc.relocates and the gc.result are tied to.
140   Instruction *StatepointToken;
141
142   /// Instruction to which exceptional gc relocates are attached
143   /// Makes it easier to iterate through them during relocationViaAlloca.
144   Instruction *UnwindToken;
145 };
146 }
147
148 /// Compute the live-in set for every basic block in the function
149 static void computeLiveInValues(DominatorTree &DT, Function &F,
150                                 GCPtrLivenessData &Data);
151
152 /// Given results from the dataflow liveness computation, find the set of live
153 /// Values at a particular instruction.
154 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
155                               StatepointLiveSetTy &out);
156
157 // TODO: Once we can get to the GCStrategy, this becomes
158 // Optional<bool> isGCManagedPointer(const Value *V) const override {
159
160 static bool isGCPointerType(const Type *T) {
161   if (const PointerType *PT = dyn_cast<PointerType>(T))
162     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
163     // GC managed heap.  We know that a pointer into this heap needs to be
164     // updated and that no other pointer does.
165     return (1 == PT->getAddressSpace());
166   return false;
167 }
168
169 // Return true if this type is one which a) is a gc pointer or contains a GC
170 // pointer and b) is of a type this code expects to encounter as a live value.
171 // (The insertion code will assert that a type which matches (a) and not (b)
172 // is not encountered.)
173 static bool isHandledGCPointerType(Type *T) {
174   // We fully support gc pointers
175   if (isGCPointerType(T))
176     return true;
177   // We partially support vectors of gc pointers. The code will assert if it
178   // can't handle something.
179   if (auto VT = dyn_cast<VectorType>(T))
180     if (isGCPointerType(VT->getElementType()))
181       return true;
182   return false;
183 }
184
185 #ifndef NDEBUG
186 /// Returns true if this type contains a gc pointer whether we know how to
187 /// handle that type or not.
188 static bool containsGCPtrType(Type *Ty) {
189   if (isGCPointerType(Ty))
190     return true;
191   if (VectorType *VT = dyn_cast<VectorType>(Ty))
192     return isGCPointerType(VT->getScalarType());
193   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
194     return containsGCPtrType(AT->getElementType());
195   if (StructType *ST = dyn_cast<StructType>(Ty))
196     return std::any_of(
197         ST->subtypes().begin(), ST->subtypes().end(),
198         [](Type *SubType) { return containsGCPtrType(SubType); });
199   return false;
200 }
201
202 // Returns true if this is a type which a) is a gc pointer or contains a GC
203 // pointer and b) is of a type which the code doesn't expect (i.e. first class
204 // aggregates).  Used to trip assertions.
205 static bool isUnhandledGCPointerType(Type *Ty) {
206   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
207 }
208 #endif
209
210 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
211   if (a->hasName() && b->hasName()) {
212     return -1 == a->getName().compare(b->getName());
213   } else if (a->hasName() && !b->hasName()) {
214     return true;
215   } else if (!a->hasName() && b->hasName()) {
216     return false;
217   } else {
218     // Better than nothing, but not stable
219     return a < b;
220   }
221 }
222
223 // Conservatively identifies any definitions which might be live at the
224 // given instruction. The  analysis is performed immediately before the
225 // given instruction. Values defined by that instruction are not considered
226 // live.  Values used by that instruction are considered live.
227 static void analyzeParsePointLiveness(
228     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
229     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
230   Instruction *inst = CS.getInstruction();
231
232   StatepointLiveSetTy liveset;
233   findLiveSetAtInst(inst, OriginalLivenessData, liveset);
234
235   if (PrintLiveSet) {
236     // Note: This output is used by several of the test cases
237     // The order of elemtns in a set is not stable, put them in a vec and sort
238     // by name
239     SmallVector<Value *, 64> temp;
240     temp.insert(temp.end(), liveset.begin(), liveset.end());
241     std::sort(temp.begin(), temp.end(), order_by_name);
242     errs() << "Live Variables:\n";
243     for (Value *V : temp) {
244       errs() << " " << V->getName(); // no newline
245       V->dump();
246     }
247   }
248   if (PrintLiveSetSize) {
249     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
250     errs() << "Number live values: " << liveset.size() << "\n";
251   }
252   result.liveset = liveset;
253 }
254
255 /// If we can trivially determine that this vector contains only base pointers,
256 /// return the base instruction.
257 static Value *findBaseOfVector(Value *I) {
258   assert(I->getType()->isVectorTy() &&
259          cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
260          "Illegal to ask for the base pointer of a non-pointer type");
261
262   // Each case parallels findBaseDefiningValue below, see that code for
263   // detailed motivation.
264
265   if (isa<Argument>(I))
266     // An incoming argument to the function is a base pointer
267     return I;
268
269   // We shouldn't see the address of a global as a vector value?
270   assert(!isa<GlobalVariable>(I) &&
271          "unexpected global variable found in base of vector");
272
273   // inlining could possibly introduce phi node that contains
274   // undef if callee has multiple returns
275   if (isa<UndefValue>(I))
276     // utterly meaningless, but useful for dealing with partially optimized
277     // code.
278     return I;
279
280   // Due to inheritance, this must be _after_ the global variable and undef
281   // checks
282   if (Constant *Con = dyn_cast<Constant>(I)) {
283     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
284            "order of checks wrong!");
285     assert(Con->isNullValue() && "null is the only case which makes sense");
286     return Con;
287   }
288
289   if (isa<LoadInst>(I))
290     return I;
291
292   // Note: This code is currently rather incomplete.  We are essentially only
293   // handling cases where the vector element is trivially a base pointer.  We
294   // need to update the entire base pointer construction algorithm to know how
295   // to track vector elements and potentially scalarize, but the case which
296   // would motivate the work hasn't shown up in real workloads yet.
297   llvm_unreachable("no base found for vector element");
298 }
299
300 /// Helper function for findBasePointer - Will return a value which either a)
301 /// defines the base pointer for the input or b) blocks the simple search
302 /// (i.e. a PHI or Select of two derived pointers)
303 static Value *findBaseDefiningValue(Value *I) {
304   assert(I->getType()->isPointerTy() &&
305          "Illegal to ask for the base pointer of a non-pointer type");
306
307   // This case is a bit of a hack - it only handles extracts from vectors which
308   // trivially contain only base pointers.  See note inside the function for
309   // how to improve this.
310   if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
311     Value *VectorOperand = EEI->getVectorOperand();
312     Value *VectorBase = findBaseOfVector(VectorOperand);
313     (void)VectorBase;
314     assert(VectorBase && "extract element not known to be a trivial base");
315     return EEI;
316   }
317
318   if (isa<Argument>(I))
319     // An incoming argument to the function is a base pointer
320     // We should have never reached here if this argument isn't an gc value
321     return I;
322
323   if (isa<GlobalVariable>(I))
324     // base case
325     return I;
326
327   // inlining could possibly introduce phi node that contains
328   // undef if callee has multiple returns
329   if (isa<UndefValue>(I))
330     // utterly meaningless, but useful for dealing with
331     // partially optimized code.
332     return I;
333
334   // Due to inheritance, this must be _after_ the global variable and undef
335   // checks
336   if (Constant *Con = dyn_cast<Constant>(I)) {
337     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
338            "order of checks wrong!");
339     // Note: Finding a constant base for something marked for relocation
340     // doesn't really make sense.  The most likely case is either a) some
341     // screwed up the address space usage or b) your validating against
342     // compiled C++ code w/o the proper separation.  The only real exception
343     // is a null pointer.  You could have generic code written to index of
344     // off a potentially null value and have proven it null.  We also use
345     // null pointers in dead paths of relocation phis (which we might later
346     // want to find a base pointer for).
347     assert(isa<ConstantPointerNull>(Con) &&
348            "null is the only case which makes sense");
349     return Con;
350   }
351
352   if (CastInst *CI = dyn_cast<CastInst>(I)) {
353     Value *Def = CI->stripPointerCasts();
354     // If we find a cast instruction here, it means we've found a cast which is
355     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
356     // handle int->ptr conversion.
357     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
358     return findBaseDefiningValue(Def);
359   }
360
361   if (isa<LoadInst>(I))
362     return I; // The value loaded is an gc base itself
363
364   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
365     // The base of this GEP is the base
366     return findBaseDefiningValue(GEP->getPointerOperand());
367
368   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
369     switch (II->getIntrinsicID()) {
370     case Intrinsic::experimental_gc_result_ptr:
371     default:
372       // fall through to general call handling
373       break;
374     case Intrinsic::experimental_gc_statepoint:
375     case Intrinsic::experimental_gc_result_float:
376     case Intrinsic::experimental_gc_result_int:
377       llvm_unreachable("these don't produce pointers");
378     case Intrinsic::experimental_gc_relocate: {
379       // Rerunning safepoint insertion after safepoints are already
380       // inserted is not supported.  It could probably be made to work,
381       // but why are you doing this?  There's no good reason.
382       llvm_unreachable("repeat safepoint insertion is not supported");
383     }
384     case Intrinsic::gcroot:
385       // Currently, this mechanism hasn't been extended to work with gcroot.
386       // There's no reason it couldn't be, but I haven't thought about the
387       // implications much.
388       llvm_unreachable(
389           "interaction with the gcroot mechanism is not supported");
390     }
391   }
392   // We assume that functions in the source language only return base
393   // pointers.  This should probably be generalized via attributes to support
394   // both source language and internal functions.
395   if (isa<CallInst>(I) || isa<InvokeInst>(I))
396     return I;
397
398   // I have absolutely no idea how to implement this part yet.  It's not
399   // neccessarily hard, I just haven't really looked at it yet.
400   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
401
402   if (isa<AtomicCmpXchgInst>(I))
403     // A CAS is effectively a atomic store and load combined under a
404     // predicate.  From the perspective of base pointers, we just treat it
405     // like a load.
406     return I;
407
408   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
409                                    "binary ops which don't apply to pointers");
410
411   // The aggregate ops.  Aggregates can either be in the heap or on the
412   // stack, but in either case, this is simply a field load.  As a result,
413   // this is a defining definition of the base just like a load is.
414   if (isa<ExtractValueInst>(I))
415     return I;
416
417   // We should never see an insert vector since that would require we be
418   // tracing back a struct value not a pointer value.
419   assert(!isa<InsertValueInst>(I) &&
420          "Base pointer for a struct is meaningless");
421
422   // The last two cases here don't return a base pointer.  Instead, they
423   // return a value which dynamically selects from amoung several base
424   // derived pointers (each with it's own base potentially).  It's the job of
425   // the caller to resolve these.
426   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
427          "missing instruction case in findBaseDefiningValing");
428   return I;
429 }
430
431 /// Returns the base defining value for this value.
432 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
433   Value *&Cached = Cache[I];
434   if (!Cached) {
435     Cached = findBaseDefiningValue(I);
436   }
437   assert(Cache[I] != nullptr);
438
439   if (TraceLSP) {
440     dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
441            << "\n";
442   }
443   return Cached;
444 }
445
446 /// Return a base pointer for this value if known.  Otherwise, return it's
447 /// base defining value.
448 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
449   Value *Def = findBaseDefiningValueCached(I, Cache);
450   auto Found = Cache.find(Def);
451   if (Found != Cache.end()) {
452     // Either a base-of relation, or a self reference.  Caller must check.
453     return Found->second;
454   }
455   // Only a BDV available
456   return Def;
457 }
458
459 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
460 /// is it known to be a base pointer?  Or do we need to continue searching.
461 static bool isKnownBaseResult(Value *V) {
462   if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
463     // no recursion possible
464     return true;
465   }
466   if (isa<Instruction>(V) &&
467       cast<Instruction>(V)->getMetadata("is_base_value")) {
468     // This is a previously inserted base phi or select.  We know
469     // that this is a base value.
470     return true;
471   }
472
473   // We need to keep searching
474   return false;
475 }
476
477 // TODO: find a better name for this
478 namespace {
479 class PhiState {
480 public:
481   enum Status { Unknown, Base, Conflict };
482
483   PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
484     assert(status != Base || b);
485   }
486   PhiState(Value *b) : status(Base), base(b) {}
487   PhiState() : status(Unknown), base(nullptr) {}
488
489   Status getStatus() const { return status; }
490   Value *getBase() const { return base; }
491
492   bool isBase() const { return getStatus() == Base; }
493   bool isUnknown() const { return getStatus() == Unknown; }
494   bool isConflict() const { return getStatus() == Conflict; }
495
496   bool operator==(const PhiState &other) const {
497     return base == other.base && status == other.status;
498   }
499
500   bool operator!=(const PhiState &other) const { return !(*this == other); }
501
502   void dump() {
503     errs() << status << " (" << base << " - "
504            << (base ? base->getName() : "nullptr") << "): ";
505   }
506
507 private:
508   Status status;
509   Value *base; // non null only if status == base
510 };
511
512 typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
513 // Values of type PhiState form a lattice, and this is a helper
514 // class that implementes the meet operation.  The meat of the meet
515 // operation is implemented in MeetPhiStates::pureMeet
516 class MeetPhiStates {
517 public:
518   // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
519   explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
520       : phiStates(phiStates) {}
521
522   // Destructively meet the current result with the base V.  V can
523   // either be a merge instruction (SelectInst / PHINode), in which
524   // case its status is looked up in the phiStates map; or a regular
525   // SSA value, in which case it is assumed to be a base.
526   void meetWith(Value *V) {
527     PhiState otherState = getStateForBDV(V);
528     assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
529             MeetPhiStates::pureMeet(currentResult, otherState)) &&
530            "math is wrong: meet does not commute!");
531     currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
532   }
533
534   PhiState getResult() const { return currentResult; }
535
536 private:
537   const ConflictStateMapTy &phiStates;
538   PhiState currentResult;
539
540   /// Return a phi state for a base defining value.  We'll generate a new
541   /// base state for known bases and expect to find a cached state otherwise
542   PhiState getStateForBDV(Value *baseValue) {
543     if (isKnownBaseResult(baseValue)) {
544       return PhiState(baseValue);
545     } else {
546       return lookupFromMap(baseValue);
547     }
548   }
549
550   PhiState lookupFromMap(Value *V) {
551     auto I = phiStates.find(V);
552     assert(I != phiStates.end() && "lookup failed!");
553     return I->second;
554   }
555
556   static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
557     switch (stateA.getStatus()) {
558     case PhiState::Unknown:
559       return stateB;
560
561     case PhiState::Base:
562       assert(stateA.getBase() && "can't be null");
563       if (stateB.isUnknown())
564         return stateA;
565
566       if (stateB.isBase()) {
567         if (stateA.getBase() == stateB.getBase()) {
568           assert(stateA == stateB && "equality broken!");
569           return stateA;
570         }
571         return PhiState(PhiState::Conflict);
572       }
573       assert(stateB.isConflict() && "only three states!");
574       return PhiState(PhiState::Conflict);
575
576     case PhiState::Conflict:
577       return stateA;
578     }
579     llvm_unreachable("only three states!");
580   }
581 };
582 }
583 /// For a given value or instruction, figure out what base ptr it's derived
584 /// from.  For gc objects, this is simply itself.  On success, returns a value
585 /// which is the base pointer.  (This is reliable and can be used for
586 /// relocation.)  On failure, returns nullptr.
587 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
588                               DenseSet<llvm::Value *> &NewInsertedDefs) {
589   Value *def = findBaseOrBDV(I, cache);
590
591   if (isKnownBaseResult(def)) {
592     return def;
593   }
594
595   // Here's the rough algorithm:
596   // - For every SSA value, construct a mapping to either an actual base
597   //   pointer or a PHI which obscures the base pointer.
598   // - Construct a mapping from PHI to unknown TOP state.  Use an
599   //   optimistic algorithm to propagate base pointer information.  Lattice
600   //   looks like:
601   //   UNKNOWN
602   //   b1 b2 b3 b4
603   //   CONFLICT
604   //   When algorithm terminates, all PHIs will either have a single concrete
605   //   base or be in a conflict state.
606   // - For every conflict, insert a dummy PHI node without arguments.  Add
607   //   these to the base[Instruction] = BasePtr mapping.  For every
608   //   non-conflict, add the actual base.
609   //  - For every conflict, add arguments for the base[a] of each input
610   //   arguments.
611   //
612   // Note: A simpler form of this would be to add the conflict form of all
613   // PHIs without running the optimistic algorithm.  This would be
614   // analougous to pessimistic data flow and would likely lead to an
615   // overall worse solution.
616
617   ConflictStateMapTy states;
618   states[def] = PhiState();
619   // Recursively fill in all phis & selects reachable from the initial one
620   // for which we don't already know a definite base value for
621   // TODO: This should be rewritten with a worklist
622   bool done = false;
623   while (!done) {
624     done = true;
625     // Since we're adding elements to 'states' as we run, we can't keep
626     // iterators into the set.
627     SmallVector<Value *, 16> Keys;
628     Keys.reserve(states.size());
629     for (auto Pair : states) {
630       Value *V = Pair.first;
631       Keys.push_back(V);
632     }
633     for (Value *v : Keys) {
634       assert(!isKnownBaseResult(v) && "why did it get added?");
635       if (PHINode *phi = dyn_cast<PHINode>(v)) {
636         assert(phi->getNumIncomingValues() > 0 &&
637                "zero input phis are illegal");
638         for (Value *InVal : phi->incoming_values()) {
639           Value *local = findBaseOrBDV(InVal, cache);
640           if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
641             states[local] = PhiState();
642             done = false;
643           }
644         }
645       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
646         Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
647         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
648           states[local] = PhiState();
649           done = false;
650         }
651         local = findBaseOrBDV(sel->getFalseValue(), cache);
652         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
653           states[local] = PhiState();
654           done = false;
655         }
656       }
657     }
658   }
659
660   if (TraceLSP) {
661     errs() << "States after initialization:\n";
662     for (auto Pair : states) {
663       Instruction *v = cast<Instruction>(Pair.first);
664       PhiState state = Pair.second;
665       state.dump();
666       v->dump();
667     }
668   }
669
670   // TODO: come back and revisit the state transitions around inputs which
671   // have reached conflict state.  The current version seems too conservative.
672
673   bool progress = true;
674   while (progress) {
675 #ifndef NDEBUG
676     size_t oldSize = states.size();
677 #endif
678     progress = false;
679     // We're only changing keys in this loop, thus safe to keep iterators
680     for (auto Pair : states) {
681       MeetPhiStates calculateMeet(states);
682       Value *v = Pair.first;
683       assert(!isKnownBaseResult(v) && "why did it get added?");
684       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
685         calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
686         calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
687       } else
688         for (Value *Val : cast<PHINode>(v)->incoming_values())
689           calculateMeet.meetWith(findBaseOrBDV(Val, cache));
690
691       PhiState oldState = states[v];
692       PhiState newState = calculateMeet.getResult();
693       if (oldState != newState) {
694         progress = true;
695         states[v] = newState;
696       }
697     }
698
699     assert(oldSize <= states.size());
700     assert(oldSize == states.size() || progress);
701   }
702
703   if (TraceLSP) {
704     errs() << "States after meet iteration:\n";
705     for (auto Pair : states) {
706       Instruction *v = cast<Instruction>(Pair.first);
707       PhiState state = Pair.second;
708       state.dump();
709       v->dump();
710     }
711   }
712
713   // Insert Phis for all conflicts
714   // We want to keep naming deterministic in the loop that follows, so
715   // sort the keys before iteration.  This is useful in allowing us to
716   // write stable tests. Note that there is no invalidation issue here.
717   SmallVector<Value *, 16> Keys;
718   Keys.reserve(states.size());
719   for (auto Pair : states) {
720     Value *V = Pair.first;
721     Keys.push_back(V);
722   }
723   std::sort(Keys.begin(), Keys.end(), order_by_name);
724   // TODO: adjust naming patterns to avoid this order of iteration dependency
725   for (Value *V : Keys) {
726     Instruction *v = cast<Instruction>(V);
727     PhiState state = states[V];
728     assert(!isKnownBaseResult(v) && "why did it get added?");
729     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
730     if (!state.isConflict())
731       continue;
732
733     if (isa<PHINode>(v)) {
734       int num_preds =
735           std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
736       assert(num_preds > 0 && "how did we reach here");
737       PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
738       NewInsertedDefs.insert(phi);
739       // Add metadata marking this as a base value
740       auto *const_1 = ConstantInt::get(
741           Type::getInt32Ty(
742               v->getParent()->getParent()->getParent()->getContext()),
743           1);
744       auto MDConst = ConstantAsMetadata::get(const_1);
745       MDNode *md = MDNode::get(
746           v->getParent()->getParent()->getParent()->getContext(), MDConst);
747       phi->setMetadata("is_base_value", md);
748       states[v] = PhiState(PhiState::Conflict, phi);
749     } else {
750       SelectInst *sel = cast<SelectInst>(v);
751       // The undef will be replaced later
752       UndefValue *undef = UndefValue::get(sel->getType());
753       SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
754                                                undef, "base_select", sel);
755       NewInsertedDefs.insert(basesel);
756       // Add metadata marking this as a base value
757       auto *const_1 = ConstantInt::get(
758           Type::getInt32Ty(
759               v->getParent()->getParent()->getParent()->getContext()),
760           1);
761       auto MDConst = ConstantAsMetadata::get(const_1);
762       MDNode *md = MDNode::get(
763           v->getParent()->getParent()->getParent()->getContext(), MDConst);
764       basesel->setMetadata("is_base_value", md);
765       states[v] = PhiState(PhiState::Conflict, basesel);
766     }
767   }
768
769   // Fixup all the inputs of the new PHIs
770   for (auto Pair : states) {
771     Instruction *v = cast<Instruction>(Pair.first);
772     PhiState state = Pair.second;
773
774     assert(!isKnownBaseResult(v) && "why did it get added?");
775     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
776     if (!state.isConflict())
777       continue;
778
779     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
780       PHINode *phi = cast<PHINode>(v);
781       unsigned NumPHIValues = phi->getNumIncomingValues();
782       for (unsigned i = 0; i < NumPHIValues; i++) {
783         Value *InVal = phi->getIncomingValue(i);
784         BasicBlock *InBB = phi->getIncomingBlock(i);
785
786         // If we've already seen InBB, add the same incoming value
787         // we added for it earlier.  The IR verifier requires phi
788         // nodes with multiple entries from the same basic block
789         // to have the same incoming value for each of those
790         // entries.  If we don't do this check here and basephi
791         // has a different type than base, we'll end up adding two
792         // bitcasts (and hence two distinct values) as incoming
793         // values for the same basic block.
794
795         int blockIndex = basephi->getBasicBlockIndex(InBB);
796         if (blockIndex != -1) {
797           Value *oldBase = basephi->getIncomingValue(blockIndex);
798           basephi->addIncoming(oldBase, InBB);
799 #ifndef NDEBUG
800           Value *base = findBaseOrBDV(InVal, cache);
801           if (!isKnownBaseResult(base)) {
802             // Either conflict or base.
803             assert(states.count(base));
804             base = states[base].getBase();
805             assert(base != nullptr && "unknown PhiState!");
806             assert(NewInsertedDefs.count(base) &&
807                    "should have already added this in a prev. iteration!");
808           }
809
810           // In essense this assert states: the only way two
811           // values incoming from the same basic block may be
812           // different is by being different bitcasts of the same
813           // value.  A cleanup that remains TODO is changing
814           // findBaseOrBDV to return an llvm::Value of the correct
815           // type (and still remain pure).  This will remove the
816           // need to add bitcasts.
817           assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
818                  "sanity -- findBaseOrBDV should be pure!");
819 #endif
820           continue;
821         }
822
823         // Find either the defining value for the PHI or the normal base for
824         // a non-phi node
825         Value *base = findBaseOrBDV(InVal, cache);
826         if (!isKnownBaseResult(base)) {
827           // Either conflict or base.
828           assert(states.count(base));
829           base = states[base].getBase();
830           assert(base != nullptr && "unknown PhiState!");
831         }
832         assert(base && "can't be null");
833         // Must use original input BB since base may not be Instruction
834         // The cast is needed since base traversal may strip away bitcasts
835         if (base->getType() != basephi->getType()) {
836           base = new BitCastInst(base, basephi->getType(), "cast",
837                                  InBB->getTerminator());
838           NewInsertedDefs.insert(base);
839         }
840         basephi->addIncoming(base, InBB);
841       }
842       assert(basephi->getNumIncomingValues() == NumPHIValues);
843     } else {
844       SelectInst *basesel = cast<SelectInst>(state.getBase());
845       SelectInst *sel = cast<SelectInst>(v);
846       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
847       // something more safe and less hacky.
848       for (int i = 1; i <= 2; i++) {
849         Value *InVal = sel->getOperand(i);
850         // Find either the defining value for the PHI or the normal base for
851         // a non-phi node
852         Value *base = findBaseOrBDV(InVal, cache);
853         if (!isKnownBaseResult(base)) {
854           // Either conflict or base.
855           assert(states.count(base));
856           base = states[base].getBase();
857           assert(base != nullptr && "unknown PhiState!");
858         }
859         assert(base && "can't be null");
860         // Must use original input BB since base may not be Instruction
861         // The cast is needed since base traversal may strip away bitcasts
862         if (base->getType() != basesel->getType()) {
863           base = new BitCastInst(base, basesel->getType(), "cast", basesel);
864           NewInsertedDefs.insert(base);
865         }
866         basesel->setOperand(i, base);
867       }
868     }
869   }
870
871   // Cache all of our results so we can cheaply reuse them
872   // NOTE: This is actually two caches: one of the base defining value
873   // relation and one of the base pointer relation!  FIXME
874   for (auto item : states) {
875     Value *v = item.first;
876     Value *base = item.second.getBase();
877     assert(v && base);
878     assert(!isKnownBaseResult(v) && "why did it get added?");
879
880     if (TraceLSP) {
881       std::string fromstr =
882           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
883                          : "none";
884       errs() << "Updating base value cache"
885              << " for: " << (v->hasName() ? v->getName() : "")
886              << " from: " << fromstr
887              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
888     }
889
890     assert(isKnownBaseResult(base) &&
891            "must be something we 'know' is a base pointer");
892     if (cache.count(v)) {
893       // Once we transition from the BDV relation being store in the cache to
894       // the base relation being stored, it must be stable
895       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
896              "base relation should be stable");
897     }
898     cache[v] = base;
899   }
900   assert(cache.find(def) != cache.end());
901   return cache[def];
902 }
903
904 // For a set of live pointers (base and/or derived), identify the base
905 // pointer of the object which they are derived from.  This routine will
906 // mutate the IR graph as needed to make the 'base' pointer live at the
907 // definition site of 'derived'.  This ensures that any use of 'derived' can
908 // also use 'base'.  This may involve the insertion of a number of
909 // additional PHI nodes.
910 //
911 // preconditions: live is a set of pointer type Values
912 //
913 // side effects: may insert PHI nodes into the existing CFG, will preserve
914 // CFG, will not remove or mutate any existing nodes
915 //
916 // post condition: PointerToBase contains one (derived, base) pair for every
917 // pointer in live.  Note that derived can be equal to base if the original
918 // pointer was a base pointer.
919 static void
920 findBasePointers(const StatepointLiveSetTy &live,
921                  DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
922                  DominatorTree *DT, DefiningValueMapTy &DVCache,
923                  DenseSet<llvm::Value *> &NewInsertedDefs) {
924   // For the naming of values inserted to be deterministic - which makes for
925   // much cleaner and more stable tests - we need to assign an order to the
926   // live values.  DenseSets do not provide a deterministic order across runs.
927   SmallVector<Value *, 64> Temp;
928   Temp.insert(Temp.end(), live.begin(), live.end());
929   std::sort(Temp.begin(), Temp.end(), order_by_name);
930   for (Value *ptr : Temp) {
931     Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
932     assert(base && "failed to find base pointer");
933     PointerToBase[ptr] = base;
934     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
935             DT->dominates(cast<Instruction>(base)->getParent(),
936                           cast<Instruction>(ptr)->getParent())) &&
937            "The base we found better dominate the derived pointer");
938
939     // If you see this trip and like to live really dangerously, the code should
940     // be correct, just with idioms the verifier can't handle.  You can try
941     // disabling the verifier at your own substaintial risk.
942     assert(!isa<ConstantPointerNull>(base) &&
943            "the relocation code needs adjustment to handle the relocation of "
944            "a null pointer constant without causing false positives in the "
945            "safepoint ir verifier.");
946   }
947 }
948
949 /// Find the required based pointers (and adjust the live set) for the given
950 /// parse point.
951 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
952                              const CallSite &CS,
953                              PartiallyConstructedSafepointRecord &result) {
954   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
955   DenseSet<llvm::Value *> NewInsertedDefs;
956   findBasePointers(result.liveset, PointerToBase, &DT, DVCache,
957                    NewInsertedDefs);
958
959   if (PrintBasePointers) {
960     // Note: Need to print these in a stable order since this is checked in
961     // some tests.
962     errs() << "Base Pairs (w/o Relocation):\n";
963     SmallVector<Value *, 64> Temp;
964     Temp.reserve(PointerToBase.size());
965     for (auto Pair : PointerToBase) {
966       Temp.push_back(Pair.first);
967     }
968     std::sort(Temp.begin(), Temp.end(), order_by_name);
969     for (Value *Ptr : Temp) {
970       Value *Base = PointerToBase[Ptr];
971       errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
972              << "\n";
973     }
974   }
975
976   result.PointerToBase = PointerToBase;
977   result.NewInsertedDefs = NewInsertedDefs;
978 }
979
980 /// Given an updated version of the dataflow liveness results, update the
981 /// liveset and base pointer maps for the call site CS.
982 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
983                                   const CallSite &CS,
984                                   PartiallyConstructedSafepointRecord &result);
985
986 static void recomputeLiveInValues(
987     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
988     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
989   // TODO-PERF: reuse the original liveness, then simply run the dataflow
990   // again.  The old values are still live and will help it stablize quickly.
991   GCPtrLivenessData RevisedLivenessData;
992   computeLiveInValues(DT, F, RevisedLivenessData);
993   for (size_t i = 0; i < records.size(); i++) {
994     struct PartiallyConstructedSafepointRecord &info = records[i];
995     const CallSite &CS = toUpdate[i];
996     recomputeLiveInValues(RevisedLivenessData, CS, info);
997   }
998 }
999
1000 // When inserting gc.relocate calls, we need to ensure there are no uses
1001 // of the original value between the gc.statepoint and the gc.relocate call.
1002 // One case which can arise is a phi node starting one of the successor blocks.
1003 // We also need to be able to insert the gc.relocates only on the path which
1004 // goes through the statepoint.  We might need to split an edge to make this
1005 // possible.  
1006 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
1007                                                  BasicBlock *InvokeParent,
1008                                                  Pass *P) {
1009   DominatorTree *DT = nullptr;
1010   if (auto *DTP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
1011     DT = &DTP->getDomTree();
1012
1013   BasicBlock *Ret = BB;
1014   if (!BB->getUniquePredecessor()) {
1015     Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, DT);
1016   }
1017
1018   // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1019   // from it
1020   FoldSingleEntryPHINodes(Ret);
1021   assert(!isa<PHINode>(Ret->begin()));
1022
1023   // At this point, we can safely insert a gc.relocate as the first instruction
1024   // in Ret if needed.
1025   return Ret;
1026 }
1027
1028 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1029   auto itr = std::find(livevec.begin(), livevec.end(), val);
1030   assert(livevec.end() != itr);
1031   size_t index = std::distance(livevec.begin(), itr);
1032   assert(index < livevec.size());
1033   return index;
1034 }
1035
1036 // Create new attribute set containing only attributes which can be transfered
1037 // from original call to the safepoint.
1038 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1039   AttributeSet ret;
1040
1041   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1042     unsigned index = AS.getSlotIndex(Slot);
1043
1044     if (index == AttributeSet::ReturnIndex ||
1045         index == AttributeSet::FunctionIndex) {
1046
1047       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1048            ++it) {
1049         Attribute attr = *it;
1050
1051         // Do not allow certain attributes - just skip them
1052         // Safepoint can not be read only or read none.
1053         if (attr.hasAttribute(Attribute::ReadNone) ||
1054             attr.hasAttribute(Attribute::ReadOnly))
1055           continue;
1056
1057         ret = ret.addAttributes(
1058             AS.getContext(), index,
1059             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1060       }
1061     }
1062
1063     // Just skip parameter attributes for now
1064   }
1065
1066   return ret;
1067 }
1068
1069 /// Helper function to place all gc relocates necessary for the given
1070 /// statepoint.
1071 /// Inputs:
1072 ///   liveVariables - list of variables to be relocated.
1073 ///   liveStart - index of the first live variable.
1074 ///   basePtrs - base pointers.
1075 ///   statepointToken - statepoint instruction to which relocates should be
1076 ///   bound.
1077 ///   Builder - Llvm IR builder to be used to construct new calls.
1078 static void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1079                               const int liveStart,
1080                               ArrayRef<llvm::Value *> basePtrs,
1081                               Instruction *statepointToken,
1082                               IRBuilder<> Builder) {
1083   SmallVector<Instruction *, 64> NewDefs;
1084   NewDefs.reserve(liveVariables.size());
1085
1086   Module *M = statepointToken->getParent()->getParent()->getParent();
1087
1088   for (unsigned i = 0; i < liveVariables.size(); i++) {
1089     // We generate a (potentially) unique declaration for every pointer type
1090     // combination.  This results is some blow up the function declarations in
1091     // the IR, but removes the need for argument bitcasts which shrinks the IR
1092     // greatly and makes it much more readable.
1093     SmallVector<Type *, 1> types;                 // one per 'any' type
1094     types.push_back(liveVariables[i]->getType()); // result type
1095     Value *gc_relocate_decl = Intrinsic::getDeclaration(
1096         M, Intrinsic::experimental_gc_relocate, types);
1097
1098     // Generate the gc.relocate call and save the result
1099     Value *baseIdx =
1100         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1101                          liveStart + find_index(liveVariables, basePtrs[i]));
1102     Value *liveIdx = ConstantInt::get(
1103         Type::getInt32Ty(M->getContext()),
1104         liveStart + find_index(liveVariables, liveVariables[i]));
1105
1106     // only specify a debug name if we can give a useful one
1107     Value *reloc = Builder.CreateCall3(
1108         gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1109         liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1110                                     : "");
1111     // Trick CodeGen into thinking there are lots of free registers at this
1112     // fake call.
1113     cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1114
1115     NewDefs.push_back(cast<Instruction>(reloc));
1116   }
1117   assert(NewDefs.size() == liveVariables.size() &&
1118          "missing or extra redefinition at safepoint");
1119 }
1120
1121 static void
1122 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1123                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1124                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1125                            Pass *P,
1126                            PartiallyConstructedSafepointRecord &result) {
1127   assert(basePtrs.size() == liveVariables.size());
1128   assert(isStatepoint(CS) &&
1129          "This method expects to be rewriting a statepoint");
1130
1131   BasicBlock *BB = CS.getInstruction()->getParent();
1132   assert(BB);
1133   Function *F = BB->getParent();
1134   assert(F && "must be set");
1135   Module *M = F->getParent();
1136   (void)M;
1137   assert(M && "must be set");
1138
1139   // We're not changing the function signature of the statepoint since the gc
1140   // arguments go into the var args section.
1141   Function *gc_statepoint_decl = CS.getCalledFunction();
1142
1143   // Then go ahead and use the builder do actually do the inserts.  We insert
1144   // immediately before the previous instruction under the assumption that all
1145   // arguments will be available here.  We can't insert afterwards since we may
1146   // be replacing a terminator.
1147   Instruction *insertBefore = CS.getInstruction();
1148   IRBuilder<> Builder(insertBefore);
1149   // Copy all of the arguments from the original statepoint - this includes the
1150   // target, call args, and deopt args
1151   SmallVector<llvm::Value *, 64> args;
1152   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1153   // TODO: Clear the 'needs rewrite' flag
1154
1155   // add all the pointers to be relocated (gc arguments)
1156   // Capture the start of the live variable list for use in the gc_relocates
1157   const int live_start = args.size();
1158   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1159
1160   // Create the statepoint given all the arguments
1161   Instruction *token = nullptr;
1162   AttributeSet return_attributes;
1163   if (CS.isCall()) {
1164     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1165     CallInst *call =
1166         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1167     call->setTailCall(toReplace->isTailCall());
1168     call->setCallingConv(toReplace->getCallingConv());
1169
1170     // Currently we will fail on parameter attributes and on certain
1171     // function attributes.
1172     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1173     // In case if we can handle this set of sttributes - set up function attrs
1174     // directly on statepoint and return attrs later for gc_result intrinsic.
1175     call->setAttributes(new_attrs.getFnAttributes());
1176     return_attributes = new_attrs.getRetAttributes();
1177
1178     token = call;
1179
1180     // Put the following gc_result and gc_relocate calls immediately after the
1181     // the old call (which we're about to delete)
1182     BasicBlock::iterator next(toReplace);
1183     assert(BB->end() != next && "not a terminator, must have next");
1184     next++;
1185     Instruction *IP = &*(next);
1186     Builder.SetInsertPoint(IP);
1187     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1188
1189   } else {
1190     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1191
1192     // Insert the new invoke into the old block.  We'll remove the old one in a
1193     // moment at which point this will become the new terminator for the
1194     // original block.
1195     InvokeInst *invoke = InvokeInst::Create(
1196         gc_statepoint_decl, toReplace->getNormalDest(),
1197         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1198     invoke->setCallingConv(toReplace->getCallingConv());
1199
1200     // Currently we will fail on parameter attributes and on certain
1201     // function attributes.
1202     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1203     // In case if we can handle this set of sttributes - set up function attrs
1204     // directly on statepoint and return attrs later for gc_result intrinsic.
1205     invoke->setAttributes(new_attrs.getFnAttributes());
1206     return_attributes = new_attrs.getRetAttributes();
1207
1208     token = invoke;
1209
1210     // Generate gc relocates in exceptional path
1211     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1212     assert(!isa<PHINode>(unwindBlock->begin()) &&
1213            unwindBlock->getUniquePredecessor() &&
1214            "can't safely insert in this block!");
1215
1216     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1217     Builder.SetInsertPoint(IP);
1218     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1219
1220     // Extract second element from landingpad return value. We will attach
1221     // exceptional gc relocates to it.
1222     const unsigned idx = 1;
1223     Instruction *exceptional_token =
1224         cast<Instruction>(Builder.CreateExtractValue(
1225             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1226     result.UnwindToken = exceptional_token;
1227
1228     // Just throw away return value. We will use the one we got for normal
1229     // block.
1230     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1231                             exceptional_token, Builder);
1232
1233     // Generate gc relocates and returns for normal block
1234     BasicBlock *normalDest = toReplace->getNormalDest();
1235     assert(!isa<PHINode>(normalDest->begin()) &&
1236            normalDest->getUniquePredecessor() &&
1237            "can't safely insert in this block!");
1238
1239     IP = &*(normalDest->getFirstInsertionPt());
1240     Builder.SetInsertPoint(IP);
1241
1242     // gc relocates will be generated later as if it were regular call
1243     // statepoint
1244   }
1245   assert(token);
1246
1247   // Take the name of the original value call if it had one.
1248   token->takeName(CS.getInstruction());
1249
1250 // The GCResult is already inserted, we just need to find it
1251 #ifndef NDEBUG
1252   Instruction *toReplace = CS.getInstruction();
1253   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1254          "only valid use before rewrite is gc.result");
1255   assert(!toReplace->hasOneUse() ||
1256          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1257 #endif
1258
1259   // Update the gc.result of the original statepoint (if any) to use the newly
1260   // inserted statepoint.  This is safe to do here since the token can't be
1261   // considered a live reference.
1262   CS.getInstruction()->replaceAllUsesWith(token);
1263
1264   result.StatepointToken = token;
1265
1266   // Second, create a gc.relocate for every live variable
1267   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1268 }
1269
1270 namespace {
1271 struct name_ordering {
1272   Value *base;
1273   Value *derived;
1274   bool operator()(name_ordering const &a, name_ordering const &b) {
1275     return -1 == a.derived->getName().compare(b.derived->getName());
1276   }
1277 };
1278 }
1279 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1280                            SmallVectorImpl<Value *> &livevec) {
1281   assert(basevec.size() == livevec.size());
1282
1283   SmallVector<name_ordering, 64> temp;
1284   for (size_t i = 0; i < basevec.size(); i++) {
1285     name_ordering v;
1286     v.base = basevec[i];
1287     v.derived = livevec[i];
1288     temp.push_back(v);
1289   }
1290   std::sort(temp.begin(), temp.end(), name_ordering());
1291   for (size_t i = 0; i < basevec.size(); i++) {
1292     basevec[i] = temp[i].base;
1293     livevec[i] = temp[i].derived;
1294   }
1295 }
1296
1297 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1298 // which make the relocations happening at this safepoint explicit.
1299 //
1300 // WARNING: Does not do any fixup to adjust users of the original live
1301 // values.  That's the callers responsibility.
1302 static void
1303 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1304                        PartiallyConstructedSafepointRecord &result) {
1305   auto liveset = result.liveset;
1306   auto PointerToBase = result.PointerToBase;
1307
1308   // Convert to vector for efficient cross referencing.
1309   SmallVector<Value *, 64> basevec, livevec;
1310   livevec.reserve(liveset.size());
1311   basevec.reserve(liveset.size());
1312   for (Value *L : liveset) {
1313     livevec.push_back(L);
1314
1315     assert(PointerToBase.find(L) != PointerToBase.end());
1316     Value *base = PointerToBase[L];
1317     basevec.push_back(base);
1318   }
1319   assert(livevec.size() == basevec.size());
1320
1321   // To make the output IR slightly more stable (for use in diffs), ensure a
1322   // fixed order of the values in the safepoint (by sorting the value name).
1323   // The order is otherwise meaningless.
1324   stablize_order(basevec, livevec);
1325
1326   // Do the actual rewriting and delete the old statepoint
1327   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1328   CS.getInstruction()->eraseFromParent();
1329 }
1330
1331 // Helper function for the relocationViaAlloca.
1332 // It receives iterator to the statepoint gc relocates and emits store to the
1333 // assigned
1334 // location (via allocaMap) for the each one of them.
1335 // Add visited values into the visitedLiveValues set we will later use them
1336 // for sanity check.
1337 static void
1338 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1339                        DenseMap<Value *, Value *> &allocaMap,
1340                        DenseSet<Value *> &visitedLiveValues) {
1341
1342   for (User *U : gcRelocs) {
1343     if (!isa<IntrinsicInst>(U))
1344       continue;
1345
1346     IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1347
1348     // We only care about relocates
1349     if (relocatedValue->getIntrinsicID() !=
1350         Intrinsic::experimental_gc_relocate) {
1351       continue;
1352     }
1353
1354     GCRelocateOperands relocateOperands(relocatedValue);
1355     Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1356     assert(allocaMap.count(originalValue));
1357     Value *alloca = allocaMap[originalValue];
1358
1359     // Emit store into the related alloca
1360     StoreInst *store = new StoreInst(relocatedValue, alloca);
1361     store->insertAfter(relocatedValue);
1362
1363 #ifndef NDEBUG
1364     visitedLiveValues.insert(originalValue);
1365 #endif
1366   }
1367 }
1368
1369 /// do all the relocation update via allocas and mem2reg
1370 static void relocationViaAlloca(
1371     Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1372     ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1373 #ifndef NDEBUG
1374   // record initial number of (static) allocas; we'll check we have the same
1375   // number when we get done.
1376   int InitialAllocaNum = 0;
1377   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1378        I++)
1379     if (isa<AllocaInst>(*I))
1380       InitialAllocaNum++;
1381 #endif
1382
1383   // TODO-PERF: change data structures, reserve
1384   DenseMap<Value *, Value *> allocaMap;
1385   SmallVector<AllocaInst *, 200> PromotableAllocas;
1386   PromotableAllocas.reserve(live.size());
1387
1388   // emit alloca for each live gc pointer
1389   for (unsigned i = 0; i < live.size(); i++) {
1390     Value *liveValue = live[i];
1391     AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1392                                         F.getEntryBlock().getFirstNonPHI());
1393     allocaMap[liveValue] = alloca;
1394     PromotableAllocas.push_back(alloca);
1395   }
1396
1397   // The next two loops are part of the same conceptual operation.  We need to
1398   // insert a store to the alloca after the original def and at each
1399   // redefinition.  We need to insert a load before each use.  These are split
1400   // into distinct loops for performance reasons.
1401
1402   // update gc pointer after each statepoint
1403   // either store a relocated value or null (if no relocated value found for
1404   // this gc pointer and it is not a gc_result)
1405   // this must happen before we update the statepoint with load of alloca
1406   // otherwise we lose the link between statepoint and old def
1407   for (size_t i = 0; i < records.size(); i++) {
1408     const struct PartiallyConstructedSafepointRecord &info = records[i];
1409     Value *Statepoint = info.StatepointToken;
1410
1411     // This will be used for consistency check
1412     DenseSet<Value *> visitedLiveValues;
1413
1414     // Insert stores for normal statepoint gc relocates
1415     insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
1416
1417     // In case if it was invoke statepoint
1418     // we will insert stores for exceptional path gc relocates.
1419     if (isa<InvokeInst>(Statepoint)) {
1420       insertRelocationStores(info.UnwindToken->users(), allocaMap,
1421                              visitedLiveValues);
1422     }
1423
1424     if (ClobberNonLive) {
1425       // As a debuging aid, pretend that an unrelocated pointer becomes null at
1426       // the gc.statepoint.  This will turn some subtle GC problems into
1427       // slightly easier to debug SEGVs.  Note that on large IR files with
1428       // lots of gc.statepoints this is extremely costly both memory and time
1429       // wise.
1430       SmallVector<AllocaInst *, 64> ToClobber;
1431       for (auto Pair : allocaMap) {
1432         Value *Def = Pair.first;
1433         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1434
1435         // This value was relocated
1436         if (visitedLiveValues.count(Def)) {
1437           continue;
1438         }
1439         ToClobber.push_back(Alloca);
1440       }
1441
1442       auto InsertClobbersAt = [&](Instruction *IP) {
1443         for (auto *AI : ToClobber) {
1444           auto AIType = cast<PointerType>(AI->getType());
1445           auto PT = cast<PointerType>(AIType->getElementType());
1446           Constant *CPN = ConstantPointerNull::get(PT);
1447           StoreInst *store = new StoreInst(CPN, AI);
1448           store->insertBefore(IP);
1449         }
1450       };
1451
1452       // Insert the clobbering stores.  These may get intermixed with the
1453       // gc.results and gc.relocates, but that's fine.
1454       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1455         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1456         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1457       } else {
1458         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1459         Next++;
1460         InsertClobbersAt(Next);
1461       }
1462     }
1463   }
1464   // update use with load allocas and add store for gc_relocated
1465   for (auto Pair : allocaMap) {
1466     Value *def = Pair.first;
1467     Value *alloca = Pair.second;
1468
1469     // we pre-record the uses of allocas so that we dont have to worry about
1470     // later update
1471     // that change the user information.
1472     SmallVector<Instruction *, 20> uses;
1473     // PERF: trade a linear scan for repeated reallocation
1474     uses.reserve(std::distance(def->user_begin(), def->user_end()));
1475     for (User *U : def->users()) {
1476       if (!isa<ConstantExpr>(U)) {
1477         // If the def has a ConstantExpr use, then the def is either a
1478         // ConstantExpr use itself or null.  In either case
1479         // (recursively in the first, directly in the second), the oop
1480         // it is ultimately dependent on is null and this particular
1481         // use does not need to be fixed up.
1482         uses.push_back(cast<Instruction>(U));
1483       }
1484     }
1485
1486     std::sort(uses.begin(), uses.end());
1487     auto last = std::unique(uses.begin(), uses.end());
1488     uses.erase(last, uses.end());
1489
1490     for (Instruction *use : uses) {
1491       if (isa<PHINode>(use)) {
1492         PHINode *phi = cast<PHINode>(use);
1493         for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1494           if (def == phi->getIncomingValue(i)) {
1495             LoadInst *load = new LoadInst(
1496                 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1497             phi->setIncomingValue(i, load);
1498           }
1499         }
1500       } else {
1501         LoadInst *load = new LoadInst(alloca, "", use);
1502         use->replaceUsesOfWith(def, load);
1503       }
1504     }
1505
1506     // emit store for the initial gc value
1507     // store must be inserted after load, otherwise store will be in alloca's
1508     // use list and an extra load will be inserted before it
1509     StoreInst *store = new StoreInst(def, alloca);
1510     if (Instruction *inst = dyn_cast<Instruction>(def)) {
1511       if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1512         // InvokeInst is a TerminatorInst so the store need to be inserted
1513         // into its normal destination block.
1514         BasicBlock *normalDest = invoke->getNormalDest();
1515         store->insertBefore(normalDest->getFirstNonPHI());
1516       } else {
1517         assert(!inst->isTerminator() &&
1518                "The only TerminatorInst that can produce a value is "
1519                "InvokeInst which is handled above.");
1520         store->insertAfter(inst);
1521       }
1522     } else {
1523       assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1524               isa<ConstantPointerNull>(def)) &&
1525              "Must be argument or global");
1526       store->insertAfter(cast<Instruction>(alloca));
1527     }
1528   }
1529
1530   assert(PromotableAllocas.size() == live.size() &&
1531          "we must have the same allocas with lives");
1532   if (!PromotableAllocas.empty()) {
1533     // apply mem2reg to promote alloca to SSA
1534     PromoteMemToReg(PromotableAllocas, DT);
1535   }
1536
1537 #ifndef NDEBUG
1538   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1539        I++)
1540     if (isa<AllocaInst>(*I))
1541       InitialAllocaNum--;
1542   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1543 #endif
1544 }
1545
1546 /// Implement a unique function which doesn't require we sort the input
1547 /// vector.  Doing so has the effect of changing the output of a couple of
1548 /// tests in ways which make them less useful in testing fused safepoints.
1549 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1550   DenseSet<T> Seen;
1551   SmallVector<T, 128> TempVec;
1552   TempVec.reserve(Vec.size());
1553   for (auto Element : Vec)
1554     TempVec.push_back(Element);
1555   Vec.clear();
1556   for (auto V : TempVec) {
1557     if (Seen.insert(V).second) {
1558       Vec.push_back(V);
1559     }
1560   }
1561 }
1562
1563 static Function *getUseHolder(Module &M) {
1564   FunctionType *ftype =
1565       FunctionType::get(Type::getVoidTy(M.getContext()), true);
1566   Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1567   return Func;
1568 }
1569
1570 /// Insert holders so that each Value is obviously live through the entire
1571 /// liftetime of the call.
1572 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1573                                  SmallVectorImpl<CallInst *> &holders) {
1574   if (Values.empty())
1575     // No values to hold live, might as well not insert the empty holder
1576     return;
1577
1578   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1579   Function *Func = getUseHolder(*M);
1580   if (CS.isCall()) {
1581     // For call safepoints insert dummy calls right after safepoint
1582     BasicBlock::iterator next(CS.getInstruction());
1583     next++;
1584     CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1585     holders.push_back(base_holder);
1586   } else if (CS.isInvoke()) {
1587     // For invoke safepooints insert dummy calls both in normal and
1588     // exceptional destination blocks
1589     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1590     CallInst *normal_holder = CallInst::Create(
1591         Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1592     CallInst *unwind_holder = CallInst::Create(
1593         Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1594     holders.push_back(normal_holder);
1595     holders.push_back(unwind_holder);
1596   } else
1597     llvm_unreachable("unsupported call type");
1598 }
1599
1600 static void findLiveReferences(
1601     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1602     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1603   GCPtrLivenessData OriginalLivenessData;
1604   computeLiveInValues(DT, F, OriginalLivenessData);
1605   for (size_t i = 0; i < records.size(); i++) {
1606     struct PartiallyConstructedSafepointRecord &info = records[i];
1607     const CallSite &CS = toUpdate[i];
1608     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1609   }
1610 }
1611
1612 /// Remove any vector of pointers from the liveset by scalarizing them over the
1613 /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1614 /// would be preferrable to include the vector in the statepoint itself, but
1615 /// the lowering code currently does not handle that.  Extending it would be
1616 /// slightly non-trivial since it requires a format change.  Given how rare
1617 /// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1618 static void splitVectorValues(Instruction *StatepointInst,
1619                               StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
1620   SmallVector<Value *, 16> ToSplit;
1621   for (Value *V : LiveSet)
1622     if (isa<VectorType>(V->getType()))
1623       ToSplit.push_back(V);
1624
1625   if (ToSplit.empty())
1626     return;
1627
1628   Function &F = *(StatepointInst->getParent()->getParent());
1629
1630   DenseMap<Value *, AllocaInst *> AllocaMap;
1631   // First is normal return, second is exceptional return (invoke only)
1632   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1633   for (Value *V : ToSplit) {
1634     LiveSet.erase(V);
1635
1636     AllocaInst *Alloca =
1637         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1638     AllocaMap[V] = Alloca;
1639
1640     VectorType *VT = cast<VectorType>(V->getType());
1641     IRBuilder<> Builder(StatepointInst);
1642     SmallVector<Value *, 16> Elements;
1643     for (unsigned i = 0; i < VT->getNumElements(); i++)
1644       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1645     LiveSet.insert(Elements.begin(), Elements.end());
1646
1647     auto InsertVectorReform = [&](Instruction *IP) {
1648       Builder.SetInsertPoint(IP);
1649       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1650       Value *ResultVec = UndefValue::get(VT);
1651       for (unsigned i = 0; i < VT->getNumElements(); i++)
1652         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1653                                                 Builder.getInt32(i));
1654       return ResultVec;
1655     };
1656
1657     if (isa<CallInst>(StatepointInst)) {
1658       BasicBlock::iterator Next(StatepointInst);
1659       Next++;
1660       Instruction *IP = &*(Next);
1661       Replacements[V].first = InsertVectorReform(IP);
1662       Replacements[V].second = nullptr;
1663     } else {
1664       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1665       // We've already normalized - check that we don't have shared destination
1666       // blocks
1667       BasicBlock *NormalDest = Invoke->getNormalDest();
1668       assert(!isa<PHINode>(NormalDest->begin()));
1669       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1670       assert(!isa<PHINode>(UnwindDest->begin()));
1671       // Insert insert element sequences in both successors
1672       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1673       Replacements[V].first = InsertVectorReform(IP);
1674       IP = &*(UnwindDest->getFirstInsertionPt());
1675       Replacements[V].second = InsertVectorReform(IP);
1676     }
1677   }
1678   for (Value *V : ToSplit) {
1679     AllocaInst *Alloca = AllocaMap[V];
1680
1681     // Capture all users before we start mutating use lists
1682     SmallVector<Instruction *, 16> Users;
1683     for (User *U : V->users())
1684       Users.push_back(cast<Instruction>(U));
1685
1686     for (Instruction *I : Users) {
1687       if (auto Phi = dyn_cast<PHINode>(I)) {
1688         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1689           if (V == Phi->getIncomingValue(i)) {
1690             LoadInst *Load = new LoadInst(
1691                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1692             Phi->setIncomingValue(i, Load);
1693           }
1694       } else {
1695         LoadInst *Load = new LoadInst(Alloca, "", I);
1696         I->replaceUsesOfWith(V, Load);
1697       }
1698     }
1699
1700     // Store the original value and the replacement value into the alloca
1701     StoreInst *Store = new StoreInst(V, Alloca);
1702     if (auto I = dyn_cast<Instruction>(V))
1703       Store->insertAfter(I);
1704     else
1705       Store->insertAfter(Alloca);
1706
1707     // Normal return for invoke, or call return
1708     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1709     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1710     // Unwind return for invoke only
1711     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1712     if (Replacement)
1713       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1714   }
1715
1716   // apply mem2reg to promote alloca to SSA
1717   SmallVector<AllocaInst *, 16> Allocas;
1718   for (Value *V : ToSplit)
1719     Allocas.push_back(AllocaMap[V]);
1720   PromoteMemToReg(Allocas, DT);
1721 }
1722
1723 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1724                               SmallVectorImpl<CallSite> &toUpdate) {
1725 #ifndef NDEBUG
1726   // sanity check the input
1727   std::set<CallSite> uniqued;
1728   uniqued.insert(toUpdate.begin(), toUpdate.end());
1729   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1730
1731   for (size_t i = 0; i < toUpdate.size(); i++) {
1732     CallSite &CS = toUpdate[i];
1733     assert(CS.getInstruction()->getParent()->getParent() == &F);
1734     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1735   }
1736 #endif
1737
1738   // When inserting gc.relocates for invokes, we need to be able to insert at
1739   // the top of the successor blocks.  See the comment on
1740   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
1741   // may restructure the CFG.  
1742   for (CallSite CS : toUpdate)
1743     if (CS.isInvoke()) {
1744       InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1745       normalizeForInvokeSafepoint(invoke->getNormalDest(),
1746                                   invoke->getParent(), P);
1747       normalizeForInvokeSafepoint(invoke->getUnwindDest(),
1748                                   invoke->getParent(), P);
1749     }
1750
1751   // A list of dummy calls added to the IR to keep various values obviously
1752   // live in the IR.  We'll remove all of these when done.
1753   SmallVector<CallInst *, 64> holders;
1754
1755   // Insert a dummy call with all of the arguments to the vm_state we'll need
1756   // for the actual safepoint insertion.  This ensures reference arguments in
1757   // the deopt argument list are considered live through the safepoint (and
1758   // thus makes sure they get relocated.)
1759   for (size_t i = 0; i < toUpdate.size(); i++) {
1760     CallSite &CS = toUpdate[i];
1761     Statepoint StatepointCS(CS);
1762
1763     SmallVector<Value *, 64> DeoptValues;
1764     for (Use &U : StatepointCS.vm_state_args()) {
1765       Value *Arg = cast<Value>(&U);
1766       assert(!isUnhandledGCPointerType(Arg->getType()) &&
1767              "support for FCA unimplemented");
1768       if (isHandledGCPointerType(Arg->getType()))
1769         DeoptValues.push_back(Arg);
1770     }
1771     insertUseHolderAfter(CS, DeoptValues, holders);
1772   }
1773
1774   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
1775   records.reserve(toUpdate.size());
1776   for (size_t i = 0; i < toUpdate.size(); i++) {
1777     struct PartiallyConstructedSafepointRecord info;
1778     records.push_back(info);
1779   }
1780   assert(records.size() == toUpdate.size());
1781
1782   // A) Identify all gc pointers which are staticly live at the given call
1783   // site.
1784   findLiveReferences(F, DT, P, toUpdate, records);
1785
1786   // Do a limited scalarization of any live at safepoint vector values which
1787   // contain pointers.  This enables this pass to run after vectorization at
1788   // the cost of some possible performance loss.  TODO: it would be nice to
1789   // natively support vectors all the way through the backend so we don't need
1790   // to scalarize here.
1791   for (size_t i = 0; i < records.size(); i++) {
1792     struct PartiallyConstructedSafepointRecord &info = records[i];
1793     Instruction *statepoint = toUpdate[i].getInstruction();
1794     splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
1795   }
1796
1797   // B) Find the base pointers for each live pointer
1798   /* scope for caching */ {
1799     // Cache the 'defining value' relation used in the computation and
1800     // insertion of base phis and selects.  This ensures that we don't insert
1801     // large numbers of duplicate base_phis.
1802     DefiningValueMapTy DVCache;
1803
1804     for (size_t i = 0; i < records.size(); i++) {
1805       struct PartiallyConstructedSafepointRecord &info = records[i];
1806       CallSite &CS = toUpdate[i];
1807       findBasePointers(DT, DVCache, CS, info);
1808     }
1809   } // end of cache scope
1810
1811   // The base phi insertion logic (for any safepoint) may have inserted new
1812   // instructions which are now live at some safepoint.  The simplest such
1813   // example is:
1814   // loop:
1815   //   phi a  <-- will be a new base_phi here
1816   //   safepoint 1 <-- that needs to be live here
1817   //   gep a + 1
1818   //   safepoint 2
1819   //   br loop
1820   DenseSet<llvm::Value *> allInsertedDefs;
1821   for (size_t i = 0; i < records.size(); i++) {
1822     struct PartiallyConstructedSafepointRecord &info = records[i];
1823     allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1824                            info.NewInsertedDefs.end());
1825   }
1826
1827   // We insert some dummy calls after each safepoint to definitely hold live
1828   // the base pointers which were identified for that safepoint.  We'll then
1829   // ask liveness for _every_ base inserted to see what is now live.  Then we
1830   // remove the dummy calls.
1831   holders.reserve(holders.size() + records.size());
1832   for (size_t i = 0; i < records.size(); i++) {
1833     struct PartiallyConstructedSafepointRecord &info = records[i];
1834     CallSite &CS = toUpdate[i];
1835
1836     SmallVector<Value *, 128> Bases;
1837     for (auto Pair : info.PointerToBase) {
1838       Bases.push_back(Pair.second);
1839     }
1840     insertUseHolderAfter(CS, Bases, holders);
1841   }
1842
1843   // By selecting base pointers, we've effectively inserted new uses. Thus, we
1844   // need to rerun liveness.  We may *also* have inserted new defs, but that's
1845   // not the key issue.
1846   recomputeLiveInValues(F, DT, P, toUpdate, records);
1847
1848   if (PrintBasePointers) {
1849     for (size_t i = 0; i < records.size(); i++) {
1850       struct PartiallyConstructedSafepointRecord &info = records[i];
1851       errs() << "Base Pairs: (w/Relocation)\n";
1852       for (auto Pair : info.PointerToBase) {
1853         errs() << " derived %" << Pair.first->getName() << " base %"
1854                << Pair.second->getName() << "\n";
1855       }
1856     }
1857   }
1858   for (size_t i = 0; i < holders.size(); i++) {
1859     holders[i]->eraseFromParent();
1860     holders[i] = nullptr;
1861   }
1862   holders.clear();
1863
1864   // Now run through and replace the existing statepoints with new ones with
1865   // the live variables listed.  We do not yet update uses of the values being
1866   // relocated. We have references to live variables that need to
1867   // survive to the last iteration of this loop.  (By construction, the
1868   // previous statepoint can not be a live variable, thus we can and remove
1869   // the old statepoint calls as we go.)
1870   for (size_t i = 0; i < records.size(); i++) {
1871     struct PartiallyConstructedSafepointRecord &info = records[i];
1872     CallSite &CS = toUpdate[i];
1873     makeStatepointExplicit(DT, CS, P, info);
1874   }
1875   toUpdate.clear(); // prevent accident use of invalid CallSites
1876
1877   // Do all the fixups of the original live variables to their relocated selves
1878   SmallVector<Value *, 128> live;
1879   for (size_t i = 0; i < records.size(); i++) {
1880     struct PartiallyConstructedSafepointRecord &info = records[i];
1881     // We can't simply save the live set from the original insertion.  One of
1882     // the live values might be the result of a call which needs a safepoint.
1883     // That Value* no longer exists and we need to use the new gc_result.
1884     // Thankfully, the liveset is embedded in the statepoint (and updated), so
1885     // we just grab that.
1886     Statepoint statepoint(info.StatepointToken);
1887     live.insert(live.end(), statepoint.gc_args_begin(),
1888                 statepoint.gc_args_end());
1889 #ifndef NDEBUG
1890     // Do some basic sanity checks on our liveness results before performing
1891     // relocation.  Relocation can and will turn mistakes in liveness results
1892     // into non-sensical code which is must harder to debug.
1893     // TODO: It would be nice to test consistency as well
1894     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
1895            "statepoint must be reachable or liveness is meaningless");
1896     for (Value *V : statepoint.gc_args()) {
1897       if (!isa<Instruction>(V))
1898         // Non-instruction values trivial dominate all possible uses
1899         continue;
1900       auto LiveInst = cast<Instruction>(V);
1901       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
1902              "unreachable values should never be live");
1903       assert(DT.dominates(LiveInst, info.StatepointToken) &&
1904              "basic SSA liveness expectation violated by liveness analysis");
1905     }
1906 #endif
1907   }
1908   unique_unsorted(live);
1909
1910 #ifndef NDEBUG
1911   // sanity check
1912   for (auto ptr : live) {
1913     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1914   }
1915 #endif
1916
1917   relocationViaAlloca(F, DT, live, records);
1918   return !records.empty();
1919 }
1920
1921 /// Returns true if this function should be rewritten by this pass.  The main
1922 /// point of this function is as an extension point for custom logic.
1923 static bool shouldRewriteStatepointsIn(Function &F) {
1924   // TODO: This should check the GCStrategy
1925   if (F.hasGC()) {
1926     const std::string StatepointExampleName("statepoint-example");
1927     return StatepointExampleName == F.getGC();
1928   } else
1929     return false;
1930 }
1931
1932 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1933   // Nothing to do for declarations.
1934   if (F.isDeclaration() || F.empty())
1935     return false;
1936
1937   // Policy choice says not to rewrite - the most common reason is that we're
1938   // compiling code without a GCStrategy.
1939   if (!shouldRewriteStatepointsIn(F))
1940     return false;
1941
1942   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1943
1944   // Gather all the statepoints which need rewritten.  Be careful to only
1945   // consider those in reachable code since we need to ask dominance queries
1946   // when rewriting.  We'll delete the unreachable ones in a moment.
1947   SmallVector<CallSite, 64> ParsePointNeeded;
1948   bool HasUnreachableStatepoint = false;
1949   for (Instruction &I : inst_range(F)) {
1950     // TODO: only the ones with the flag set!
1951     if (isStatepoint(I)) {
1952       if (DT.isReachableFromEntry(I.getParent()))
1953         ParsePointNeeded.push_back(CallSite(&I));
1954       else
1955         HasUnreachableStatepoint = true;
1956     }
1957   }
1958
1959   bool MadeChange = false;
1960
1961   // Delete any unreachable statepoints so that we don't have unrewritten
1962   // statepoints surviving this pass.  This makes testing easier and the
1963   // resulting IR less confusing to human readers.  Rather than be fancy, we
1964   // just reuse a utility function which removes the unreachable blocks.
1965   if (HasUnreachableStatepoint)
1966     MadeChange |= removeUnreachableBlocks(F);
1967
1968   // Return early if no work to do.
1969   if (ParsePointNeeded.empty())
1970     return MadeChange;
1971
1972   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
1973   // These are created by LCSSA.  They have the effect of increasing the size
1974   // of liveness sets for no good reason.  It may be harder to do this post
1975   // insertion since relocations and base phis can confuse things.
1976   for (BasicBlock &BB : F)
1977     if (BB.getUniquePredecessor()) {
1978       MadeChange = true;
1979       FoldSingleEntryPHINodes(&BB);
1980     }
1981
1982   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
1983   return MadeChange;
1984 }
1985
1986 // liveness computation via standard dataflow
1987 // -------------------------------------------------------------------
1988
1989 // TODO: Consider using bitvectors for liveness, the set of potentially
1990 // interesting values should be small and easy to pre-compute.
1991
1992 /// Is this value a constant consisting of entirely null values?
1993 static bool isConstantNull(Value *V) {
1994   return isa<Constant>(V) && cast<Constant>(V)->isNullValue();
1995 }
1996
1997 /// Compute the live-in set for the location rbegin starting from
1998 /// the live-out set of the basic block
1999 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2000                                 BasicBlock::reverse_iterator rend,
2001                                 DenseSet<Value *> &LiveTmp) {
2002
2003   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2004     Instruction *I = &*ritr;
2005
2006     // KILL/Def - Remove this definition from LiveIn
2007     LiveTmp.erase(I);
2008
2009     // Don't consider *uses* in PHI nodes, we handle their contribution to
2010     // predecessor blocks when we seed the LiveOut sets
2011     if (isa<PHINode>(I))
2012       continue;
2013
2014     // USE - Add to the LiveIn set for this instruction
2015     for (Value *V : I->operands()) {
2016       assert(!isUnhandledGCPointerType(V->getType()) &&
2017              "support for FCA unimplemented");
2018       if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) &&
2019           !isa<UndefValue>(V)) {
2020         // The choice to exclude null and undef is arbitrary here.  Reconsider?
2021         LiveTmp.insert(V);
2022       }
2023     }
2024   }
2025 }
2026
2027 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2028
2029   for (BasicBlock *Succ : successors(BB)) {
2030     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2031     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2032       PHINode *Phi = cast<PHINode>(&*I);
2033       Value *V = Phi->getIncomingValueForBlock(BB);
2034       assert(!isUnhandledGCPointerType(V->getType()) &&
2035              "support for FCA unimplemented");
2036       if (isHandledGCPointerType(V->getType()) && !isConstantNull(V) &&
2037           !isa<UndefValue>(V)) {
2038         // The choice to exclude null and undef is arbitrary here.  Reconsider?
2039         LiveTmp.insert(V);
2040       }
2041     }
2042   }
2043 }
2044
2045 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2046   DenseSet<Value *> KillSet;
2047   for (Instruction &I : *BB)
2048     if (isHandledGCPointerType(I.getType()))
2049       KillSet.insert(&I);
2050   return KillSet;
2051 }
2052
2053 #ifndef NDEBUG
2054 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2055 /// sanity check for the liveness computation.
2056 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2057                           TerminatorInst *TI, bool TermOkay = false) {
2058   for (Value *V : Live) {
2059     if (auto *I = dyn_cast<Instruction>(V)) {
2060       // The terminator can be a member of the LiveOut set.  LLVM's definition
2061       // of instruction dominance states that V does not dominate itself.  As
2062       // such, we need to special case this to allow it.
2063       if (TermOkay && TI == I)
2064         continue;
2065       assert(DT.dominates(I, TI) &&
2066              "basic SSA liveness expectation violated by liveness analysis");
2067     }
2068   }
2069 }
2070
2071 /// Check that all the liveness sets used during the computation of liveness
2072 /// obey basic SSA properties.  This is useful for finding cases where we miss
2073 /// a def.
2074 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2075                           BasicBlock &BB) {
2076   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2077   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2078   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2079 }
2080 #endif
2081
2082 static void computeLiveInValues(DominatorTree &DT, Function &F,
2083                                 GCPtrLivenessData &Data) {
2084
2085   SmallSetVector<BasicBlock *, 200> Worklist;
2086   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2087     // We use a SetVector so that we don't have duplicates in the worklist.
2088     Worklist.insert(pred_begin(BB), pred_end(BB));
2089   };
2090   auto NextItem = [&]() {
2091     BasicBlock *BB = Worklist.back();
2092     Worklist.pop_back();
2093     return BB;
2094   };
2095
2096   // Seed the liveness for each individual block
2097   for (BasicBlock &BB : F) {
2098     Data.KillSet[&BB] = computeKillSet(&BB);
2099     Data.LiveSet[&BB].clear();
2100     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2101
2102 #ifndef NDEBUG
2103     for (Value *Kill : Data.KillSet[&BB])
2104       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2105 #endif
2106
2107     Data.LiveOut[&BB] = DenseSet<Value *>();
2108     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2109     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2110     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2111     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2112     if (!Data.LiveIn[&BB].empty())
2113       AddPredsToWorklist(&BB);
2114   }
2115
2116   // Propagate that liveness until stable
2117   while (!Worklist.empty()) {
2118     BasicBlock *BB = NextItem();
2119
2120     // Compute our new liveout set, then exit early if it hasn't changed
2121     // despite the contribution of our successor.
2122     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2123     const auto OldLiveOutSize = LiveOut.size();
2124     for (BasicBlock *Succ : successors(BB)) {
2125       assert(Data.LiveIn.count(Succ));
2126       set_union(LiveOut, Data.LiveIn[Succ]);
2127     }
2128     // assert OutLiveOut is a subset of LiveOut
2129     if (OldLiveOutSize == LiveOut.size()) {
2130       // If the sets are the same size, then we didn't actually add anything
2131       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2132       // hasn't changed.
2133       continue;
2134     }
2135     Data.LiveOut[BB] = LiveOut;
2136
2137     // Apply the effects of this basic block
2138     DenseSet<Value *> LiveTmp = LiveOut;
2139     set_union(LiveTmp, Data.LiveSet[BB]);
2140     set_subtract(LiveTmp, Data.KillSet[BB]);
2141
2142     assert(Data.LiveIn.count(BB));
2143     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2144     // assert: OldLiveIn is a subset of LiveTmp
2145     if (OldLiveIn.size() != LiveTmp.size()) {
2146       Data.LiveIn[BB] = LiveTmp;
2147       AddPredsToWorklist(BB);
2148     }
2149   } // while( !worklist.empty() )
2150
2151 #ifndef NDEBUG
2152   // Sanity check our ouput against SSA properties.  This helps catch any
2153   // missing kills during the above iteration.
2154   for (BasicBlock &BB : F) {
2155     checkBasicSSA(DT, Data, BB);
2156   }
2157 #endif
2158 }
2159
2160 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2161                               StatepointLiveSetTy &Out) {
2162
2163   BasicBlock *BB = Inst->getParent();
2164
2165   // Note: The copy is intentional and required
2166   assert(Data.LiveOut.count(BB));
2167   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2168
2169   // We want to handle the statepoint itself oddly.  It's
2170   // call result is not live (normal), nor are it's arguments
2171   // (unless they're used again later).  This adjustment is
2172   // specifically what we need to relocate
2173   BasicBlock::reverse_iterator rend(Inst);
2174   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2175   LiveOut.erase(Inst);
2176   Out.insert(LiveOut.begin(), LiveOut.end());
2177 }
2178
2179 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2180                                   const CallSite &CS,
2181                                   PartiallyConstructedSafepointRecord &Info) {
2182   Instruction *Inst = CS.getInstruction();
2183   StatepointLiveSetTy Updated;
2184   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2185
2186 #ifndef NDEBUG
2187   DenseSet<Value *> Bases;
2188   for (auto KVPair : Info.PointerToBase) {
2189     Bases.insert(KVPair.second);
2190   }
2191 #endif
2192   // We may have base pointers which are now live that weren't before.  We need
2193   // to update the PointerToBase structure to reflect this.
2194   for (auto V : Updated)
2195     if (!Info.PointerToBase.count(V)) {
2196       assert(Bases.count(V) && "can't find base for unexpected live value");
2197       Info.PointerToBase[V] = V;
2198       continue;
2199     }
2200
2201 #ifndef NDEBUG
2202   for (auto V : Updated) {
2203     assert(Info.PointerToBase.count(V) &&
2204            "must be able to find base for live value");
2205   }
2206 #endif
2207
2208   // Remove any stale base mappings - this can happen since our liveness is
2209   // more precise then the one inherent in the base pointer analysis
2210   DenseSet<Value *> ToErase;
2211   for (auto KVPair : Info.PointerToBase)
2212     if (!Updated.count(KVPair.first))
2213       ToErase.insert(KVPair.first);
2214   for (auto V : ToErase)
2215     Info.PointerToBase.erase(V);
2216
2217 #ifndef NDEBUG
2218   for (auto KVPair : Info.PointerToBase)
2219     assert(Updated.count(KVPair.first) && "record for non-live value");
2220 #endif
2221
2222   Info.liveset = Updated;
2223 }