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