1ff0cc061SDimitry Andric //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2ff0cc061SDimitry Andric //
3ff0cc061SDimitry Andric //                     The LLVM Compiler Infrastructure
4ff0cc061SDimitry Andric //
5ff0cc061SDimitry Andric // This file is distributed under the University of Illinois Open Source
6ff0cc061SDimitry Andric // License. See LICENSE.TXT for details.
7ff0cc061SDimitry Andric //
8ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
9ff0cc061SDimitry Andric //
10ff0cc061SDimitry Andric // Rewrite an existing set of gc.statepoints such that they make potential
11ff0cc061SDimitry Andric // relocations performed by the garbage collector explicit in the IR.
12ff0cc061SDimitry Andric //
13ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
14ff0cc061SDimitry Andric 
15ff0cc061SDimitry Andric #include "llvm/Pass.h"
16ff0cc061SDimitry Andric #include "llvm/Analysis/CFG.h"
177d523365SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
18ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
19ff0cc061SDimitry Andric #include "llvm/ADT/SetOperations.h"
20ff0cc061SDimitry Andric #include "llvm/ADT/Statistic.h"
21ff0cc061SDimitry Andric #include "llvm/ADT/DenseSet.h"
22ff0cc061SDimitry Andric #include "llvm/ADT/SetVector.h"
23ff0cc061SDimitry Andric #include "llvm/ADT/StringRef.h"
247d523365SDimitry Andric #include "llvm/ADT/MapVector.h"
25ff0cc061SDimitry Andric #include "llvm/IR/BasicBlock.h"
26ff0cc061SDimitry Andric #include "llvm/IR/CallSite.h"
27ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
28ff0cc061SDimitry Andric #include "llvm/IR/Function.h"
29ff0cc061SDimitry Andric #include "llvm/IR/IRBuilder.h"
30ff0cc061SDimitry Andric #include "llvm/IR/InstIterator.h"
31ff0cc061SDimitry Andric #include "llvm/IR/Instructions.h"
32ff0cc061SDimitry Andric #include "llvm/IR/Intrinsics.h"
33ff0cc061SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
34ff0cc061SDimitry Andric #include "llvm/IR/Module.h"
3597bc6c73SDimitry Andric #include "llvm/IR/MDBuilder.h"
36ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
37ff0cc061SDimitry Andric #include "llvm/IR/Value.h"
38ff0cc061SDimitry Andric #include "llvm/IR/Verifier.h"
39ff0cc061SDimitry Andric #include "llvm/Support/Debug.h"
40ff0cc061SDimitry Andric #include "llvm/Support/CommandLine.h"
41ff0cc061SDimitry Andric #include "llvm/Transforms/Scalar.h"
42ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
44ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
45ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
46ff0cc061SDimitry Andric 
47ff0cc061SDimitry Andric #define DEBUG_TYPE "rewrite-statepoints-for-gc"
48ff0cc061SDimitry Andric 
49ff0cc061SDimitry Andric using namespace llvm;
50ff0cc061SDimitry Andric 
51ff0cc061SDimitry Andric // Print the liveset found at the insert location
52ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53ff0cc061SDimitry Andric                                   cl::init(false));
54ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55ff0cc061SDimitry Andric                                       cl::init(false));
56ff0cc061SDimitry Andric // Print out the base pointers for debugging
57ff0cc061SDimitry Andric static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58ff0cc061SDimitry Andric                                        cl::init(false));
59ff0cc061SDimitry Andric 
60ff0cc061SDimitry Andric // Cost threshold measuring when it is profitable to rematerialize value instead
61ff0cc061SDimitry Andric // of relocating it
62ff0cc061SDimitry Andric static cl::opt<unsigned>
63ff0cc061SDimitry Andric RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64ff0cc061SDimitry Andric                            cl::init(6));
65ff0cc061SDimitry Andric 
66ff0cc061SDimitry Andric #ifdef XDEBUG
67ff0cc061SDimitry Andric static bool ClobberNonLive = true;
68ff0cc061SDimitry Andric #else
69ff0cc061SDimitry Andric static bool ClobberNonLive = false;
70ff0cc061SDimitry Andric #endif
71ff0cc061SDimitry Andric static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72ff0cc061SDimitry Andric                                                   cl::location(ClobberNonLive),
73ff0cc061SDimitry Andric                                                   cl::Hidden);
74ff0cc061SDimitry Andric 
757d523365SDimitry Andric static cl::opt<bool> UseDeoptBundles("rs4gc-use-deopt-bundles", cl::Hidden,
767d523365SDimitry Andric                                      cl::init(false));
777d523365SDimitry Andric static cl::opt<bool>
787d523365SDimitry Andric     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
797d523365SDimitry Andric                                    cl::Hidden, cl::init(true));
807d523365SDimitry Andric 
81ff0cc061SDimitry Andric namespace {
8297bc6c73SDimitry Andric struct RewriteStatepointsForGC : public ModulePass {
83ff0cc061SDimitry Andric   static char ID; // Pass identification, replacement for typeid
84ff0cc061SDimitry Andric 
8597bc6c73SDimitry Andric   RewriteStatepointsForGC() : ModulePass(ID) {
86ff0cc061SDimitry Andric     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
87ff0cc061SDimitry Andric   }
8897bc6c73SDimitry Andric   bool runOnFunction(Function &F);
8997bc6c73SDimitry Andric   bool runOnModule(Module &M) override {
9097bc6c73SDimitry Andric     bool Changed = false;
9197bc6c73SDimitry Andric     for (Function &F : M)
9297bc6c73SDimitry Andric       Changed |= runOnFunction(F);
9397bc6c73SDimitry Andric 
9497bc6c73SDimitry Andric     if (Changed) {
957d523365SDimitry Andric       // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
9697bc6c73SDimitry Andric       // returns true for at least one function in the module.  Since at least
9797bc6c73SDimitry Andric       // one function changed, we know that the precondition is satisfied.
987d523365SDimitry Andric       stripNonValidAttributes(M);
9997bc6c73SDimitry Andric     }
10097bc6c73SDimitry Andric 
10197bc6c73SDimitry Andric     return Changed;
10297bc6c73SDimitry Andric   }
103ff0cc061SDimitry Andric 
104ff0cc061SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
105ff0cc061SDimitry Andric     // We add and rewrite a bunch of instructions, but don't really do much
106ff0cc061SDimitry Andric     // else.  We could in theory preserve a lot more analyses here.
107ff0cc061SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
108ff0cc061SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
109ff0cc061SDimitry Andric   }
11097bc6c73SDimitry Andric 
11197bc6c73SDimitry Andric   /// The IR fed into RewriteStatepointsForGC may have had attributes implying
11297bc6c73SDimitry Andric   /// dereferenceability that are no longer valid/correct after
11397bc6c73SDimitry Andric   /// RewriteStatepointsForGC has run.  This is because semantically, after
11497bc6c73SDimitry Andric   /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
1157d523365SDimitry Andric   /// heap.  stripNonValidAttributes (conservatively) restores correctness
11697bc6c73SDimitry Andric   /// by erasing all attributes in the module that externally imply
11797bc6c73SDimitry Andric   /// dereferenceability.
1187d523365SDimitry Andric   /// Similar reasoning also applies to the noalias attributes. gc.statepoint
1197d523365SDimitry Andric   /// can touch the entire heap including noalias objects.
1207d523365SDimitry Andric   void stripNonValidAttributes(Module &M);
12197bc6c73SDimitry Andric 
1227d523365SDimitry Andric   // Helpers for stripNonValidAttributes
1237d523365SDimitry Andric   void stripNonValidAttributesFromBody(Function &F);
1247d523365SDimitry Andric   void stripNonValidAttributesFromPrototype(Function &F);
125ff0cc061SDimitry Andric };
126ff0cc061SDimitry Andric } // namespace
127ff0cc061SDimitry Andric 
128ff0cc061SDimitry Andric char RewriteStatepointsForGC::ID = 0;
129ff0cc061SDimitry Andric 
13097bc6c73SDimitry Andric ModulePass *llvm::createRewriteStatepointsForGCPass() {
131ff0cc061SDimitry Andric   return new RewriteStatepointsForGC();
132ff0cc061SDimitry Andric }
133ff0cc061SDimitry Andric 
134ff0cc061SDimitry Andric INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
135ff0cc061SDimitry Andric                       "Make relocations explicit at statepoints", false, false)
136ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
137ff0cc061SDimitry Andric INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
138ff0cc061SDimitry Andric                     "Make relocations explicit at statepoints", false, false)
139ff0cc061SDimitry Andric 
140ff0cc061SDimitry Andric namespace {
141ff0cc061SDimitry Andric struct GCPtrLivenessData {
142ff0cc061SDimitry Andric   /// Values defined in this block.
143ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
144ff0cc061SDimitry Andric   /// Values used in this block (and thus live); does not included values
145ff0cc061SDimitry Andric   /// killed within this block.
146ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
147ff0cc061SDimitry Andric 
148ff0cc061SDimitry Andric   /// Values live into this basic block (i.e. used by any
149ff0cc061SDimitry Andric   /// instruction in this basic block or ones reachable from here)
150ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
151ff0cc061SDimitry Andric 
152ff0cc061SDimitry Andric   /// Values live out of this basic block (i.e. live into
153ff0cc061SDimitry Andric   /// any successor block)
154ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
155ff0cc061SDimitry Andric };
156ff0cc061SDimitry Andric 
157ff0cc061SDimitry Andric // The type of the internal cache used inside the findBasePointers family
158ff0cc061SDimitry Andric // of functions.  From the callers perspective, this is an opaque type and
159ff0cc061SDimitry Andric // should not be inspected.
160ff0cc061SDimitry Andric //
161ff0cc061SDimitry Andric // In the actual implementation this caches two relations:
162ff0cc061SDimitry Andric // - The base relation itself (i.e. this pointer is based on that one)
163ff0cc061SDimitry Andric // - The base defining value relation (i.e. before base_phi insertion)
164ff0cc061SDimitry Andric // Generally, after the execution of a full findBasePointer call, only the
165ff0cc061SDimitry Andric // base relation will remain.  Internally, we add a mixture of the two
166ff0cc061SDimitry Andric // types, then update all the second type to the first type
167ff0cc061SDimitry Andric typedef DenseMap<Value *, Value *> DefiningValueMapTy;
1687d523365SDimitry Andric typedef DenseSet<Value *> StatepointLiveSetTy;
1697d523365SDimitry Andric typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
1707d523365SDimitry Andric   RematerializedValueMapTy;
171ff0cc061SDimitry Andric 
172ff0cc061SDimitry Andric struct PartiallyConstructedSafepointRecord {
1737d523365SDimitry Andric   /// The set of values known to be live across this safepoint
1747d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
175ff0cc061SDimitry Andric 
176ff0cc061SDimitry Andric   /// Mapping from live pointers to a base-defining-value
1777d523365SDimitry Andric   DenseMap<Value *, Value *> PointerToBase;
178ff0cc061SDimitry Andric 
179ff0cc061SDimitry Andric   /// The *new* gc.statepoint instruction itself.  This produces the token
180ff0cc061SDimitry Andric   /// that normal path gc.relocates and the gc.result are tied to.
181ff0cc061SDimitry Andric   Instruction *StatepointToken;
182ff0cc061SDimitry Andric 
183ff0cc061SDimitry Andric   /// Instruction to which exceptional gc relocates are attached
184ff0cc061SDimitry Andric   /// Makes it easier to iterate through them during relocationViaAlloca.
185ff0cc061SDimitry Andric   Instruction *UnwindToken;
186ff0cc061SDimitry Andric 
187ff0cc061SDimitry Andric   /// Record live values we are rematerialized instead of relocating.
1887d523365SDimitry Andric   /// They are not included into 'LiveSet' field.
189ff0cc061SDimitry Andric   /// Maps rematerialized copy to it's original value.
190ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues;
191ff0cc061SDimitry Andric };
1923dac3a9bSDimitry Andric }
193ff0cc061SDimitry Andric 
1947d523365SDimitry Andric static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
1957d523365SDimitry Andric   assert(UseDeoptBundles && "Should not be called otherwise!");
1967d523365SDimitry Andric 
1977d523365SDimitry Andric   Optional<OperandBundleUse> DeoptBundle = CS.getOperandBundle("deopt");
1987d523365SDimitry Andric 
1997d523365SDimitry Andric   if (!DeoptBundle.hasValue()) {
2007d523365SDimitry Andric     assert(AllowStatepointWithNoDeoptInfo &&
2017d523365SDimitry Andric            "Found non-leaf call without deopt info!");
2027d523365SDimitry Andric     return None;
2037d523365SDimitry Andric   }
2047d523365SDimitry Andric 
2057d523365SDimitry Andric   return DeoptBundle.getValue().Inputs;
2067d523365SDimitry Andric }
2077d523365SDimitry Andric 
208ff0cc061SDimitry Andric /// Compute the live-in set for every basic block in the function
209ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
210ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data);
211ff0cc061SDimitry Andric 
212ff0cc061SDimitry Andric /// Given results from the dataflow liveness computation, find the set of live
213ff0cc061SDimitry Andric /// Values at a particular instruction.
214ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
215ff0cc061SDimitry Andric                               StatepointLiveSetTy &out);
216ff0cc061SDimitry Andric 
217ff0cc061SDimitry Andric // TODO: Once we can get to the GCStrategy, this becomes
2187d523365SDimitry Andric // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
219ff0cc061SDimitry Andric 
2207d523365SDimitry Andric static bool isGCPointerType(Type *T) {
2217d523365SDimitry Andric   if (auto *PT = dyn_cast<PointerType>(T))
222ff0cc061SDimitry Andric     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
223ff0cc061SDimitry Andric     // GC managed heap.  We know that a pointer into this heap needs to be
224ff0cc061SDimitry Andric     // updated and that no other pointer does.
225ff0cc061SDimitry Andric     return (1 == PT->getAddressSpace());
226ff0cc061SDimitry Andric   return false;
227ff0cc061SDimitry Andric }
228ff0cc061SDimitry Andric 
229ff0cc061SDimitry Andric // Return true if this type is one which a) is a gc pointer or contains a GC
230ff0cc061SDimitry Andric // pointer and b) is of a type this code expects to encounter as a live value.
231ff0cc061SDimitry Andric // (The insertion code will assert that a type which matches (a) and not (b)
232ff0cc061SDimitry Andric // is not encountered.)
233ff0cc061SDimitry Andric static bool isHandledGCPointerType(Type *T) {
234ff0cc061SDimitry Andric   // We fully support gc pointers
235ff0cc061SDimitry Andric   if (isGCPointerType(T))
236ff0cc061SDimitry Andric     return true;
237ff0cc061SDimitry Andric   // We partially support vectors of gc pointers. The code will assert if it
238ff0cc061SDimitry Andric   // can't handle something.
239ff0cc061SDimitry Andric   if (auto VT = dyn_cast<VectorType>(T))
240ff0cc061SDimitry Andric     if (isGCPointerType(VT->getElementType()))
241ff0cc061SDimitry Andric       return true;
242ff0cc061SDimitry Andric   return false;
243ff0cc061SDimitry Andric }
244ff0cc061SDimitry Andric 
245ff0cc061SDimitry Andric #ifndef NDEBUG
246ff0cc061SDimitry Andric /// Returns true if this type contains a gc pointer whether we know how to
247ff0cc061SDimitry Andric /// handle that type or not.
248ff0cc061SDimitry Andric static bool containsGCPtrType(Type *Ty) {
249ff0cc061SDimitry Andric   if (isGCPointerType(Ty))
250ff0cc061SDimitry Andric     return true;
251ff0cc061SDimitry Andric   if (VectorType *VT = dyn_cast<VectorType>(Ty))
252ff0cc061SDimitry Andric     return isGCPointerType(VT->getScalarType());
253ff0cc061SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
254ff0cc061SDimitry Andric     return containsGCPtrType(AT->getElementType());
255ff0cc061SDimitry Andric   if (StructType *ST = dyn_cast<StructType>(Ty))
2567d523365SDimitry Andric     return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
2577d523365SDimitry Andric                        containsGCPtrType);
258ff0cc061SDimitry Andric   return false;
259ff0cc061SDimitry Andric }
260ff0cc061SDimitry Andric 
261ff0cc061SDimitry Andric // Returns true if this is a type which a) is a gc pointer or contains a GC
262ff0cc061SDimitry Andric // pointer and b) is of a type which the code doesn't expect (i.e. first class
263ff0cc061SDimitry Andric // aggregates).  Used to trip assertions.
264ff0cc061SDimitry Andric static bool isUnhandledGCPointerType(Type *Ty) {
265ff0cc061SDimitry Andric   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
266ff0cc061SDimitry Andric }
267ff0cc061SDimitry Andric #endif
268ff0cc061SDimitry Andric 
2697d523365SDimitry Andric static bool order_by_name(Value *a, Value *b) {
270ff0cc061SDimitry Andric   if (a->hasName() && b->hasName()) {
271ff0cc061SDimitry Andric     return -1 == a->getName().compare(b->getName());
272ff0cc061SDimitry Andric   } else if (a->hasName() && !b->hasName()) {
273ff0cc061SDimitry Andric     return true;
274ff0cc061SDimitry Andric   } else if (!a->hasName() && b->hasName()) {
275ff0cc061SDimitry Andric     return false;
276ff0cc061SDimitry Andric   } else {
277ff0cc061SDimitry Andric     // Better than nothing, but not stable
278ff0cc061SDimitry Andric     return a < b;
279ff0cc061SDimitry Andric   }
280ff0cc061SDimitry Andric }
281ff0cc061SDimitry Andric 
2827d523365SDimitry Andric // Return the name of the value suffixed with the provided value, or if the
2837d523365SDimitry Andric // value didn't have a name, the default value specified.
2847d523365SDimitry Andric static std::string suffixed_name_or(Value *V, StringRef Suffix,
2857d523365SDimitry Andric                                     StringRef DefaultName) {
2867d523365SDimitry Andric   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
2877d523365SDimitry Andric }
2887d523365SDimitry Andric 
289ff0cc061SDimitry Andric // Conservatively identifies any definitions which might be live at the
290ff0cc061SDimitry Andric // given instruction. The  analysis is performed immediately before the
291ff0cc061SDimitry Andric // given instruction. Values defined by that instruction are not considered
292ff0cc061SDimitry Andric // live.  Values used by that instruction are considered live.
293ff0cc061SDimitry Andric static void analyzeParsePointLiveness(
294ff0cc061SDimitry Andric     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
295ff0cc061SDimitry Andric     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
296ff0cc061SDimitry Andric   Instruction *inst = CS.getInstruction();
297ff0cc061SDimitry Andric 
2987d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
2997d523365SDimitry Andric   findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
300ff0cc061SDimitry Andric 
301ff0cc061SDimitry Andric   if (PrintLiveSet) {
302ff0cc061SDimitry Andric     // Note: This output is used by several of the test cases
3037d523365SDimitry Andric     // The order of elements in a set is not stable, put them in a vec and sort
304ff0cc061SDimitry Andric     // by name
3057d523365SDimitry Andric     SmallVector<Value *, 64> Temp;
3067d523365SDimitry Andric     Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
3077d523365SDimitry Andric     std::sort(Temp.begin(), Temp.end(), order_by_name);
308ff0cc061SDimitry Andric     errs() << "Live Variables:\n";
3097d523365SDimitry Andric     for (Value *V : Temp)
3107d523365SDimitry Andric       dbgs() << " " << V->getName() << " " << *V << "\n";
311ff0cc061SDimitry Andric   }
312ff0cc061SDimitry Andric   if (PrintLiveSetSize) {
313ff0cc061SDimitry Andric     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
3147d523365SDimitry Andric     errs() << "Number live values: " << LiveSet.size() << "\n";
315ff0cc061SDimitry Andric   }
3167d523365SDimitry Andric   result.LiveSet = LiveSet;
317ff0cc061SDimitry Andric }
318ff0cc061SDimitry Andric 
3197d523365SDimitry Andric static bool isKnownBaseResult(Value *V);
3207d523365SDimitry Andric namespace {
3217d523365SDimitry Andric /// A single base defining value - An immediate base defining value for an
3227d523365SDimitry Andric /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
3237d523365SDimitry Andric /// For instructions which have multiple pointer [vector] inputs or that
3247d523365SDimitry Andric /// transition between vector and scalar types, there is no immediate base
3257d523365SDimitry Andric /// defining value.  The 'base defining value' for 'Def' is the transitive
3267d523365SDimitry Andric /// closure of this relation stopping at the first instruction which has no
3277d523365SDimitry Andric /// immediate base defining value.  The b.d.v. might itself be a base pointer,
3287d523365SDimitry Andric /// but it can also be an arbitrary derived pointer.
3297d523365SDimitry Andric struct BaseDefiningValueResult {
3307d523365SDimitry Andric   /// Contains the value which is the base defining value.
3317d523365SDimitry Andric   Value * const BDV;
3327d523365SDimitry Andric   /// True if the base defining value is also known to be an actual base
3337d523365SDimitry Andric   /// pointer.
3347d523365SDimitry Andric   const bool IsKnownBase;
3357d523365SDimitry Andric   BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
3367d523365SDimitry Andric     : BDV(BDV), IsKnownBase(IsKnownBase) {
3377d523365SDimitry Andric #ifndef NDEBUG
3387d523365SDimitry Andric     // Check consistency between new and old means of checking whether a BDV is
3397d523365SDimitry Andric     // a base.
3407d523365SDimitry Andric     bool MustBeBase = isKnownBaseResult(BDV);
3417d523365SDimitry Andric     assert(!MustBeBase || MustBeBase == IsKnownBase);
3427d523365SDimitry Andric #endif
3437d523365SDimitry Andric   }
3447d523365SDimitry Andric };
3457d523365SDimitry Andric }
3467d523365SDimitry Andric 
3477d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I);
348ff0cc061SDimitry Andric 
3493dac3a9bSDimitry Andric /// Return a base defining value for the 'Index' element of the given vector
3503dac3a9bSDimitry Andric /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
3513dac3a9bSDimitry Andric /// 'I'.  As an optimization, this method will try to determine when the
3523dac3a9bSDimitry Andric /// element is known to already be a base pointer.  If this can be established,
3533dac3a9bSDimitry Andric /// the second value in the returned pair will be true.  Note that either a
3543dac3a9bSDimitry Andric /// vector or a pointer typed value can be returned.  For the former, the
3553dac3a9bSDimitry Andric /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
3563dac3a9bSDimitry Andric /// If the later, the return pointer is a BDV (or possibly a base) for the
3573dac3a9bSDimitry Andric /// particular element in 'I'.
3587d523365SDimitry Andric static BaseDefiningValueResult
3597d523365SDimitry Andric findBaseDefiningValueOfVector(Value *I) {
360ff0cc061SDimitry Andric   assert(I->getType()->isVectorTy() &&
361ff0cc061SDimitry Andric          cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
362ff0cc061SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
363ff0cc061SDimitry Andric 
364ff0cc061SDimitry Andric   // Each case parallels findBaseDefiningValue below, see that code for
365ff0cc061SDimitry Andric   // detailed motivation.
366ff0cc061SDimitry Andric 
367ff0cc061SDimitry Andric   if (isa<Argument>(I))
368ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
3697d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
370ff0cc061SDimitry Andric 
371ff0cc061SDimitry Andric   // We shouldn't see the address of a global as a vector value?
372ff0cc061SDimitry Andric   assert(!isa<GlobalVariable>(I) &&
373ff0cc061SDimitry Andric          "unexpected global variable found in base of vector");
374ff0cc061SDimitry Andric 
375ff0cc061SDimitry Andric   // inlining could possibly introduce phi node that contains
376ff0cc061SDimitry Andric   // undef if callee has multiple returns
377ff0cc061SDimitry Andric   if (isa<UndefValue>(I))
378ff0cc061SDimitry Andric     // utterly meaningless, but useful for dealing with partially optimized
379ff0cc061SDimitry Andric     // code.
3807d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
381ff0cc061SDimitry Andric 
382ff0cc061SDimitry Andric   // Due to inheritance, this must be _after_ the global variable and undef
383ff0cc061SDimitry Andric   // checks
384ff0cc061SDimitry Andric   if (Constant *Con = dyn_cast<Constant>(I)) {
385ff0cc061SDimitry Andric     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
386ff0cc061SDimitry Andric            "order of checks wrong!");
387ff0cc061SDimitry Andric     assert(Con->isNullValue() && "null is the only case which makes sense");
3887d523365SDimitry Andric     return BaseDefiningValueResult(Con, true);
389ff0cc061SDimitry Andric   }
390ff0cc061SDimitry Andric 
391ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
3927d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
393ff0cc061SDimitry Andric 
3947d523365SDimitry Andric   if (isa<InsertElementInst>(I))
3953dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
3963dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
3973dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
3987d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
399ff0cc061SDimitry Andric 
4003dac3a9bSDimitry Andric   if (isa<ShuffleVectorInst>(I))
4013dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
4023dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
4033dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
4043dac3a9bSDimitry Andric     // TODO: There a number of local optimizations which could be applied here
4053dac3a9bSDimitry Andric     // for particular sufflevector patterns.
4067d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
4073dac3a9bSDimitry Andric 
4083dac3a9bSDimitry Andric   // A PHI or Select is a base defining value.  The outer findBasePointer
4093dac3a9bSDimitry Andric   // algorithm is responsible for constructing a base value for this BDV.
4103dac3a9bSDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
4113dac3a9bSDimitry Andric          "unknown vector instruction - no base found for vector element");
4127d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
4133dac3a9bSDimitry Andric }
4143dac3a9bSDimitry Andric 
415ff0cc061SDimitry Andric /// Helper function for findBasePointer - Will return a value which either a)
4167d523365SDimitry Andric /// defines the base pointer for the input, b) blocks the simple search
4177d523365SDimitry Andric /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
4187d523365SDimitry Andric /// from pointer to vector type or back.
4197d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
4203dac3a9bSDimitry Andric   if (I->getType()->isVectorTy())
4217d523365SDimitry Andric     return findBaseDefiningValueOfVector(I);
4223dac3a9bSDimitry Andric 
423ff0cc061SDimitry Andric   assert(I->getType()->isPointerTy() &&
424ff0cc061SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
425ff0cc061SDimitry Andric 
426ff0cc061SDimitry Andric   if (isa<Argument>(I))
427ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
428ff0cc061SDimitry Andric     // We should have never reached here if this argument isn't an gc value
4297d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
430ff0cc061SDimitry Andric 
4314d0b32cdSDimitry Andric   if (isa<Constant>(I))
4324d0b32cdSDimitry Andric     // We assume that objects with a constant base (e.g. a global) can't move
4334d0b32cdSDimitry Andric     // and don't need to be reported to the collector because they are always
4344d0b32cdSDimitry Andric     // live.  All constants have constant bases.  Besides global references, all
4354d0b32cdSDimitry Andric     // kinds of constants (e.g. undef, constant expressions, null pointers) can
4364d0b32cdSDimitry Andric     // be introduced by the inliner or the optimizer, especially on dynamically
4374d0b32cdSDimitry Andric     // dead paths.  See e.g. test4 in constants.ll.
4387d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
439ff0cc061SDimitry Andric 
440ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
441ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
4427d523365SDimitry Andric     // If stripping pointer casts changes the address space there is an
4437d523365SDimitry Andric     // addrspacecast in between.
4447d523365SDimitry Andric     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
4457d523365SDimitry Andric                cast<PointerType>(CI->getType())->getAddressSpace() &&
4467d523365SDimitry Andric            "unsupported addrspacecast");
447ff0cc061SDimitry Andric     // If we find a cast instruction here, it means we've found a cast which is
448ff0cc061SDimitry Andric     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
449ff0cc061SDimitry Andric     // handle int->ptr conversion.
450ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
451ff0cc061SDimitry Andric     return findBaseDefiningValue(Def);
452ff0cc061SDimitry Andric   }
453ff0cc061SDimitry Andric 
454ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
4557d523365SDimitry Andric     // The value loaded is an gc base itself
4567d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
4577d523365SDimitry Andric 
458ff0cc061SDimitry Andric 
459ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
460ff0cc061SDimitry Andric     // The base of this GEP is the base
461ff0cc061SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
462ff0cc061SDimitry Andric 
463ff0cc061SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
464ff0cc061SDimitry Andric     switch (II->getIntrinsicID()) {
465ff0cc061SDimitry Andric     default:
466ff0cc061SDimitry Andric       // fall through to general call handling
467ff0cc061SDimitry Andric       break;
468ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_statepoint:
4697d523365SDimitry Andric       llvm_unreachable("statepoints don't produce pointers");
470ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_relocate: {
471ff0cc061SDimitry Andric       // Rerunning safepoint insertion after safepoints are already
472ff0cc061SDimitry Andric       // inserted is not supported.  It could probably be made to work,
473ff0cc061SDimitry Andric       // but why are you doing this?  There's no good reason.
474ff0cc061SDimitry Andric       llvm_unreachable("repeat safepoint insertion is not supported");
475ff0cc061SDimitry Andric     }
476ff0cc061SDimitry Andric     case Intrinsic::gcroot:
477ff0cc061SDimitry Andric       // Currently, this mechanism hasn't been extended to work with gcroot.
478ff0cc061SDimitry Andric       // There's no reason it couldn't be, but I haven't thought about the
479ff0cc061SDimitry Andric       // implications much.
480ff0cc061SDimitry Andric       llvm_unreachable(
481ff0cc061SDimitry Andric           "interaction with the gcroot mechanism is not supported");
482ff0cc061SDimitry Andric     }
483ff0cc061SDimitry Andric   }
484ff0cc061SDimitry Andric   // We assume that functions in the source language only return base
485ff0cc061SDimitry Andric   // pointers.  This should probably be generalized via attributes to support
486ff0cc061SDimitry Andric   // both source language and internal functions.
487ff0cc061SDimitry Andric   if (isa<CallInst>(I) || isa<InvokeInst>(I))
4887d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
489ff0cc061SDimitry Andric 
490ff0cc061SDimitry Andric   // I have absolutely no idea how to implement this part yet.  It's not
4917d523365SDimitry Andric   // necessarily hard, I just haven't really looked at it yet.
492ff0cc061SDimitry Andric   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
493ff0cc061SDimitry Andric 
494ff0cc061SDimitry Andric   if (isa<AtomicCmpXchgInst>(I))
495ff0cc061SDimitry Andric     // A CAS is effectively a atomic store and load combined under a
496ff0cc061SDimitry Andric     // predicate.  From the perspective of base pointers, we just treat it
497ff0cc061SDimitry Andric     // like a load.
4987d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
499ff0cc061SDimitry Andric 
500ff0cc061SDimitry Andric   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
501ff0cc061SDimitry Andric                                    "binary ops which don't apply to pointers");
502ff0cc061SDimitry Andric 
503ff0cc061SDimitry Andric   // The aggregate ops.  Aggregates can either be in the heap or on the
504ff0cc061SDimitry Andric   // stack, but in either case, this is simply a field load.  As a result,
505ff0cc061SDimitry Andric   // this is a defining definition of the base just like a load is.
506ff0cc061SDimitry Andric   if (isa<ExtractValueInst>(I))
5077d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
508ff0cc061SDimitry Andric 
509ff0cc061SDimitry Andric   // We should never see an insert vector since that would require we be
510ff0cc061SDimitry Andric   // tracing back a struct value not a pointer value.
511ff0cc061SDimitry Andric   assert(!isa<InsertValueInst>(I) &&
512ff0cc061SDimitry Andric          "Base pointer for a struct is meaningless");
513ff0cc061SDimitry Andric 
5147d523365SDimitry Andric   // An extractelement produces a base result exactly when it's input does.
5157d523365SDimitry Andric   // We may need to insert a parallel instruction to extract the appropriate
5167d523365SDimitry Andric   // element out of the base vector corresponding to the input. Given this,
5177d523365SDimitry Andric   // it's analogous to the phi and select case even though it's not a merge.
5187d523365SDimitry Andric   if (isa<ExtractElementInst>(I))
5197d523365SDimitry Andric     // Note: There a lot of obvious peephole cases here.  This are deliberately
5207d523365SDimitry Andric     // handled after the main base pointer inference algorithm to make writing
5217d523365SDimitry Andric     // test cases to exercise that code easier.
5227d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
5237d523365SDimitry Andric 
524ff0cc061SDimitry Andric   // The last two cases here don't return a base pointer.  Instead, they
5257d523365SDimitry Andric   // return a value which dynamically selects from among several base
526ff0cc061SDimitry Andric   // derived pointers (each with it's own base potentially).  It's the job of
527ff0cc061SDimitry Andric   // the caller to resolve these.
528ff0cc061SDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
529ff0cc061SDimitry Andric          "missing instruction case in findBaseDefiningValing");
5307d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
531ff0cc061SDimitry Andric }
532ff0cc061SDimitry Andric 
533ff0cc061SDimitry Andric /// Returns the base defining value for this value.
534ff0cc061SDimitry Andric static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
535ff0cc061SDimitry Andric   Value *&Cached = Cache[I];
536ff0cc061SDimitry Andric   if (!Cached) {
5377d523365SDimitry Andric     Cached = findBaseDefiningValue(I).BDV;
5387d523365SDimitry Andric     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
5397d523365SDimitry Andric                  << Cached->getName() << "\n");
540ff0cc061SDimitry Andric   }
541ff0cc061SDimitry Andric   assert(Cache[I] != nullptr);
542ff0cc061SDimitry Andric   return Cached;
543ff0cc061SDimitry Andric }
544ff0cc061SDimitry Andric 
545ff0cc061SDimitry Andric /// Return a base pointer for this value if known.  Otherwise, return it's
546ff0cc061SDimitry Andric /// base defining value.
547ff0cc061SDimitry Andric static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
548ff0cc061SDimitry Andric   Value *Def = findBaseDefiningValueCached(I, Cache);
549ff0cc061SDimitry Andric   auto Found = Cache.find(Def);
550ff0cc061SDimitry Andric   if (Found != Cache.end()) {
551ff0cc061SDimitry Andric     // Either a base-of relation, or a self reference.  Caller must check.
552ff0cc061SDimitry Andric     return Found->second;
553ff0cc061SDimitry Andric   }
554ff0cc061SDimitry Andric   // Only a BDV available
555ff0cc061SDimitry Andric   return Def;
556ff0cc061SDimitry Andric }
557ff0cc061SDimitry Andric 
558ff0cc061SDimitry Andric /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
559ff0cc061SDimitry Andric /// is it known to be a base pointer?  Or do we need to continue searching.
560ff0cc061SDimitry Andric static bool isKnownBaseResult(Value *V) {
5617d523365SDimitry Andric   if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
5627d523365SDimitry Andric       !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
5637d523365SDimitry Andric       !isa<ShuffleVectorInst>(V)) {
564ff0cc061SDimitry Andric     // no recursion possible
565ff0cc061SDimitry Andric     return true;
566ff0cc061SDimitry Andric   }
567ff0cc061SDimitry Andric   if (isa<Instruction>(V) &&
568ff0cc061SDimitry Andric       cast<Instruction>(V)->getMetadata("is_base_value")) {
569ff0cc061SDimitry Andric     // This is a previously inserted base phi or select.  We know
570ff0cc061SDimitry Andric     // that this is a base value.
571ff0cc061SDimitry Andric     return true;
572ff0cc061SDimitry Andric   }
573ff0cc061SDimitry Andric 
574ff0cc061SDimitry Andric   // We need to keep searching
575ff0cc061SDimitry Andric   return false;
576ff0cc061SDimitry Andric }
577ff0cc061SDimitry Andric 
578ff0cc061SDimitry Andric namespace {
5797d523365SDimitry Andric /// Models the state of a single base defining value in the findBasePointer
5807d523365SDimitry Andric /// algorithm for determining where a new instruction is needed to propagate
5817d523365SDimitry Andric /// the base of this BDV.
5827d523365SDimitry Andric class BDVState {
583ff0cc061SDimitry Andric public:
584ff0cc061SDimitry Andric   enum Status { Unknown, Base, Conflict };
585ff0cc061SDimitry Andric 
5867d523365SDimitry Andric   BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
587ff0cc061SDimitry Andric     assert(status != Base || b);
588ff0cc061SDimitry Andric   }
5897d523365SDimitry Andric   explicit BDVState(Value *b) : status(Base), base(b) {}
5907d523365SDimitry Andric   BDVState() : status(Unknown), base(nullptr) {}
591ff0cc061SDimitry Andric 
592ff0cc061SDimitry Andric   Status getStatus() const { return status; }
593ff0cc061SDimitry Andric   Value *getBase() const { return base; }
594ff0cc061SDimitry Andric 
595ff0cc061SDimitry Andric   bool isBase() const { return getStatus() == Base; }
596ff0cc061SDimitry Andric   bool isUnknown() const { return getStatus() == Unknown; }
597ff0cc061SDimitry Andric   bool isConflict() const { return getStatus() == Conflict; }
598ff0cc061SDimitry Andric 
5997d523365SDimitry Andric   bool operator==(const BDVState &other) const {
600ff0cc061SDimitry Andric     return base == other.base && status == other.status;
601ff0cc061SDimitry Andric   }
602ff0cc061SDimitry Andric 
6037d523365SDimitry Andric   bool operator!=(const BDVState &other) const { return !(*this == other); }
604ff0cc061SDimitry Andric 
6057d523365SDimitry Andric   LLVM_DUMP_METHOD
6067d523365SDimitry Andric   void dump() const { print(dbgs()); dbgs() << '\n'; }
6077d523365SDimitry Andric 
6087d523365SDimitry Andric   void print(raw_ostream &OS) const {
6097d523365SDimitry Andric     switch (status) {
6107d523365SDimitry Andric     case Unknown:
6117d523365SDimitry Andric       OS << "U";
6127d523365SDimitry Andric       break;
6137d523365SDimitry Andric     case Base:
6147d523365SDimitry Andric       OS << "B";
6157d523365SDimitry Andric       break;
6167d523365SDimitry Andric     case Conflict:
6177d523365SDimitry Andric       OS << "C";
6187d523365SDimitry Andric       break;
6197d523365SDimitry Andric     };
6207d523365SDimitry Andric     OS << " (" << base << " - "
621ff0cc061SDimitry Andric        << (base ? base->getName() : "nullptr") << "): ";
622ff0cc061SDimitry Andric   }
623ff0cc061SDimitry Andric 
624ff0cc061SDimitry Andric private:
625ff0cc061SDimitry Andric   Status status;
6267d523365SDimitry Andric   AssertingVH<Value> base; // non null only if status == base
627ff0cc061SDimitry Andric };
628ff0cc061SDimitry Andric }
629ff0cc061SDimitry Andric 
6307d523365SDimitry Andric #ifndef NDEBUG
6317d523365SDimitry Andric static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
6327d523365SDimitry Andric   State.print(OS);
6337d523365SDimitry Andric   return OS;
6347d523365SDimitry Andric }
6357d523365SDimitry Andric #endif
6367d523365SDimitry Andric 
6377d523365SDimitry Andric namespace {
6387d523365SDimitry Andric // Values of type BDVState form a lattice, and this is a helper
6397d523365SDimitry Andric // class that implementes the meet operation.  The meat of the meet
6407d523365SDimitry Andric // operation is implemented in MeetBDVStates::pureMeet
6417d523365SDimitry Andric class MeetBDVStates {
6427d523365SDimitry Andric public:
6437d523365SDimitry Andric   /// Initializes the currentResult to the TOP state so that if can be met with
6447d523365SDimitry Andric   /// any other state to produce that state.
6457d523365SDimitry Andric   MeetBDVStates() {}
6467d523365SDimitry Andric 
6477d523365SDimitry Andric   // Destructively meet the current result with the given BDVState
6487d523365SDimitry Andric   void meetWith(BDVState otherState) {
6497d523365SDimitry Andric     currentResult = meet(otherState, currentResult);
6507d523365SDimitry Andric   }
6517d523365SDimitry Andric 
6527d523365SDimitry Andric   BDVState getResult() const { return currentResult; }
653ff0cc061SDimitry Andric 
654ff0cc061SDimitry Andric private:
6557d523365SDimitry Andric   BDVState currentResult;
656ff0cc061SDimitry Andric 
6577d523365SDimitry Andric   /// Perform a meet operation on two elements of the BDVState lattice.
6587d523365SDimitry Andric   static BDVState meet(BDVState LHS, BDVState RHS) {
6597d523365SDimitry Andric     assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
6607d523365SDimitry Andric            "math is wrong: meet does not commute!");
6617d523365SDimitry Andric     BDVState Result = pureMeet(LHS, RHS);
6627d523365SDimitry Andric     DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
6637d523365SDimitry Andric                  << " produced " << Result << "\n");
6647d523365SDimitry Andric     return Result;
665ff0cc061SDimitry Andric   }
666ff0cc061SDimitry Andric 
6677d523365SDimitry Andric   static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
668ff0cc061SDimitry Andric     switch (stateA.getStatus()) {
6697d523365SDimitry Andric     case BDVState::Unknown:
670ff0cc061SDimitry Andric       return stateB;
671ff0cc061SDimitry Andric 
6727d523365SDimitry Andric     case BDVState::Base:
673ff0cc061SDimitry Andric       assert(stateA.getBase() && "can't be null");
674ff0cc061SDimitry Andric       if (stateB.isUnknown())
675ff0cc061SDimitry Andric         return stateA;
676ff0cc061SDimitry Andric 
677ff0cc061SDimitry Andric       if (stateB.isBase()) {
678ff0cc061SDimitry Andric         if (stateA.getBase() == stateB.getBase()) {
679ff0cc061SDimitry Andric           assert(stateA == stateB && "equality broken!");
680ff0cc061SDimitry Andric           return stateA;
681ff0cc061SDimitry Andric         }
6827d523365SDimitry Andric         return BDVState(BDVState::Conflict);
683ff0cc061SDimitry Andric       }
684ff0cc061SDimitry Andric       assert(stateB.isConflict() && "only three states!");
6857d523365SDimitry Andric       return BDVState(BDVState::Conflict);
686ff0cc061SDimitry Andric 
6877d523365SDimitry Andric     case BDVState::Conflict:
688ff0cc061SDimitry Andric       return stateA;
689ff0cc061SDimitry Andric     }
690ff0cc061SDimitry Andric     llvm_unreachable("only three states!");
691ff0cc061SDimitry Andric   }
692ff0cc061SDimitry Andric };
6933dac3a9bSDimitry Andric }
6947d523365SDimitry Andric 
6957d523365SDimitry Andric 
696ff0cc061SDimitry Andric /// For a given value or instruction, figure out what base ptr it's derived
697ff0cc061SDimitry Andric /// from.  For gc objects, this is simply itself.  On success, returns a value
698ff0cc061SDimitry Andric /// which is the base pointer.  (This is reliable and can be used for
699ff0cc061SDimitry Andric /// relocation.)  On failure, returns nullptr.
700ff0cc061SDimitry Andric static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
701ff0cc061SDimitry Andric   Value *def = findBaseOrBDV(I, cache);
702ff0cc061SDimitry Andric 
703ff0cc061SDimitry Andric   if (isKnownBaseResult(def)) {
704ff0cc061SDimitry Andric     return def;
705ff0cc061SDimitry Andric   }
706ff0cc061SDimitry Andric 
707ff0cc061SDimitry Andric   // Here's the rough algorithm:
708ff0cc061SDimitry Andric   // - For every SSA value, construct a mapping to either an actual base
709ff0cc061SDimitry Andric   //   pointer or a PHI which obscures the base pointer.
710ff0cc061SDimitry Andric   // - Construct a mapping from PHI to unknown TOP state.  Use an
711ff0cc061SDimitry Andric   //   optimistic algorithm to propagate base pointer information.  Lattice
712ff0cc061SDimitry Andric   //   looks like:
713ff0cc061SDimitry Andric   //   UNKNOWN
714ff0cc061SDimitry Andric   //   b1 b2 b3 b4
715ff0cc061SDimitry Andric   //   CONFLICT
716ff0cc061SDimitry Andric   //   When algorithm terminates, all PHIs will either have a single concrete
717ff0cc061SDimitry Andric   //   base or be in a conflict state.
718ff0cc061SDimitry Andric   // - For every conflict, insert a dummy PHI node without arguments.  Add
719ff0cc061SDimitry Andric   //   these to the base[Instruction] = BasePtr mapping.  For every
720ff0cc061SDimitry Andric   //   non-conflict, add the actual base.
721ff0cc061SDimitry Andric   //  - For every conflict, add arguments for the base[a] of each input
722ff0cc061SDimitry Andric   //   arguments.
723ff0cc061SDimitry Andric   //
724ff0cc061SDimitry Andric   // Note: A simpler form of this would be to add the conflict form of all
725ff0cc061SDimitry Andric   // PHIs without running the optimistic algorithm.  This would be
7267d523365SDimitry Andric   // analogous to pessimistic data flow and would likely lead to an
727ff0cc061SDimitry Andric   // overall worse solution.
728ff0cc061SDimitry Andric 
7297d523365SDimitry Andric #ifndef NDEBUG
7307d523365SDimitry Andric   auto isExpectedBDVType = [](Value *BDV) {
7317d523365SDimitry Andric     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
7327d523365SDimitry Andric            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
7337d523365SDimitry Andric   };
7347d523365SDimitry Andric #endif
7357d523365SDimitry Andric 
7367d523365SDimitry Andric   // Once populated, will contain a mapping from each potentially non-base BDV
7377d523365SDimitry Andric   // to a lattice value (described above) which corresponds to that BDV.
7387d523365SDimitry Andric   // We use the order of insertion (DFS over the def/use graph) to provide a
7397d523365SDimitry Andric   // stable deterministic ordering for visiting DenseMaps (which are unordered)
7407d523365SDimitry Andric   // below.  This is important for deterministic compilation.
7417d523365SDimitry Andric   MapVector<Value *, BDVState> States;
7427d523365SDimitry Andric 
7437d523365SDimitry Andric   // Recursively fill in all base defining values reachable from the initial
7447d523365SDimitry Andric   // one for which we don't already know a definite base value for
7457d523365SDimitry Andric   /* scope */ {
7467d523365SDimitry Andric     SmallVector<Value*, 16> Worklist;
7477d523365SDimitry Andric     Worklist.push_back(def);
7487d523365SDimitry Andric     States.insert(std::make_pair(def, BDVState()));
7497d523365SDimitry Andric     while (!Worklist.empty()) {
7507d523365SDimitry Andric       Value *Current = Worklist.pop_back_val();
7517d523365SDimitry Andric       assert(!isKnownBaseResult(Current) && "why did it get added?");
7527d523365SDimitry Andric 
7537d523365SDimitry Andric       auto visitIncomingValue = [&](Value *InVal) {
7547d523365SDimitry Andric         Value *Base = findBaseOrBDV(InVal, cache);
7557d523365SDimitry Andric         if (isKnownBaseResult(Base))
7567d523365SDimitry Andric           // Known bases won't need new instructions introduced and can be
7577d523365SDimitry Andric           // ignored safely
7587d523365SDimitry Andric           return;
7597d523365SDimitry Andric         assert(isExpectedBDVType(Base) && "the only non-base values "
7607d523365SDimitry Andric                "we see should be base defining values");
7617d523365SDimitry Andric         if (States.insert(std::make_pair(Base, BDVState())).second)
7627d523365SDimitry Andric           Worklist.push_back(Base);
7637d523365SDimitry Andric       };
7647d523365SDimitry Andric       if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
7657d523365SDimitry Andric         for (Value *InVal : Phi->incoming_values())
7667d523365SDimitry Andric           visitIncomingValue(InVal);
7677d523365SDimitry Andric       } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
7687d523365SDimitry Andric         visitIncomingValue(Sel->getTrueValue());
7697d523365SDimitry Andric         visitIncomingValue(Sel->getFalseValue());
7707d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
7717d523365SDimitry Andric         visitIncomingValue(EE->getVectorOperand());
7727d523365SDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
7737d523365SDimitry Andric         visitIncomingValue(IE->getOperand(0)); // vector operand
7747d523365SDimitry Andric         visitIncomingValue(IE->getOperand(1)); // scalar operand
7757d523365SDimitry Andric       } else {
7767d523365SDimitry Andric         // There is one known class of instructions we know we don't handle.
7777d523365SDimitry Andric         assert(isa<ShuffleVectorInst>(Current));
7787d523365SDimitry Andric         llvm_unreachable("unimplemented instruction case");
779ff0cc061SDimitry Andric       }
780ff0cc061SDimitry Andric     }
781ff0cc061SDimitry Andric   }
782ff0cc061SDimitry Andric 
7837d523365SDimitry Andric #ifndef NDEBUG
7847d523365SDimitry Andric   DEBUG(dbgs() << "States after initialization:\n");
7857d523365SDimitry Andric   for (auto Pair : States) {
7867d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
787ff0cc061SDimitry Andric   }
7887d523365SDimitry Andric #endif
789ff0cc061SDimitry Andric 
7907d523365SDimitry Andric   // Return a phi state for a base defining value.  We'll generate a new
7917d523365SDimitry Andric   // base state for known bases and expect to find a cached state otherwise.
7927d523365SDimitry Andric   auto getStateForBDV = [&](Value *baseValue) {
7937d523365SDimitry Andric     if (isKnownBaseResult(baseValue))
7947d523365SDimitry Andric       return BDVState(baseValue);
7957d523365SDimitry Andric     auto I = States.find(baseValue);
7967d523365SDimitry Andric     assert(I != States.end() && "lookup failed!");
7977d523365SDimitry Andric     return I->second;
7987d523365SDimitry Andric   };
799ff0cc061SDimitry Andric 
800ff0cc061SDimitry Andric   bool progress = true;
801ff0cc061SDimitry Andric   while (progress) {
802ff0cc061SDimitry Andric #ifndef NDEBUG
8037d523365SDimitry Andric     const size_t oldSize = States.size();
804ff0cc061SDimitry Andric #endif
805ff0cc061SDimitry Andric     progress = false;
8067d523365SDimitry Andric     // We're only changing values in this loop, thus safe to keep iterators.
8077d523365SDimitry Andric     // Since this is computing a fixed point, the order of visit does not
8087d523365SDimitry Andric     // effect the result.  TODO: We could use a worklist here and make this run
8097d523365SDimitry Andric     // much faster.
8107d523365SDimitry Andric     for (auto Pair : States) {
8117d523365SDimitry Andric       Value *BDV = Pair.first;
8127d523365SDimitry Andric       assert(!isKnownBaseResult(BDV) && "why did it get added?");
813ff0cc061SDimitry Andric 
8147d523365SDimitry Andric       // Given an input value for the current instruction, return a BDVState
8157d523365SDimitry Andric       // instance which represents the BDV of that value.
8167d523365SDimitry Andric       auto getStateForInput = [&](Value *V) mutable {
8177d523365SDimitry Andric         Value *BDV = findBaseOrBDV(V, cache);
8187d523365SDimitry Andric         return getStateForBDV(BDV);
8197d523365SDimitry Andric       };
8207d523365SDimitry Andric 
8217d523365SDimitry Andric       MeetBDVStates calculateMeet;
8227d523365SDimitry Andric       if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
8237d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
8247d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
8257d523365SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
8267d523365SDimitry Andric         for (Value *Val : Phi->incoming_values())
8277d523365SDimitry Andric           calculateMeet.meetWith(getStateForInput(Val));
8287d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
8297d523365SDimitry Andric         // The 'meet' for an extractelement is slightly trivial, but it's still
8307d523365SDimitry Andric         // useful in that it drives us to conflict if our input is.
8317d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
8327d523365SDimitry Andric       } else {
8337d523365SDimitry Andric         // Given there's a inherent type mismatch between the operands, will
8347d523365SDimitry Andric         // *always* produce Conflict.
8357d523365SDimitry Andric         auto *IE = cast<InsertElementInst>(BDV);
8367d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
8377d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
8387d523365SDimitry Andric       }
8397d523365SDimitry Andric 
8407d523365SDimitry Andric       BDVState oldState = States[BDV];
8417d523365SDimitry Andric       BDVState newState = calculateMeet.getResult();
842ff0cc061SDimitry Andric       if (oldState != newState) {
843ff0cc061SDimitry Andric         progress = true;
8447d523365SDimitry Andric         States[BDV] = newState;
845ff0cc061SDimitry Andric       }
846ff0cc061SDimitry Andric     }
847ff0cc061SDimitry Andric 
8487d523365SDimitry Andric     assert(oldSize == States.size() &&
8497d523365SDimitry Andric            "fixed point shouldn't be adding any new nodes to state");
850ff0cc061SDimitry Andric   }
851ff0cc061SDimitry Andric 
8527d523365SDimitry Andric #ifndef NDEBUG
8537d523365SDimitry Andric   DEBUG(dbgs() << "States after meet iteration:\n");
8547d523365SDimitry Andric   for (auto Pair : States) {
8557d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
856ff0cc061SDimitry Andric   }
8577d523365SDimitry Andric #endif
858ff0cc061SDimitry Andric 
859ff0cc061SDimitry Andric   // Insert Phis for all conflicts
860ff0cc061SDimitry Andric   // TODO: adjust naming patterns to avoid this order of iteration dependency
8617d523365SDimitry Andric   for (auto Pair : States) {
8627d523365SDimitry Andric     Instruction *I = cast<Instruction>(Pair.first);
8637d523365SDimitry Andric     BDVState State = Pair.second;
8647d523365SDimitry Andric     assert(!isKnownBaseResult(I) && "why did it get added?");
8657d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
8667d523365SDimitry Andric 
8677d523365SDimitry Andric     // extractelement instructions are a bit special in that we may need to
8687d523365SDimitry Andric     // insert an extract even when we know an exact base for the instruction.
8697d523365SDimitry Andric     // The problem is that we need to convert from a vector base to a scalar
8707d523365SDimitry Andric     // base for the particular indice we're interested in.
8717d523365SDimitry Andric     if (State.isBase() && isa<ExtractElementInst>(I) &&
8727d523365SDimitry Andric         isa<VectorType>(State.getBase()->getType())) {
8737d523365SDimitry Andric       auto *EE = cast<ExtractElementInst>(I);
8747d523365SDimitry Andric       // TODO: In many cases, the new instruction is just EE itself.  We should
8757d523365SDimitry Andric       // exploit this, but can't do it here since it would break the invariant
8767d523365SDimitry Andric       // about the BDV not being known to be a base.
8777d523365SDimitry Andric       auto *BaseInst = ExtractElementInst::Create(State.getBase(),
8787d523365SDimitry Andric                                                   EE->getIndexOperand(),
8797d523365SDimitry Andric                                                   "base_ee", EE);
8807d523365SDimitry Andric       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
8817d523365SDimitry Andric       States[I] = BDVState(BDVState::Base, BaseInst);
8827d523365SDimitry Andric     }
8837d523365SDimitry Andric 
8847d523365SDimitry Andric     // Since we're joining a vector and scalar base, they can never be the
8857d523365SDimitry Andric     // same.  As a result, we should always see insert element having reached
8867d523365SDimitry Andric     // the conflict state.
8877d523365SDimitry Andric     if (isa<InsertElementInst>(I)) {
8887d523365SDimitry Andric       assert(State.isConflict());
8897d523365SDimitry Andric     }
8907d523365SDimitry Andric 
8917d523365SDimitry Andric     if (!State.isConflict())
892ff0cc061SDimitry Andric       continue;
893ff0cc061SDimitry Andric 
8947d523365SDimitry Andric     /// Create and insert a new instruction which will represent the base of
8957d523365SDimitry Andric     /// the given instruction 'I'.
8967d523365SDimitry Andric     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
8977d523365SDimitry Andric       if (isa<PHINode>(I)) {
8987d523365SDimitry Andric         BasicBlock *BB = I->getParent();
8997d523365SDimitry Andric         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
9007d523365SDimitry Andric         assert(NumPreds > 0 && "how did we reach here");
9017d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_phi");
9027d523365SDimitry Andric         return PHINode::Create(I->getType(), NumPreds, Name, I);
9037d523365SDimitry Andric       } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
904ff0cc061SDimitry Andric         // The undef will be replaced later
9057d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(Sel->getType());
9067d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_select");
9077d523365SDimitry Andric         return SelectInst::Create(Sel->getCondition(), Undef,
9087d523365SDimitry Andric                                   Undef, Name, Sel);
9097d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
9107d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
9117d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ee");
9127d523365SDimitry Andric         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
9137d523365SDimitry Andric                                           EE);
9147d523365SDimitry Andric       } else {
9157d523365SDimitry Andric         auto *IE = cast<InsertElementInst>(I);
9167d523365SDimitry Andric         UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
9177d523365SDimitry Andric         UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
9187d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ie");
9197d523365SDimitry Andric         return InsertElementInst::Create(VecUndef, ScalarUndef,
9207d523365SDimitry Andric                                          IE->getOperand(2), Name, IE);
9217d523365SDimitry Andric       }
9227d523365SDimitry Andric 
9237d523365SDimitry Andric     };
9247d523365SDimitry Andric     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
925ff0cc061SDimitry Andric     // Add metadata marking this as a base value
9267d523365SDimitry Andric     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
9277d523365SDimitry Andric     States[I] = BDVState(BDVState::Conflict, BaseInst);
928ff0cc061SDimitry Andric   }
929ff0cc061SDimitry Andric 
9307d523365SDimitry Andric   // Returns a instruction which produces the base pointer for a given
9317d523365SDimitry Andric   // instruction.  The instruction is assumed to be an input to one of the BDVs
9327d523365SDimitry Andric   // seen in the inference algorithm above.  As such, we must either already
9337d523365SDimitry Andric   // know it's base defining value is a base, or have inserted a new
9347d523365SDimitry Andric   // instruction to propagate the base of it's BDV and have entered that newly
9357d523365SDimitry Andric   // introduced instruction into the state table.  In either case, we are
9367d523365SDimitry Andric   // assured to be able to determine an instruction which produces it's base
9377d523365SDimitry Andric   // pointer.
9387d523365SDimitry Andric   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
9397d523365SDimitry Andric     Value *BDV = findBaseOrBDV(Input, cache);
9407d523365SDimitry Andric     Value *Base = nullptr;
9417d523365SDimitry Andric     if (isKnownBaseResult(BDV)) {
9427d523365SDimitry Andric       Base = BDV;
9437d523365SDimitry Andric     } else {
9447d523365SDimitry Andric       // Either conflict or base.
9457d523365SDimitry Andric       assert(States.count(BDV));
9467d523365SDimitry Andric       Base = States[BDV].getBase();
9477d523365SDimitry Andric     }
9487d523365SDimitry Andric     assert(Base && "can't be null");
9497d523365SDimitry Andric     // The cast is needed since base traversal may strip away bitcasts
9507d523365SDimitry Andric     if (Base->getType() != Input->getType() &&
9517d523365SDimitry Andric         InsertPt) {
9527d523365SDimitry Andric       Base = new BitCastInst(Base, Input->getType(), "cast",
9537d523365SDimitry Andric                              InsertPt);
9547d523365SDimitry Andric     }
9557d523365SDimitry Andric     return Base;
9567d523365SDimitry Andric   };
957ff0cc061SDimitry Andric 
9587d523365SDimitry Andric   // Fixup all the inputs of the new PHIs.  Visit order needs to be
9597d523365SDimitry Andric   // deterministic and predictable because we're naming newly created
9607d523365SDimitry Andric   // instructions.
9617d523365SDimitry Andric   for (auto Pair : States) {
9627d523365SDimitry Andric     Instruction *BDV = cast<Instruction>(Pair.first);
9637d523365SDimitry Andric     BDVState State = Pair.second;
9647d523365SDimitry Andric 
9657d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
9667d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
9677d523365SDimitry Andric     if (!State.isConflict())
968ff0cc061SDimitry Andric       continue;
969ff0cc061SDimitry Andric 
9707d523365SDimitry Andric     if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
9717d523365SDimitry Andric       PHINode *phi = cast<PHINode>(BDV);
972ff0cc061SDimitry Andric       unsigned NumPHIValues = phi->getNumIncomingValues();
973ff0cc061SDimitry Andric       for (unsigned i = 0; i < NumPHIValues; i++) {
974ff0cc061SDimitry Andric         Value *InVal = phi->getIncomingValue(i);
975ff0cc061SDimitry Andric         BasicBlock *InBB = phi->getIncomingBlock(i);
976ff0cc061SDimitry Andric 
977ff0cc061SDimitry Andric         // If we've already seen InBB, add the same incoming value
978ff0cc061SDimitry Andric         // we added for it earlier.  The IR verifier requires phi
979ff0cc061SDimitry Andric         // nodes with multiple entries from the same basic block
980ff0cc061SDimitry Andric         // to have the same incoming value for each of those
981ff0cc061SDimitry Andric         // entries.  If we don't do this check here and basephi
982ff0cc061SDimitry Andric         // has a different type than base, we'll end up adding two
983ff0cc061SDimitry Andric         // bitcasts (and hence two distinct values) as incoming
984ff0cc061SDimitry Andric         // values for the same basic block.
985ff0cc061SDimitry Andric 
986ff0cc061SDimitry Andric         int blockIndex = basephi->getBasicBlockIndex(InBB);
987ff0cc061SDimitry Andric         if (blockIndex != -1) {
988ff0cc061SDimitry Andric           Value *oldBase = basephi->getIncomingValue(blockIndex);
989ff0cc061SDimitry Andric           basephi->addIncoming(oldBase, InBB);
990ff0cc061SDimitry Andric 
9917d523365SDimitry Andric #ifndef NDEBUG
9927d523365SDimitry Andric           Value *Base = getBaseForInput(InVal, nullptr);
9937d523365SDimitry Andric           // In essence this assert states: the only way two
994ff0cc061SDimitry Andric           // values incoming from the same basic block may be
995ff0cc061SDimitry Andric           // different is by being different bitcasts of the same
996ff0cc061SDimitry Andric           // value.  A cleanup that remains TODO is changing
997ff0cc061SDimitry Andric           // findBaseOrBDV to return an llvm::Value of the correct
998ff0cc061SDimitry Andric           // type (and still remain pure).  This will remove the
999ff0cc061SDimitry Andric           // need to add bitcasts.
10007d523365SDimitry Andric           assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
1001ff0cc061SDimitry Andric                  "sanity -- findBaseOrBDV should be pure!");
1002ff0cc061SDimitry Andric #endif
1003ff0cc061SDimitry Andric           continue;
1004ff0cc061SDimitry Andric         }
1005ff0cc061SDimitry Andric 
10067d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
10077d523365SDimitry Andric         // need to insert a bitcast in the incoming block.
10087d523365SDimitry Andric         // TODO: Need to split critical edges if insertion is needed
10097d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
10107d523365SDimitry Andric         basephi->addIncoming(Base, InBB);
1011ff0cc061SDimitry Andric       }
1012ff0cc061SDimitry Andric       assert(basephi->getNumIncomingValues() == NumPHIValues);
10137d523365SDimitry Andric     } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
10147d523365SDimitry Andric       SelectInst *Sel = cast<SelectInst>(BDV);
1015ff0cc061SDimitry Andric       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1016ff0cc061SDimitry Andric       // something more safe and less hacky.
1017ff0cc061SDimitry Andric       for (int i = 1; i <= 2; i++) {
10187d523365SDimitry Andric         Value *InVal = Sel->getOperand(i);
10197d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
10207d523365SDimitry Andric         // need to insert a bitcast.
10217d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseSel);
10227d523365SDimitry Andric         BaseSel->setOperand(i, Base);
1023ff0cc061SDimitry Andric       }
10247d523365SDimitry Andric     } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
10257d523365SDimitry Andric       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
10267d523365SDimitry Andric       // Find the instruction which produces the base for each input.  We may
10277d523365SDimitry Andric       // need to insert a bitcast.
10287d523365SDimitry Andric       Value *Base = getBaseForInput(InVal, BaseEE);
10297d523365SDimitry Andric       BaseEE->setOperand(0, Base);
10307d523365SDimitry Andric     } else {
10317d523365SDimitry Andric       auto *BaseIE = cast<InsertElementInst>(State.getBase());
10327d523365SDimitry Andric       auto *BdvIE = cast<InsertElementInst>(BDV);
10337d523365SDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
10347d523365SDimitry Andric         Value *InVal = BdvIE->getOperand(OperandIdx);
10357d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseIE);
10367d523365SDimitry Andric         BaseIE->setOperand(OperandIdx, Base);
10377d523365SDimitry Andric       };
10387d523365SDimitry Andric       UpdateOperand(0); // vector operand
10397d523365SDimitry Andric       UpdateOperand(1); // scalar operand
1040ff0cc061SDimitry Andric     }
10417d523365SDimitry Andric 
1042ff0cc061SDimitry Andric   }
10437d523365SDimitry Andric 
10447d523365SDimitry Andric   // Now that we're done with the algorithm, see if we can optimize the
10457d523365SDimitry Andric   // results slightly by reducing the number of new instructions needed.
10467d523365SDimitry Andric   // Arguably, this should be integrated into the algorithm above, but
10477d523365SDimitry Andric   // doing as a post process step is easier to reason about for the moment.
10487d523365SDimitry Andric   DenseMap<Value *, Value *> ReverseMap;
10497d523365SDimitry Andric   SmallPtrSet<Instruction *, 16> NewInsts;
10507d523365SDimitry Andric   SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
10517d523365SDimitry Andric   // Note: We need to visit the states in a deterministic order.  We uses the
10527d523365SDimitry Andric   // Keys we sorted above for this purpose.  Note that we are papering over a
10537d523365SDimitry Andric   // bigger problem with the algorithm above - it's visit order is not
10547d523365SDimitry Andric   // deterministic.  A larger change is needed to fix this.
10557d523365SDimitry Andric   for (auto Pair : States) {
10567d523365SDimitry Andric     auto *BDV = Pair.first;
10577d523365SDimitry Andric     auto State = Pair.second;
10587d523365SDimitry Andric     Value *Base = State.getBase();
10597d523365SDimitry Andric     assert(BDV && Base);
10607d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
10617d523365SDimitry Andric     assert(isKnownBaseResult(Base) &&
10627d523365SDimitry Andric            "must be something we 'know' is a base pointer");
10637d523365SDimitry Andric     if (!State.isConflict())
10647d523365SDimitry Andric       continue;
10657d523365SDimitry Andric 
10667d523365SDimitry Andric     ReverseMap[Base] = BDV;
10677d523365SDimitry Andric     if (auto *BaseI = dyn_cast<Instruction>(Base)) {
10687d523365SDimitry Andric       NewInsts.insert(BaseI);
10697d523365SDimitry Andric       Worklist.insert(BaseI);
10707d523365SDimitry Andric     }
10717d523365SDimitry Andric   }
10727d523365SDimitry Andric   auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
10737d523365SDimitry Andric                                  Value *Replacement) {
10747d523365SDimitry Andric     // Add users which are new instructions (excluding self references)
10757d523365SDimitry Andric     for (User *U : BaseI->users())
10767d523365SDimitry Andric       if (auto *UI = dyn_cast<Instruction>(U))
10777d523365SDimitry Andric         if (NewInsts.count(UI) && UI != BaseI)
10787d523365SDimitry Andric           Worklist.insert(UI);
10797d523365SDimitry Andric     // Then do the actual replacement
10807d523365SDimitry Andric     NewInsts.erase(BaseI);
10817d523365SDimitry Andric     ReverseMap.erase(BaseI);
10827d523365SDimitry Andric     BaseI->replaceAllUsesWith(Replacement);
10837d523365SDimitry Andric     assert(States.count(BDV));
10847d523365SDimitry Andric     assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
10857d523365SDimitry Andric     States[BDV] = BDVState(BDVState::Conflict, Replacement);
10867d523365SDimitry Andric     BaseI->eraseFromParent();
10877d523365SDimitry Andric   };
10887d523365SDimitry Andric   const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
10897d523365SDimitry Andric   while (!Worklist.empty()) {
10907d523365SDimitry Andric     Instruction *BaseI = Worklist.pop_back_val();
10917d523365SDimitry Andric     assert(NewInsts.count(BaseI));
10927d523365SDimitry Andric     Value *Bdv = ReverseMap[BaseI];
10937d523365SDimitry Andric     if (auto *BdvI = dyn_cast<Instruction>(Bdv))
10947d523365SDimitry Andric       if (BaseI->isIdenticalTo(BdvI)) {
10957d523365SDimitry Andric         DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
10967d523365SDimitry Andric         ReplaceBaseInstWith(Bdv, BaseI, Bdv);
10977d523365SDimitry Andric         continue;
10987d523365SDimitry Andric       }
10997d523365SDimitry Andric     if (Value *V = SimplifyInstruction(BaseI, DL)) {
11007d523365SDimitry Andric       DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
11017d523365SDimitry Andric       ReplaceBaseInstWith(Bdv, BaseI, V);
11027d523365SDimitry Andric       continue;
1103ff0cc061SDimitry Andric     }
1104ff0cc061SDimitry Andric   }
1105ff0cc061SDimitry Andric 
1106ff0cc061SDimitry Andric   // Cache all of our results so we can cheaply reuse them
1107ff0cc061SDimitry Andric   // NOTE: This is actually two caches: one of the base defining value
1108ff0cc061SDimitry Andric   // relation and one of the base pointer relation!  FIXME
11097d523365SDimitry Andric   for (auto Pair : States) {
11107d523365SDimitry Andric     auto *BDV = Pair.first;
11117d523365SDimitry Andric     Value *base = Pair.second.getBase();
11127d523365SDimitry Andric     assert(BDV && base);
1113ff0cc061SDimitry Andric 
11147d523365SDimitry Andric     std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
11157d523365SDimitry Andric     DEBUG(dbgs() << "Updating base value cache"
11167d523365SDimitry Andric           << " for: " << BDV->getName()
1117ff0cc061SDimitry Andric           << " from: " << fromstr
11187d523365SDimitry Andric           << " to: " << base->getName() << "\n");
1119ff0cc061SDimitry Andric 
11207d523365SDimitry Andric     if (cache.count(BDV)) {
1121ff0cc061SDimitry Andric       // Once we transition from the BDV relation being store in the cache to
1122ff0cc061SDimitry Andric       // the base relation being stored, it must be stable
11237d523365SDimitry Andric       assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
1124ff0cc061SDimitry Andric              "base relation should be stable");
1125ff0cc061SDimitry Andric     }
11267d523365SDimitry Andric     cache[BDV] = base;
1127ff0cc061SDimitry Andric   }
11287d523365SDimitry Andric   assert(cache.count(def));
1129ff0cc061SDimitry Andric   return cache[def];
1130ff0cc061SDimitry Andric }
1131ff0cc061SDimitry Andric 
1132ff0cc061SDimitry Andric // For a set of live pointers (base and/or derived), identify the base
1133ff0cc061SDimitry Andric // pointer of the object which they are derived from.  This routine will
1134ff0cc061SDimitry Andric // mutate the IR graph as needed to make the 'base' pointer live at the
1135ff0cc061SDimitry Andric // definition site of 'derived'.  This ensures that any use of 'derived' can
1136ff0cc061SDimitry Andric // also use 'base'.  This may involve the insertion of a number of
1137ff0cc061SDimitry Andric // additional PHI nodes.
1138ff0cc061SDimitry Andric //
1139ff0cc061SDimitry Andric // preconditions: live is a set of pointer type Values
1140ff0cc061SDimitry Andric //
1141ff0cc061SDimitry Andric // side effects: may insert PHI nodes into the existing CFG, will preserve
1142ff0cc061SDimitry Andric // CFG, will not remove or mutate any existing nodes
1143ff0cc061SDimitry Andric //
1144ff0cc061SDimitry Andric // post condition: PointerToBase contains one (derived, base) pair for every
1145ff0cc061SDimitry Andric // pointer in live.  Note that derived can be equal to base if the original
1146ff0cc061SDimitry Andric // pointer was a base pointer.
1147ff0cc061SDimitry Andric static void
1148ff0cc061SDimitry Andric findBasePointers(const StatepointLiveSetTy &live,
11497d523365SDimitry Andric                  DenseMap<Value *, Value *> &PointerToBase,
1150ff0cc061SDimitry Andric                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
1151ff0cc061SDimitry Andric   // For the naming of values inserted to be deterministic - which makes for
1152ff0cc061SDimitry Andric   // much cleaner and more stable tests - we need to assign an order to the
1153ff0cc061SDimitry Andric   // live values.  DenseSets do not provide a deterministic order across runs.
1154ff0cc061SDimitry Andric   SmallVector<Value *, 64> Temp;
1155ff0cc061SDimitry Andric   Temp.insert(Temp.end(), live.begin(), live.end());
1156ff0cc061SDimitry Andric   std::sort(Temp.begin(), Temp.end(), order_by_name);
1157ff0cc061SDimitry Andric   for (Value *ptr : Temp) {
1158ff0cc061SDimitry Andric     Value *base = findBasePointer(ptr, DVCache);
1159ff0cc061SDimitry Andric     assert(base && "failed to find base pointer");
1160ff0cc061SDimitry Andric     PointerToBase[ptr] = base;
1161ff0cc061SDimitry Andric     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1162ff0cc061SDimitry Andric             DT->dominates(cast<Instruction>(base)->getParent(),
1163ff0cc061SDimitry Andric                           cast<Instruction>(ptr)->getParent())) &&
1164ff0cc061SDimitry Andric            "The base we found better dominate the derived pointer");
1165ff0cc061SDimitry Andric 
1166ff0cc061SDimitry Andric     // If you see this trip and like to live really dangerously, the code should
1167ff0cc061SDimitry Andric     // be correct, just with idioms the verifier can't handle.  You can try
11687d523365SDimitry Andric     // disabling the verifier at your own substantial risk.
1169ff0cc061SDimitry Andric     assert(!isa<ConstantPointerNull>(base) &&
1170ff0cc061SDimitry Andric            "the relocation code needs adjustment to handle the relocation of "
1171ff0cc061SDimitry Andric            "a null pointer constant without causing false positives in the "
1172ff0cc061SDimitry Andric            "safepoint ir verifier.");
1173ff0cc061SDimitry Andric   }
1174ff0cc061SDimitry Andric }
1175ff0cc061SDimitry Andric 
1176ff0cc061SDimitry Andric /// Find the required based pointers (and adjust the live set) for the given
1177ff0cc061SDimitry Andric /// parse point.
1178ff0cc061SDimitry Andric static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1179ff0cc061SDimitry Andric                              const CallSite &CS,
1180ff0cc061SDimitry Andric                              PartiallyConstructedSafepointRecord &result) {
11817d523365SDimitry Andric   DenseMap<Value *, Value *> PointerToBase;
11827d523365SDimitry Andric   findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1183ff0cc061SDimitry Andric 
1184ff0cc061SDimitry Andric   if (PrintBasePointers) {
1185ff0cc061SDimitry Andric     // Note: Need to print these in a stable order since this is checked in
1186ff0cc061SDimitry Andric     // some tests.
1187ff0cc061SDimitry Andric     errs() << "Base Pairs (w/o Relocation):\n";
1188ff0cc061SDimitry Andric     SmallVector<Value *, 64> Temp;
1189ff0cc061SDimitry Andric     Temp.reserve(PointerToBase.size());
1190ff0cc061SDimitry Andric     for (auto Pair : PointerToBase) {
1191ff0cc061SDimitry Andric       Temp.push_back(Pair.first);
1192ff0cc061SDimitry Andric     }
1193ff0cc061SDimitry Andric     std::sort(Temp.begin(), Temp.end(), order_by_name);
1194ff0cc061SDimitry Andric     for (Value *Ptr : Temp) {
1195ff0cc061SDimitry Andric       Value *Base = PointerToBase[Ptr];
11967d523365SDimitry Andric       errs() << " derived ";
11977d523365SDimitry Andric       Ptr->printAsOperand(errs(), false);
11987d523365SDimitry Andric       errs() << " base ";
11997d523365SDimitry Andric       Base->printAsOperand(errs(), false);
12007d523365SDimitry Andric       errs() << "\n";;
1201ff0cc061SDimitry Andric     }
1202ff0cc061SDimitry Andric   }
1203ff0cc061SDimitry Andric 
1204ff0cc061SDimitry Andric   result.PointerToBase = PointerToBase;
1205ff0cc061SDimitry Andric }
1206ff0cc061SDimitry Andric 
1207ff0cc061SDimitry Andric /// Given an updated version of the dataflow liveness results, update the
1208ff0cc061SDimitry Andric /// liveset and base pointer maps for the call site CS.
1209ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1210ff0cc061SDimitry Andric                                   const CallSite &CS,
1211ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &result);
1212ff0cc061SDimitry Andric 
1213ff0cc061SDimitry Andric static void recomputeLiveInValues(
12147d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1215ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1216ff0cc061SDimitry Andric   // TODO-PERF: reuse the original liveness, then simply run the dataflow
12177d523365SDimitry Andric   // again.  The old values are still live and will help it stabilize quickly.
1218ff0cc061SDimitry Andric   GCPtrLivenessData RevisedLivenessData;
1219ff0cc061SDimitry Andric   computeLiveInValues(DT, F, RevisedLivenessData);
1220ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1221ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1222ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1223ff0cc061SDimitry Andric     recomputeLiveInValues(RevisedLivenessData, CS, info);
1224ff0cc061SDimitry Andric   }
1225ff0cc061SDimitry Andric }
1226ff0cc061SDimitry Andric 
12277d523365SDimitry Andric // When inserting gc.relocate and gc.result calls, we need to ensure there are
12287d523365SDimitry Andric // no uses of the original value / return value between the gc.statepoint and
12297d523365SDimitry Andric // the gc.relocate / gc.result call.  One case which can arise is a phi node
12307d523365SDimitry Andric // starting one of the successor blocks.  We also need to be able to insert the
12317d523365SDimitry Andric // gc.relocates only on the path which goes through the statepoint.  We might
12327d523365SDimitry Andric // need to split an edge to make this possible.
1233ff0cc061SDimitry Andric static BasicBlock *
123497bc6c73SDimitry Andric normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
123597bc6c73SDimitry Andric                             DominatorTree &DT) {
1236ff0cc061SDimitry Andric   BasicBlock *Ret = BB;
12377d523365SDimitry Andric   if (!BB->getUniquePredecessor())
12387d523365SDimitry Andric     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1239ff0cc061SDimitry Andric 
12407d523365SDimitry Andric   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1241ff0cc061SDimitry Andric   // from it
1242ff0cc061SDimitry Andric   FoldSingleEntryPHINodes(Ret);
12437d523365SDimitry Andric   assert(!isa<PHINode>(Ret->begin()) &&
12447d523365SDimitry Andric          "All PHI nodes should have been removed!");
1245ff0cc061SDimitry Andric 
12467d523365SDimitry Andric   // At this point, we can safely insert a gc.relocate or gc.result as the first
12477d523365SDimitry Andric   // instruction in Ret if needed.
1248ff0cc061SDimitry Andric   return Ret;
1249ff0cc061SDimitry Andric }
1250ff0cc061SDimitry Andric 
12517d523365SDimitry Andric // Create new attribute set containing only attributes which can be transferred
1252ff0cc061SDimitry Andric // from original call to the safepoint.
1253ff0cc061SDimitry Andric static AttributeSet legalizeCallAttributes(AttributeSet AS) {
12547d523365SDimitry Andric   AttributeSet Ret;
1255ff0cc061SDimitry Andric 
1256ff0cc061SDimitry Andric   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
12577d523365SDimitry Andric     unsigned Index = AS.getSlotIndex(Slot);
1258ff0cc061SDimitry Andric 
12597d523365SDimitry Andric     if (Index == AttributeSet::ReturnIndex ||
12607d523365SDimitry Andric         Index == AttributeSet::FunctionIndex) {
1261ff0cc061SDimitry Andric 
12627d523365SDimitry Andric       for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
1263ff0cc061SDimitry Andric 
1264ff0cc061SDimitry Andric         // Do not allow certain attributes - just skip them
1265ff0cc061SDimitry Andric         // Safepoint can not be read only or read none.
12667d523365SDimitry Andric         if (Attr.hasAttribute(Attribute::ReadNone) ||
12677d523365SDimitry Andric             Attr.hasAttribute(Attribute::ReadOnly))
1268ff0cc061SDimitry Andric           continue;
1269ff0cc061SDimitry Andric 
12707d523365SDimitry Andric         // These attributes control the generation of the gc.statepoint call /
12717d523365SDimitry Andric         // invoke itself; and once the gc.statepoint is in place, they're of no
12727d523365SDimitry Andric         // use.
12737d523365SDimitry Andric         if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
12747d523365SDimitry Andric             Attr.hasAttribute("statepoint-id"))
12757d523365SDimitry Andric           continue;
12767d523365SDimitry Andric 
12777d523365SDimitry Andric         Ret = Ret.addAttributes(
12787d523365SDimitry Andric             AS.getContext(), Index,
12797d523365SDimitry Andric             AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
1280ff0cc061SDimitry Andric       }
1281ff0cc061SDimitry Andric     }
1282ff0cc061SDimitry Andric 
1283ff0cc061SDimitry Andric     // Just skip parameter attributes for now
1284ff0cc061SDimitry Andric   }
1285ff0cc061SDimitry Andric 
12867d523365SDimitry Andric   return Ret;
1287ff0cc061SDimitry Andric }
1288ff0cc061SDimitry Andric 
1289ff0cc061SDimitry Andric /// Helper function to place all gc relocates necessary for the given
1290ff0cc061SDimitry Andric /// statepoint.
1291ff0cc061SDimitry Andric /// Inputs:
1292ff0cc061SDimitry Andric ///   liveVariables - list of variables to be relocated.
1293ff0cc061SDimitry Andric ///   liveStart - index of the first live variable.
1294ff0cc061SDimitry Andric ///   basePtrs - base pointers.
1295ff0cc061SDimitry Andric ///   statepointToken - statepoint instruction to which relocates should be
1296ff0cc061SDimitry Andric ///   bound.
1297ff0cc061SDimitry Andric ///   Builder - Llvm IR builder to be used to construct new calls.
12987d523365SDimitry Andric static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1299ff0cc061SDimitry Andric                               const int LiveStart,
13007d523365SDimitry Andric                               ArrayRef<Value *> BasePtrs,
1301ff0cc061SDimitry Andric                               Instruction *StatepointToken,
1302ff0cc061SDimitry Andric                               IRBuilder<> Builder) {
13037d523365SDimitry Andric   if (LiveVariables.empty())
13047d523365SDimitry Andric     return;
1305ff0cc061SDimitry Andric 
13067d523365SDimitry Andric   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
13077d523365SDimitry Andric     auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
13087d523365SDimitry Andric     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
13097d523365SDimitry Andric     size_t Index = std::distance(LiveVec.begin(), ValIt);
13107d523365SDimitry Andric     assert(Index < LiveVec.size() && "Bug in std::find?");
13117d523365SDimitry Andric     return Index;
13127d523365SDimitry Andric   };
13137d523365SDimitry Andric 
13147d523365SDimitry Andric   // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
13157d523365SDimitry Andric   // unique declarations for each pointer type, but this proved problematic
13167d523365SDimitry Andric   // because the intrinsic mangling code is incomplete and fragile.  Since
13177d523365SDimitry Andric   // we're moving towards a single unified pointer type anyways, we can just
13187d523365SDimitry Andric   // cast everything to an i8* of the right address space.  A bitcast is added
13197d523365SDimitry Andric   // later to convert gc_relocate to the actual value's type.
13207d523365SDimitry Andric   Module *M = StatepointToken->getModule();
13217d523365SDimitry Andric   auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
13227d523365SDimitry Andric   Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
13237d523365SDimitry Andric   Value *GCRelocateDecl =
13247d523365SDimitry Andric     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1325ff0cc061SDimitry Andric 
1326ff0cc061SDimitry Andric   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1327ff0cc061SDimitry Andric     // Generate the gc.relocate call and save the result
1328ff0cc061SDimitry Andric     Value *BaseIdx =
13297d523365SDimitry Andric       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
13307d523365SDimitry Andric     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1331ff0cc061SDimitry Andric 
1332ff0cc061SDimitry Andric     // only specify a debug name if we can give a useful one
13337d523365SDimitry Andric     CallInst *Reloc = Builder.CreateCall(
1334ff0cc061SDimitry Andric         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
13357d523365SDimitry Andric         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1336ff0cc061SDimitry Andric     // Trick CodeGen into thinking there are lots of free registers at this
1337ff0cc061SDimitry Andric     // fake call.
13387d523365SDimitry Andric     Reloc->setCallingConv(CallingConv::Cold);
1339ff0cc061SDimitry Andric   }
13407d523365SDimitry Andric }
13417d523365SDimitry Andric 
13427d523365SDimitry Andric namespace {
13437d523365SDimitry Andric 
13447d523365SDimitry Andric /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
13457d523365SDimitry Andric /// avoids having to worry about keeping around dangling pointers to Values.
13467d523365SDimitry Andric class DeferredReplacement {
13477d523365SDimitry Andric   AssertingVH<Instruction> Old;
13487d523365SDimitry Andric   AssertingVH<Instruction> New;
13497d523365SDimitry Andric 
13507d523365SDimitry Andric public:
13517d523365SDimitry Andric   explicit DeferredReplacement(Instruction *Old, Instruction *New) :
13527d523365SDimitry Andric     Old(Old), New(New) {
13537d523365SDimitry Andric     assert(Old != New && "Not allowed!");
13547d523365SDimitry Andric   }
13557d523365SDimitry Andric 
13567d523365SDimitry Andric   /// Does the task represented by this instance.
13577d523365SDimitry Andric   void doReplacement() {
13587d523365SDimitry Andric     Instruction *OldI = Old;
13597d523365SDimitry Andric     Instruction *NewI = New;
13607d523365SDimitry Andric 
13617d523365SDimitry Andric     assert(OldI != NewI && "Disallowed at construction?!");
13627d523365SDimitry Andric 
13637d523365SDimitry Andric     Old = nullptr;
13647d523365SDimitry Andric     New = nullptr;
13657d523365SDimitry Andric 
13667d523365SDimitry Andric     if (NewI)
13677d523365SDimitry Andric       OldI->replaceAllUsesWith(NewI);
13687d523365SDimitry Andric     OldI->eraseFromParent();
13697d523365SDimitry Andric   }
13707d523365SDimitry Andric };
1371ff0cc061SDimitry Andric }
1372ff0cc061SDimitry Andric 
1373ff0cc061SDimitry Andric static void
13747d523365SDimitry Andric makeStatepointExplicitImpl(const CallSite CS, /* to replace */
13757d523365SDimitry Andric                            const SmallVectorImpl<Value *> &BasePtrs,
13767d523365SDimitry Andric                            const SmallVectorImpl<Value *> &LiveVariables,
13777d523365SDimitry Andric                            PartiallyConstructedSafepointRecord &Result,
13787d523365SDimitry Andric                            std::vector<DeferredReplacement> &Replacements) {
13797d523365SDimitry Andric   assert(BasePtrs.size() == LiveVariables.size());
13807d523365SDimitry Andric   assert((UseDeoptBundles || isStatepoint(CS)) &&
1381ff0cc061SDimitry Andric          "This method expects to be rewriting a statepoint");
1382ff0cc061SDimitry Andric 
1383ff0cc061SDimitry Andric   // Then go ahead and use the builder do actually do the inserts.  We insert
1384ff0cc061SDimitry Andric   // immediately before the previous instruction under the assumption that all
1385ff0cc061SDimitry Andric   // arguments will be available here.  We can't insert afterwards since we may
1386ff0cc061SDimitry Andric   // be replacing a terminator.
13877d523365SDimitry Andric   Instruction *InsertBefore = CS.getInstruction();
13887d523365SDimitry Andric   IRBuilder<> Builder(InsertBefore);
1389ff0cc061SDimitry Andric 
13907d523365SDimitry Andric   ArrayRef<Value *> GCArgs(LiveVariables);
13917d523365SDimitry Andric   uint64_t StatepointID = 0xABCDEF00;
13927d523365SDimitry Andric   uint32_t NumPatchBytes = 0;
13937d523365SDimitry Andric   uint32_t Flags = uint32_t(StatepointFlags::None);
13947d523365SDimitry Andric 
13957d523365SDimitry Andric   ArrayRef<Use> CallArgs;
13967d523365SDimitry Andric   ArrayRef<Use> DeoptArgs;
13977d523365SDimitry Andric   ArrayRef<Use> TransitionArgs;
13987d523365SDimitry Andric 
13997d523365SDimitry Andric   Value *CallTarget = nullptr;
14007d523365SDimitry Andric 
14017d523365SDimitry Andric   if (UseDeoptBundles) {
14027d523365SDimitry Andric     CallArgs = {CS.arg_begin(), CS.arg_end()};
14037d523365SDimitry Andric     DeoptArgs = GetDeoptBundleOperands(CS);
14047d523365SDimitry Andric     // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
14057d523365SDimitry Andric     // could have an operand bundle for that too.
14067d523365SDimitry Andric     AttributeSet OriginalAttrs = CS.getAttributes();
14077d523365SDimitry Andric 
14087d523365SDimitry Andric     Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
14097d523365SDimitry Andric                                                   "statepoint-id");
14107d523365SDimitry Andric     if (AttrID.isStringAttribute())
14117d523365SDimitry Andric       AttrID.getValueAsString().getAsInteger(10, StatepointID);
14127d523365SDimitry Andric 
14137d523365SDimitry Andric     Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
14147d523365SDimitry Andric         AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
14157d523365SDimitry Andric     if (AttrNumPatchBytes.isStringAttribute())
14167d523365SDimitry Andric       AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
14177d523365SDimitry Andric 
14187d523365SDimitry Andric     CallTarget = CS.getCalledValue();
14197d523365SDimitry Andric   } else {
14207d523365SDimitry Andric     // This branch will be gone soon, and we will soon only support the
14217d523365SDimitry Andric     // UseDeoptBundles == true configuration.
14227d523365SDimitry Andric     Statepoint OldSP(CS);
14237d523365SDimitry Andric     StatepointID = OldSP.getID();
14247d523365SDimitry Andric     NumPatchBytes = OldSP.getNumPatchBytes();
14257d523365SDimitry Andric     Flags = OldSP.getFlags();
14267d523365SDimitry Andric 
14277d523365SDimitry Andric     CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
14287d523365SDimitry Andric     DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
14297d523365SDimitry Andric     TransitionArgs = {OldSP.gc_transition_args_begin(),
14307d523365SDimitry Andric                       OldSP.gc_transition_args_end()};
14317d523365SDimitry Andric     CallTarget = OldSP.getCalledValue();
14327d523365SDimitry Andric   }
1433ff0cc061SDimitry Andric 
1434ff0cc061SDimitry Andric   // Create the statepoint given all the arguments
14357d523365SDimitry Andric   Instruction *Token = nullptr;
14367d523365SDimitry Andric   AttributeSet ReturnAttrs;
1437ff0cc061SDimitry Andric   if (CS.isCall()) {
14387d523365SDimitry Andric     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
14397d523365SDimitry Andric     CallInst *Call = Builder.CreateGCStatepointCall(
14407d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
14417d523365SDimitry Andric         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
14427d523365SDimitry Andric 
14437d523365SDimitry Andric     Call->setTailCall(ToReplace->isTailCall());
14447d523365SDimitry Andric     Call->setCallingConv(ToReplace->getCallingConv());
1445ff0cc061SDimitry Andric 
1446ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1447ff0cc061SDimitry Andric     // function attributes.
14487d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14497d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1450ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14517d523365SDimitry Andric     Call->setAttributes(NewAttrs.getFnAttributes());
14527d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1453ff0cc061SDimitry Andric 
14547d523365SDimitry Andric     Token = Call;
1455ff0cc061SDimitry Andric 
1456ff0cc061SDimitry Andric     // Put the following gc_result and gc_relocate calls immediately after the
1457ff0cc061SDimitry Andric     // the old call (which we're about to delete)
14587d523365SDimitry Andric     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
14597d523365SDimitry Andric     Builder.SetInsertPoint(ToReplace->getNextNode());
14607d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1461ff0cc061SDimitry Andric   } else {
14627d523365SDimitry Andric     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1463ff0cc061SDimitry Andric 
1464ff0cc061SDimitry Andric     // Insert the new invoke into the old block.  We'll remove the old one in a
1465ff0cc061SDimitry Andric     // moment at which point this will become the new terminator for the
1466ff0cc061SDimitry Andric     // original block.
14677d523365SDimitry Andric     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
14687d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
14697d523365SDimitry Andric         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
14707d523365SDimitry Andric         GCArgs, "statepoint_token");
14717d523365SDimitry Andric 
14727d523365SDimitry Andric     Invoke->setCallingConv(ToReplace->getCallingConv());
1473ff0cc061SDimitry Andric 
1474ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1475ff0cc061SDimitry Andric     // function attributes.
14767d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14777d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1478ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14797d523365SDimitry Andric     Invoke->setAttributes(NewAttrs.getFnAttributes());
14807d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1481ff0cc061SDimitry Andric 
14827d523365SDimitry Andric     Token = Invoke;
1483ff0cc061SDimitry Andric 
1484ff0cc061SDimitry Andric     // Generate gc relocates in exceptional path
14857d523365SDimitry Andric     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
14867d523365SDimitry Andric     assert(!isa<PHINode>(UnwindBlock->begin()) &&
14877d523365SDimitry Andric            UnwindBlock->getUniquePredecessor() &&
1488ff0cc061SDimitry Andric            "can't safely insert in this block!");
1489ff0cc061SDimitry Andric 
14907d523365SDimitry Andric     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
14917d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1492ff0cc061SDimitry Andric 
14937d523365SDimitry Andric     // Attach exceptional gc relocates to the landingpad.
14947d523365SDimitry Andric     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
14957d523365SDimitry Andric     Result.UnwindToken = ExceptionalToken;
1496ff0cc061SDimitry Andric 
14977d523365SDimitry Andric     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
14987d523365SDimitry Andric     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
14997d523365SDimitry Andric                       Builder);
1500ff0cc061SDimitry Andric 
1501ff0cc061SDimitry Andric     // Generate gc relocates and returns for normal block
15027d523365SDimitry Andric     BasicBlock *NormalDest = ToReplace->getNormalDest();
15037d523365SDimitry Andric     assert(!isa<PHINode>(NormalDest->begin()) &&
15047d523365SDimitry Andric            NormalDest->getUniquePredecessor() &&
1505ff0cc061SDimitry Andric            "can't safely insert in this block!");
1506ff0cc061SDimitry Andric 
15077d523365SDimitry Andric     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1508ff0cc061SDimitry Andric 
1509ff0cc061SDimitry Andric     // gc relocates will be generated later as if it were regular call
1510ff0cc061SDimitry Andric     // statepoint
1511ff0cc061SDimitry Andric   }
15127d523365SDimitry Andric   assert(Token && "Should be set in one of the above branches!");
1513ff0cc061SDimitry Andric 
15147d523365SDimitry Andric   if (UseDeoptBundles) {
15157d523365SDimitry Andric     Token->setName("statepoint_token");
15167d523365SDimitry Andric     if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
15177d523365SDimitry Andric       StringRef Name =
15187d523365SDimitry Andric           CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
15197d523365SDimitry Andric       CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
15207d523365SDimitry Andric       GCResult->setAttributes(CS.getAttributes().getRetAttributes());
1521ff0cc061SDimitry Andric 
15227d523365SDimitry Andric       // We cannot RAUW or delete CS.getInstruction() because it could be in the
15237d523365SDimitry Andric       // live set of some other safepoint, in which case that safepoint's
15247d523365SDimitry Andric       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
15257d523365SDimitry Andric       // llvm::Instruction.  Instead, we defer the replacement and deletion to
15267d523365SDimitry Andric       // after the live sets have been made explicit in the IR, and we no longer
15277d523365SDimitry Andric       // have raw pointers to worry about.
15287d523365SDimitry Andric       Replacements.emplace_back(CS.getInstruction(), GCResult);
15297d523365SDimitry Andric     } else {
15307d523365SDimitry Andric       Replacements.emplace_back(CS.getInstruction(), nullptr);
15317d523365SDimitry Andric     }
15327d523365SDimitry Andric   } else {
15337d523365SDimitry Andric     assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1534ff0cc061SDimitry Andric            "only valid use before rewrite is gc.result");
15357d523365SDimitry Andric     assert(!CS.getInstruction()->hasOneUse() ||
15367d523365SDimitry Andric            isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
15377d523365SDimitry Andric 
15387d523365SDimitry Andric     // Take the name of the original statepoint token if there was one.
15397d523365SDimitry Andric     Token->takeName(CS.getInstruction());
1540ff0cc061SDimitry Andric 
1541ff0cc061SDimitry Andric     // Update the gc.result of the original statepoint (if any) to use the newly
1542ff0cc061SDimitry Andric     // inserted statepoint.  This is safe to do here since the token can't be
1543ff0cc061SDimitry Andric     // considered a live reference.
15447d523365SDimitry Andric     CS.getInstruction()->replaceAllUsesWith(Token);
15457d523365SDimitry Andric     CS.getInstruction()->eraseFromParent();
15467d523365SDimitry Andric   }
1547ff0cc061SDimitry Andric 
15487d523365SDimitry Andric   Result.StatepointToken = Token;
1549ff0cc061SDimitry Andric 
1550ff0cc061SDimitry Andric   // Second, create a gc.relocate for every live variable
15517d523365SDimitry Andric   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15527d523365SDimitry Andric   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1553ff0cc061SDimitry Andric }
1554ff0cc061SDimitry Andric 
1555ff0cc061SDimitry Andric namespace {
15567d523365SDimitry Andric struct NameOrdering {
15577d523365SDimitry Andric   Value *Base;
15587d523365SDimitry Andric   Value *Derived;
15597d523365SDimitry Andric 
15607d523365SDimitry Andric   bool operator()(NameOrdering const &a, NameOrdering const &b) {
15617d523365SDimitry Andric     return -1 == a.Derived->getName().compare(b.Derived->getName());
1562ff0cc061SDimitry Andric   }
1563ff0cc061SDimitry Andric };
1564ff0cc061SDimitry Andric }
1565ff0cc061SDimitry Andric 
15667d523365SDimitry Andric static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
15677d523365SDimitry Andric                            SmallVectorImpl<Value *> &LiveVec) {
15687d523365SDimitry Andric   assert(BaseVec.size() == LiveVec.size());
15697d523365SDimitry Andric 
15707d523365SDimitry Andric   SmallVector<NameOrdering, 64> Temp;
15717d523365SDimitry Andric   for (size_t i = 0; i < BaseVec.size(); i++) {
15727d523365SDimitry Andric     NameOrdering v;
15737d523365SDimitry Andric     v.Base = BaseVec[i];
15747d523365SDimitry Andric     v.Derived = LiveVec[i];
15757d523365SDimitry Andric     Temp.push_back(v);
1576ff0cc061SDimitry Andric   }
15777d523365SDimitry Andric 
15787d523365SDimitry Andric   std::sort(Temp.begin(), Temp.end(), NameOrdering());
15797d523365SDimitry Andric   for (size_t i = 0; i < BaseVec.size(); i++) {
15807d523365SDimitry Andric     BaseVec[i] = Temp[i].Base;
15817d523365SDimitry Andric     LiveVec[i] = Temp[i].Derived;
1582ff0cc061SDimitry Andric   }
1583ff0cc061SDimitry Andric }
1584ff0cc061SDimitry Andric 
1585ff0cc061SDimitry Andric // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1586ff0cc061SDimitry Andric // which make the relocations happening at this safepoint explicit.
1587ff0cc061SDimitry Andric //
1588ff0cc061SDimitry Andric // WARNING: Does not do any fixup to adjust users of the original live
1589ff0cc061SDimitry Andric // values.  That's the callers responsibility.
1590ff0cc061SDimitry Andric static void
15917d523365SDimitry Andric makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
15927d523365SDimitry Andric                        PartiallyConstructedSafepointRecord &Result,
15937d523365SDimitry Andric                        std::vector<DeferredReplacement> &Replacements) {
15947d523365SDimitry Andric   const auto &LiveSet = Result.LiveSet;
15957d523365SDimitry Andric   const auto &PointerToBase = Result.PointerToBase;
1596ff0cc061SDimitry Andric 
1597ff0cc061SDimitry Andric   // Convert to vector for efficient cross referencing.
15987d523365SDimitry Andric   SmallVector<Value *, 64> BaseVec, LiveVec;
15997d523365SDimitry Andric   LiveVec.reserve(LiveSet.size());
16007d523365SDimitry Andric   BaseVec.reserve(LiveSet.size());
16017d523365SDimitry Andric   for (Value *L : LiveSet) {
16027d523365SDimitry Andric     LiveVec.push_back(L);
16037d523365SDimitry Andric     assert(PointerToBase.count(L));
16047d523365SDimitry Andric     Value *Base = PointerToBase.find(L)->second;
16057d523365SDimitry Andric     BaseVec.push_back(Base);
1606ff0cc061SDimitry Andric   }
16077d523365SDimitry Andric   assert(LiveVec.size() == BaseVec.size());
1608ff0cc061SDimitry Andric 
1609ff0cc061SDimitry Andric   // To make the output IR slightly more stable (for use in diffs), ensure a
1610ff0cc061SDimitry Andric   // fixed order of the values in the safepoint (by sorting the value name).
1611ff0cc061SDimitry Andric   // The order is otherwise meaningless.
16127d523365SDimitry Andric   StabilizeOrder(BaseVec, LiveVec);
1613ff0cc061SDimitry Andric 
1614ff0cc061SDimitry Andric   // Do the actual rewriting and delete the old statepoint
16157d523365SDimitry Andric   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1616ff0cc061SDimitry Andric }
1617ff0cc061SDimitry Andric 
1618ff0cc061SDimitry Andric // Helper function for the relocationViaAlloca.
16197d523365SDimitry Andric //
16207d523365SDimitry Andric // It receives iterator to the statepoint gc relocates and emits a store to the
16217d523365SDimitry Andric // assigned location (via allocaMap) for the each one of them.  It adds the
16227d523365SDimitry Andric // visited values into the visitedLiveValues set, which we will later use them
16237d523365SDimitry Andric // for sanity checking.
1624ff0cc061SDimitry Andric static void
1625ff0cc061SDimitry Andric insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1626ff0cc061SDimitry Andric                        DenseMap<Value *, Value *> &AllocaMap,
1627ff0cc061SDimitry Andric                        DenseSet<Value *> &VisitedLiveValues) {
1628ff0cc061SDimitry Andric 
1629ff0cc061SDimitry Andric   for (User *U : GCRelocs) {
16304d0b32cdSDimitry Andric     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
16314d0b32cdSDimitry Andric     if (!Relocate)
1632ff0cc061SDimitry Andric       continue;
1633ff0cc061SDimitry Andric 
16344d0b32cdSDimitry Andric     Value *OriginalValue = const_cast<Value *>(Relocate->getDerivedPtr());
1635ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue));
1636ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1637ff0cc061SDimitry Andric 
1638ff0cc061SDimitry Andric     // Emit store into the related alloca
16397d523365SDimitry Andric     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1640ff0cc061SDimitry Andric     // the correct type according to alloca.
16414d0b32cdSDimitry Andric     assert(Relocate->getNextNode() &&
16427d523365SDimitry Andric            "Should always have one since it's not a terminator");
16434d0b32cdSDimitry Andric     IRBuilder<> Builder(Relocate->getNextNode());
1644ff0cc061SDimitry Andric     Value *CastedRelocatedValue =
16454d0b32cdSDimitry Andric       Builder.CreateBitCast(Relocate,
16467d523365SDimitry Andric                             cast<AllocaInst>(Alloca)->getAllocatedType(),
16474d0b32cdSDimitry Andric                             suffixed_name_or(Relocate, ".casted", ""));
1648ff0cc061SDimitry Andric 
1649ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1650ff0cc061SDimitry Andric     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1651ff0cc061SDimitry Andric 
1652ff0cc061SDimitry Andric #ifndef NDEBUG
1653ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1654ff0cc061SDimitry Andric #endif
1655ff0cc061SDimitry Andric   }
1656ff0cc061SDimitry Andric }
1657ff0cc061SDimitry Andric 
1658ff0cc061SDimitry Andric // Helper function for the "relocationViaAlloca". Similar to the
1659ff0cc061SDimitry Andric // "insertRelocationStores" but works for rematerialized values.
1660ff0cc061SDimitry Andric static void
1661ff0cc061SDimitry Andric insertRematerializationStores(
1662ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues,
1663ff0cc061SDimitry Andric   DenseMap<Value *, Value *> &AllocaMap,
1664ff0cc061SDimitry Andric   DenseSet<Value *> &VisitedLiveValues) {
1665ff0cc061SDimitry Andric 
1666ff0cc061SDimitry Andric   for (auto RematerializedValuePair: RematerializedValues) {
1667ff0cc061SDimitry Andric     Instruction *RematerializedValue = RematerializedValuePair.first;
1668ff0cc061SDimitry Andric     Value *OriginalValue = RematerializedValuePair.second;
1669ff0cc061SDimitry Andric 
1670ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue) &&
1671ff0cc061SDimitry Andric            "Can not find alloca for rematerialized value");
1672ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1673ff0cc061SDimitry Andric 
1674ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1675ff0cc061SDimitry Andric     Store->insertAfter(RematerializedValue);
1676ff0cc061SDimitry Andric 
1677ff0cc061SDimitry Andric #ifndef NDEBUG
1678ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1679ff0cc061SDimitry Andric #endif
1680ff0cc061SDimitry Andric   }
1681ff0cc061SDimitry Andric }
1682ff0cc061SDimitry Andric 
16837d523365SDimitry Andric /// Do all the relocation update via allocas and mem2reg
1684ff0cc061SDimitry Andric static void relocationViaAlloca(
1685ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
16867d523365SDimitry Andric     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1687ff0cc061SDimitry Andric #ifndef NDEBUG
1688ff0cc061SDimitry Andric   // record initial number of (static) allocas; we'll check we have the same
1689ff0cc061SDimitry Andric   // number when we get done.
1690ff0cc061SDimitry Andric   int InitialAllocaNum = 0;
1691ff0cc061SDimitry Andric   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1692ff0cc061SDimitry Andric        I++)
1693ff0cc061SDimitry Andric     if (isa<AllocaInst>(*I))
1694ff0cc061SDimitry Andric       InitialAllocaNum++;
1695ff0cc061SDimitry Andric #endif
1696ff0cc061SDimitry Andric 
1697ff0cc061SDimitry Andric   // TODO-PERF: change data structures, reserve
1698ff0cc061SDimitry Andric   DenseMap<Value *, Value *> AllocaMap;
1699ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 200> PromotableAllocas;
1700ff0cc061SDimitry Andric   // Used later to chack that we have enough allocas to store all values
1701ff0cc061SDimitry Andric   std::size_t NumRematerializedValues = 0;
1702ff0cc061SDimitry Andric   PromotableAllocas.reserve(Live.size());
1703ff0cc061SDimitry Andric 
1704ff0cc061SDimitry Andric   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1705ff0cc061SDimitry Andric   // "PromotableAllocas"
1706ff0cc061SDimitry Andric   auto emitAllocaFor = [&](Value *LiveValue) {
1707ff0cc061SDimitry Andric     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1708ff0cc061SDimitry Andric                                         F.getEntryBlock().getFirstNonPHI());
1709ff0cc061SDimitry Andric     AllocaMap[LiveValue] = Alloca;
1710ff0cc061SDimitry Andric     PromotableAllocas.push_back(Alloca);
1711ff0cc061SDimitry Andric   };
1712ff0cc061SDimitry Andric 
17137d523365SDimitry Andric   // Emit alloca for each live gc pointer
17147d523365SDimitry Andric   for (Value *V : Live)
17157d523365SDimitry Andric     emitAllocaFor(V);
1716ff0cc061SDimitry Andric 
17177d523365SDimitry Andric   // Emit allocas for rematerialized values
17187d523365SDimitry Andric   for (const auto &Info : Records)
1719ff0cc061SDimitry Andric     for (auto RematerializedValuePair : Info.RematerializedValues) {
1720ff0cc061SDimitry Andric       Value *OriginalValue = RematerializedValuePair.second;
1721ff0cc061SDimitry Andric       if (AllocaMap.count(OriginalValue) != 0)
1722ff0cc061SDimitry Andric         continue;
1723ff0cc061SDimitry Andric 
1724ff0cc061SDimitry Andric       emitAllocaFor(OriginalValue);
1725ff0cc061SDimitry Andric       ++NumRematerializedValues;
1726ff0cc061SDimitry Andric     }
1727ff0cc061SDimitry Andric 
1728ff0cc061SDimitry Andric   // The next two loops are part of the same conceptual operation.  We need to
1729ff0cc061SDimitry Andric   // insert a store to the alloca after the original def and at each
1730ff0cc061SDimitry Andric   // redefinition.  We need to insert a load before each use.  These are split
1731ff0cc061SDimitry Andric   // into distinct loops for performance reasons.
1732ff0cc061SDimitry Andric 
17337d523365SDimitry Andric   // Update gc pointer after each statepoint: either store a relocated value or
17347d523365SDimitry Andric   // null (if no relocated value was found for this gc pointer and it is not a
17357d523365SDimitry Andric   // gc_result).  This must happen before we update the statepoint with load of
17367d523365SDimitry Andric   // alloca otherwise we lose the link between statepoint and old def.
17377d523365SDimitry Andric   for (const auto &Info : Records) {
1738ff0cc061SDimitry Andric     Value *Statepoint = Info.StatepointToken;
1739ff0cc061SDimitry Andric 
1740ff0cc061SDimitry Andric     // This will be used for consistency check
1741ff0cc061SDimitry Andric     DenseSet<Value *> VisitedLiveValues;
1742ff0cc061SDimitry Andric 
1743ff0cc061SDimitry Andric     // Insert stores for normal statepoint gc relocates
1744ff0cc061SDimitry Andric     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1745ff0cc061SDimitry Andric 
1746ff0cc061SDimitry Andric     // In case if it was invoke statepoint
1747ff0cc061SDimitry Andric     // we will insert stores for exceptional path gc relocates.
1748ff0cc061SDimitry Andric     if (isa<InvokeInst>(Statepoint)) {
1749ff0cc061SDimitry Andric       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1750ff0cc061SDimitry Andric                              VisitedLiveValues);
1751ff0cc061SDimitry Andric     }
1752ff0cc061SDimitry Andric 
1753ff0cc061SDimitry Andric     // Do similar thing with rematerialized values
1754ff0cc061SDimitry Andric     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1755ff0cc061SDimitry Andric                                   VisitedLiveValues);
1756ff0cc061SDimitry Andric 
1757ff0cc061SDimitry Andric     if (ClobberNonLive) {
17587d523365SDimitry Andric       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1759ff0cc061SDimitry Andric       // the gc.statepoint.  This will turn some subtle GC problems into
1760ff0cc061SDimitry Andric       // slightly easier to debug SEGVs.  Note that on large IR files with
1761ff0cc061SDimitry Andric       // lots of gc.statepoints this is extremely costly both memory and time
1762ff0cc061SDimitry Andric       // wise.
1763ff0cc061SDimitry Andric       SmallVector<AllocaInst *, 64> ToClobber;
1764ff0cc061SDimitry Andric       for (auto Pair : AllocaMap) {
1765ff0cc061SDimitry Andric         Value *Def = Pair.first;
1766ff0cc061SDimitry Andric         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1767ff0cc061SDimitry Andric 
1768ff0cc061SDimitry Andric         // This value was relocated
1769ff0cc061SDimitry Andric         if (VisitedLiveValues.count(Def)) {
1770ff0cc061SDimitry Andric           continue;
1771ff0cc061SDimitry Andric         }
1772ff0cc061SDimitry Andric         ToClobber.push_back(Alloca);
1773ff0cc061SDimitry Andric       }
1774ff0cc061SDimitry Andric 
1775ff0cc061SDimitry Andric       auto InsertClobbersAt = [&](Instruction *IP) {
1776ff0cc061SDimitry Andric         for (auto *AI : ToClobber) {
1777ff0cc061SDimitry Andric           auto AIType = cast<PointerType>(AI->getType());
1778ff0cc061SDimitry Andric           auto PT = cast<PointerType>(AIType->getElementType());
1779ff0cc061SDimitry Andric           Constant *CPN = ConstantPointerNull::get(PT);
1780ff0cc061SDimitry Andric           StoreInst *Store = new StoreInst(CPN, AI);
1781ff0cc061SDimitry Andric           Store->insertBefore(IP);
1782ff0cc061SDimitry Andric         }
1783ff0cc061SDimitry Andric       };
1784ff0cc061SDimitry Andric 
1785ff0cc061SDimitry Andric       // Insert the clobbering stores.  These may get intermixed with the
1786ff0cc061SDimitry Andric       // gc.results and gc.relocates, but that's fine.
1787ff0cc061SDimitry Andric       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
17887d523365SDimitry Andric         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
17897d523365SDimitry Andric         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1790ff0cc061SDimitry Andric       } else {
17917d523365SDimitry Andric         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1792ff0cc061SDimitry Andric       }
1793ff0cc061SDimitry Andric     }
1794ff0cc061SDimitry Andric   }
17957d523365SDimitry Andric 
17967d523365SDimitry Andric   // Update use with load allocas and add store for gc_relocated.
1797ff0cc061SDimitry Andric   for (auto Pair : AllocaMap) {
1798ff0cc061SDimitry Andric     Value *Def = Pair.first;
1799ff0cc061SDimitry Andric     Value *Alloca = Pair.second;
1800ff0cc061SDimitry Andric 
18017d523365SDimitry Andric     // We pre-record the uses of allocas so that we dont have to worry about
18027d523365SDimitry Andric     // later update that changes the user information..
18037d523365SDimitry Andric 
1804ff0cc061SDimitry Andric     SmallVector<Instruction *, 20> Uses;
1805ff0cc061SDimitry Andric     // PERF: trade a linear scan for repeated reallocation
1806ff0cc061SDimitry Andric     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1807ff0cc061SDimitry Andric     for (User *U : Def->users()) {
1808ff0cc061SDimitry Andric       if (!isa<ConstantExpr>(U)) {
1809ff0cc061SDimitry Andric         // If the def has a ConstantExpr use, then the def is either a
1810ff0cc061SDimitry Andric         // ConstantExpr use itself or null.  In either case
1811ff0cc061SDimitry Andric         // (recursively in the first, directly in the second), the oop
1812ff0cc061SDimitry Andric         // it is ultimately dependent on is null and this particular
1813ff0cc061SDimitry Andric         // use does not need to be fixed up.
1814ff0cc061SDimitry Andric         Uses.push_back(cast<Instruction>(U));
1815ff0cc061SDimitry Andric       }
1816ff0cc061SDimitry Andric     }
1817ff0cc061SDimitry Andric 
1818ff0cc061SDimitry Andric     std::sort(Uses.begin(), Uses.end());
1819ff0cc061SDimitry Andric     auto Last = std::unique(Uses.begin(), Uses.end());
1820ff0cc061SDimitry Andric     Uses.erase(Last, Uses.end());
1821ff0cc061SDimitry Andric 
1822ff0cc061SDimitry Andric     for (Instruction *Use : Uses) {
1823ff0cc061SDimitry Andric       if (isa<PHINode>(Use)) {
1824ff0cc061SDimitry Andric         PHINode *Phi = cast<PHINode>(Use);
1825ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1826ff0cc061SDimitry Andric           if (Def == Phi->getIncomingValue(i)) {
1827ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1828ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1829ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1830ff0cc061SDimitry Andric           }
1831ff0cc061SDimitry Andric         }
1832ff0cc061SDimitry Andric       } else {
1833ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", Use);
1834ff0cc061SDimitry Andric         Use->replaceUsesOfWith(Def, Load);
1835ff0cc061SDimitry Andric       }
1836ff0cc061SDimitry Andric     }
1837ff0cc061SDimitry Andric 
18387d523365SDimitry Andric     // Emit store for the initial gc value.  Store must be inserted after load,
18397d523365SDimitry Andric     // otherwise store will be in alloca's use list and an extra load will be
18407d523365SDimitry Andric     // inserted before it.
1841ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(Def, Alloca);
1842ff0cc061SDimitry Andric     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1843ff0cc061SDimitry Andric       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1844ff0cc061SDimitry Andric         // InvokeInst is a TerminatorInst so the store need to be inserted
1845ff0cc061SDimitry Andric         // into its normal destination block.
1846ff0cc061SDimitry Andric         BasicBlock *NormalDest = Invoke->getNormalDest();
1847ff0cc061SDimitry Andric         Store->insertBefore(NormalDest->getFirstNonPHI());
1848ff0cc061SDimitry Andric       } else {
1849ff0cc061SDimitry Andric         assert(!Inst->isTerminator() &&
1850ff0cc061SDimitry Andric                "The only TerminatorInst that can produce a value is "
1851ff0cc061SDimitry Andric                "InvokeInst which is handled above.");
1852ff0cc061SDimitry Andric         Store->insertAfter(Inst);
1853ff0cc061SDimitry Andric       }
1854ff0cc061SDimitry Andric     } else {
1855ff0cc061SDimitry Andric       assert(isa<Argument>(Def));
1856ff0cc061SDimitry Andric       Store->insertAfter(cast<Instruction>(Alloca));
1857ff0cc061SDimitry Andric     }
1858ff0cc061SDimitry Andric   }
1859ff0cc061SDimitry Andric 
1860ff0cc061SDimitry Andric   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1861ff0cc061SDimitry Andric          "we must have the same allocas with lives");
1862ff0cc061SDimitry Andric   if (!PromotableAllocas.empty()) {
18637d523365SDimitry Andric     // Apply mem2reg to promote alloca to SSA
1864ff0cc061SDimitry Andric     PromoteMemToReg(PromotableAllocas, DT);
1865ff0cc061SDimitry Andric   }
1866ff0cc061SDimitry Andric 
1867ff0cc061SDimitry Andric #ifndef NDEBUG
18687d523365SDimitry Andric   for (auto &I : F.getEntryBlock())
18697d523365SDimitry Andric     if (isa<AllocaInst>(I))
1870ff0cc061SDimitry Andric       InitialAllocaNum--;
1871ff0cc061SDimitry Andric   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1872ff0cc061SDimitry Andric #endif
1873ff0cc061SDimitry Andric }
1874ff0cc061SDimitry Andric 
1875ff0cc061SDimitry Andric /// Implement a unique function which doesn't require we sort the input
1876ff0cc061SDimitry Andric /// vector.  Doing so has the effect of changing the output of a couple of
1877ff0cc061SDimitry Andric /// tests in ways which make them less useful in testing fused safepoints.
1878ff0cc061SDimitry Andric template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
18798f0fd8f6SDimitry Andric   SmallSet<T, 8> Seen;
18808f0fd8f6SDimitry Andric   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
18818f0fd8f6SDimitry Andric               return !Seen.insert(V).second;
18828f0fd8f6SDimitry Andric             }), Vec.end());
1883ff0cc061SDimitry Andric }
1884ff0cc061SDimitry Andric 
1885ff0cc061SDimitry Andric /// Insert holders so that each Value is obviously live through the entire
1886ff0cc061SDimitry Andric /// lifetime of the call.
1887ff0cc061SDimitry Andric static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1888ff0cc061SDimitry Andric                                  SmallVectorImpl<CallInst *> &Holders) {
1889ff0cc061SDimitry Andric   if (Values.empty())
1890ff0cc061SDimitry Andric     // No values to hold live, might as well not insert the empty holder
1891ff0cc061SDimitry Andric     return;
1892ff0cc061SDimitry Andric 
18937d523365SDimitry Andric   Module *M = CS.getInstruction()->getModule();
1894ff0cc061SDimitry Andric   // Use a dummy vararg function to actually hold the values live
1895ff0cc061SDimitry Andric   Function *Func = cast<Function>(M->getOrInsertFunction(
1896ff0cc061SDimitry Andric       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1897ff0cc061SDimitry Andric   if (CS.isCall()) {
1898ff0cc061SDimitry Andric     // For call safepoints insert dummy calls right after safepoint
18997d523365SDimitry Andric     Holders.push_back(CallInst::Create(Func, Values, "",
19007d523365SDimitry Andric                                        &*++CS.getInstruction()->getIterator()));
1901ff0cc061SDimitry Andric     return;
1902ff0cc061SDimitry Andric   }
1903ff0cc061SDimitry Andric   // For invoke safepooints insert dummy calls both in normal and
1904ff0cc061SDimitry Andric   // exceptional destination blocks
1905ff0cc061SDimitry Andric   auto *II = cast<InvokeInst>(CS.getInstruction());
1906ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19077d523365SDimitry Andric       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1908ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19097d523365SDimitry Andric       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1910ff0cc061SDimitry Andric }
1911ff0cc061SDimitry Andric 
1912ff0cc061SDimitry Andric static void findLiveReferences(
19137d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1914ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1915ff0cc061SDimitry Andric   GCPtrLivenessData OriginalLivenessData;
1916ff0cc061SDimitry Andric   computeLiveInValues(DT, F, OriginalLivenessData);
1917ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1918ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1919ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1920ff0cc061SDimitry Andric     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1921ff0cc061SDimitry Andric   }
1922ff0cc061SDimitry Andric }
1923ff0cc061SDimitry Andric 
1924ff0cc061SDimitry Andric /// Remove any vector of pointers from the live set by scalarizing them over the
1925ff0cc061SDimitry Andric /// statepoint instruction.  Adds the scalarized pieces to the live set.  It
19267d523365SDimitry Andric /// would be preferable to include the vector in the statepoint itself, but
1927ff0cc061SDimitry Andric /// the lowering code currently does not handle that.  Extending it would be
1928ff0cc061SDimitry Andric /// slightly non-trivial since it requires a format change.  Given how rare
19297d523365SDimitry Andric /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1930ff0cc061SDimitry Andric static void splitVectorValues(Instruction *StatepointInst,
19313dac3a9bSDimitry Andric                               StatepointLiveSetTy &LiveSet,
19323dac3a9bSDimitry Andric                               DenseMap<Value *, Value *>& PointerToBase,
19333dac3a9bSDimitry Andric                               DominatorTree &DT) {
1934ff0cc061SDimitry Andric   SmallVector<Value *, 16> ToSplit;
1935ff0cc061SDimitry Andric   for (Value *V : LiveSet)
1936ff0cc061SDimitry Andric     if (isa<VectorType>(V->getType()))
1937ff0cc061SDimitry Andric       ToSplit.push_back(V);
1938ff0cc061SDimitry Andric 
1939ff0cc061SDimitry Andric   if (ToSplit.empty())
1940ff0cc061SDimitry Andric     return;
1941ff0cc061SDimitry Andric 
19423dac3a9bSDimitry Andric   DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
19433dac3a9bSDimitry Andric 
1944ff0cc061SDimitry Andric   Function &F = *(StatepointInst->getParent()->getParent());
1945ff0cc061SDimitry Andric 
1946ff0cc061SDimitry Andric   DenseMap<Value *, AllocaInst *> AllocaMap;
1947ff0cc061SDimitry Andric   // First is normal return, second is exceptional return (invoke only)
1948ff0cc061SDimitry Andric   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1949ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1950ff0cc061SDimitry Andric     AllocaInst *Alloca =
1951ff0cc061SDimitry Andric         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1952ff0cc061SDimitry Andric     AllocaMap[V] = Alloca;
1953ff0cc061SDimitry Andric 
1954ff0cc061SDimitry Andric     VectorType *VT = cast<VectorType>(V->getType());
1955ff0cc061SDimitry Andric     IRBuilder<> Builder(StatepointInst);
1956ff0cc061SDimitry Andric     SmallVector<Value *, 16> Elements;
1957ff0cc061SDimitry Andric     for (unsigned i = 0; i < VT->getNumElements(); i++)
1958ff0cc061SDimitry Andric       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
19593dac3a9bSDimitry Andric     ElementMapping[V] = Elements;
1960ff0cc061SDimitry Andric 
1961ff0cc061SDimitry Andric     auto InsertVectorReform = [&](Instruction *IP) {
1962ff0cc061SDimitry Andric       Builder.SetInsertPoint(IP);
1963ff0cc061SDimitry Andric       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1964ff0cc061SDimitry Andric       Value *ResultVec = UndefValue::get(VT);
1965ff0cc061SDimitry Andric       for (unsigned i = 0; i < VT->getNumElements(); i++)
1966ff0cc061SDimitry Andric         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1967ff0cc061SDimitry Andric                                                 Builder.getInt32(i));
1968ff0cc061SDimitry Andric       return ResultVec;
1969ff0cc061SDimitry Andric     };
1970ff0cc061SDimitry Andric 
1971ff0cc061SDimitry Andric     if (isa<CallInst>(StatepointInst)) {
1972ff0cc061SDimitry Andric       BasicBlock::iterator Next(StatepointInst);
1973ff0cc061SDimitry Andric       Next++;
1974ff0cc061SDimitry Andric       Instruction *IP = &*(Next);
1975ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
1976ff0cc061SDimitry Andric       Replacements[V].second = nullptr;
1977ff0cc061SDimitry Andric     } else {
1978ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1979ff0cc061SDimitry Andric       // We've already normalized - check that we don't have shared destination
1980ff0cc061SDimitry Andric       // blocks
1981ff0cc061SDimitry Andric       BasicBlock *NormalDest = Invoke->getNormalDest();
1982ff0cc061SDimitry Andric       assert(!isa<PHINode>(NormalDest->begin()));
1983ff0cc061SDimitry Andric       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1984ff0cc061SDimitry Andric       assert(!isa<PHINode>(UnwindDest->begin()));
1985ff0cc061SDimitry Andric       // Insert insert element sequences in both successors
1986ff0cc061SDimitry Andric       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1987ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
1988ff0cc061SDimitry Andric       IP = &*(UnwindDest->getFirstInsertionPt());
1989ff0cc061SDimitry Andric       Replacements[V].second = InsertVectorReform(IP);
1990ff0cc061SDimitry Andric     }
1991ff0cc061SDimitry Andric   }
19923dac3a9bSDimitry Andric 
1993ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1994ff0cc061SDimitry Andric     AllocaInst *Alloca = AllocaMap[V];
1995ff0cc061SDimitry Andric 
1996ff0cc061SDimitry Andric     // Capture all users before we start mutating use lists
1997ff0cc061SDimitry Andric     SmallVector<Instruction *, 16> Users;
1998ff0cc061SDimitry Andric     for (User *U : V->users())
1999ff0cc061SDimitry Andric       Users.push_back(cast<Instruction>(U));
2000ff0cc061SDimitry Andric 
2001ff0cc061SDimitry Andric     for (Instruction *I : Users) {
2002ff0cc061SDimitry Andric       if (auto Phi = dyn_cast<PHINode>(I)) {
2003ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2004ff0cc061SDimitry Andric           if (V == Phi->getIncomingValue(i)) {
2005ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
2006ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
2007ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
2008ff0cc061SDimitry Andric           }
2009ff0cc061SDimitry Andric       } else {
2010ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", I);
2011ff0cc061SDimitry Andric         I->replaceUsesOfWith(V, Load);
2012ff0cc061SDimitry Andric       }
2013ff0cc061SDimitry Andric     }
2014ff0cc061SDimitry Andric 
2015ff0cc061SDimitry Andric     // Store the original value and the replacement value into the alloca
2016ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(V, Alloca);
2017ff0cc061SDimitry Andric     if (auto I = dyn_cast<Instruction>(V))
2018ff0cc061SDimitry Andric       Store->insertAfter(I);
2019ff0cc061SDimitry Andric     else
2020ff0cc061SDimitry Andric       Store->insertAfter(Alloca);
2021ff0cc061SDimitry Andric 
2022ff0cc061SDimitry Andric     // Normal return for invoke, or call return
2023ff0cc061SDimitry Andric     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2024ff0cc061SDimitry Andric     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2025ff0cc061SDimitry Andric     // Unwind return for invoke only
2026ff0cc061SDimitry Andric     Replacement = cast_or_null<Instruction>(Replacements[V].second);
2027ff0cc061SDimitry Andric     if (Replacement)
2028ff0cc061SDimitry Andric       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2029ff0cc061SDimitry Andric   }
2030ff0cc061SDimitry Andric 
2031ff0cc061SDimitry Andric   // apply mem2reg to promote alloca to SSA
2032ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
2033ff0cc061SDimitry Andric   for (Value *V : ToSplit)
2034ff0cc061SDimitry Andric     Allocas.push_back(AllocaMap[V]);
2035ff0cc061SDimitry Andric   PromoteMemToReg(Allocas, DT);
20363dac3a9bSDimitry Andric 
20373dac3a9bSDimitry Andric   // Update our tracking of live pointers and base mappings to account for the
20383dac3a9bSDimitry Andric   // changes we just made.
20393dac3a9bSDimitry Andric   for (Value *V : ToSplit) {
20403dac3a9bSDimitry Andric     auto &Elements = ElementMapping[V];
20413dac3a9bSDimitry Andric 
20423dac3a9bSDimitry Andric     LiveSet.erase(V);
20433dac3a9bSDimitry Andric     LiveSet.insert(Elements.begin(), Elements.end());
20443dac3a9bSDimitry Andric     // We need to update the base mapping as well.
20453dac3a9bSDimitry Andric     assert(PointerToBase.count(V));
20463dac3a9bSDimitry Andric     Value *OldBase = PointerToBase[V];
20473dac3a9bSDimitry Andric     auto &BaseElements = ElementMapping[OldBase];
20483dac3a9bSDimitry Andric     PointerToBase.erase(V);
20493dac3a9bSDimitry Andric     assert(Elements.size() == BaseElements.size());
20503dac3a9bSDimitry Andric     for (unsigned i = 0; i < Elements.size(); i++) {
20513dac3a9bSDimitry Andric       Value *Elem = Elements[i];
20523dac3a9bSDimitry Andric       PointerToBase[Elem] = BaseElements[i];
20533dac3a9bSDimitry Andric     }
20543dac3a9bSDimitry Andric   }
2055ff0cc061SDimitry Andric }
2056ff0cc061SDimitry Andric 
2057ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". It walks use chain
2058ff0cc061SDimitry Andric // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2059ff0cc061SDimitry Andric // values are visited (currently it is GEP's and casts). Returns true if it
20607d523365SDimitry Andric // successfully reached "BaseValue" and false otherwise.
2061ff0cc061SDimitry Andric // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2062ff0cc061SDimitry Andric // recorded.
2063ff0cc061SDimitry Andric static bool findRematerializableChainToBasePointer(
2064ff0cc061SDimitry Andric   SmallVectorImpl<Instruction*> &ChainToBase,
2065ff0cc061SDimitry Andric   Value *CurrentValue, Value *BaseValue) {
2066ff0cc061SDimitry Andric 
2067ff0cc061SDimitry Andric   // We have found a base value
2068ff0cc061SDimitry Andric   if (CurrentValue == BaseValue) {
2069ff0cc061SDimitry Andric     return true;
2070ff0cc061SDimitry Andric   }
2071ff0cc061SDimitry Andric 
2072ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2073ff0cc061SDimitry Andric     ChainToBase.push_back(GEP);
2074ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
2075ff0cc061SDimitry Andric                                                   GEP->getPointerOperand(),
2076ff0cc061SDimitry Andric                                                   BaseValue);
2077ff0cc061SDimitry Andric   }
2078ff0cc061SDimitry Andric 
2079ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2080ff0cc061SDimitry Andric     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2081ff0cc061SDimitry Andric       return false;
2082ff0cc061SDimitry Andric 
2083ff0cc061SDimitry Andric     ChainToBase.push_back(CI);
20847d523365SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
20857d523365SDimitry Andric                                                   CI->getOperand(0), BaseValue);
2086ff0cc061SDimitry Andric   }
2087ff0cc061SDimitry Andric 
2088ff0cc061SDimitry Andric   // Not supported instruction in the chain
2089ff0cc061SDimitry Andric   return false;
2090ff0cc061SDimitry Andric }
2091ff0cc061SDimitry Andric 
2092ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". Compute cost of the use
2093ff0cc061SDimitry Andric // chain we are going to rematerialize.
2094ff0cc061SDimitry Andric static unsigned
2095ff0cc061SDimitry Andric chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2096ff0cc061SDimitry Andric                        TargetTransformInfo &TTI) {
2097ff0cc061SDimitry Andric   unsigned Cost = 0;
2098ff0cc061SDimitry Andric 
2099ff0cc061SDimitry Andric   for (Instruction *Instr : Chain) {
2100ff0cc061SDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2101ff0cc061SDimitry Andric       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2102ff0cc061SDimitry Andric              "non noop cast is found during rematerialization");
2103ff0cc061SDimitry Andric 
2104ff0cc061SDimitry Andric       Type *SrcTy = CI->getOperand(0)->getType();
2105ff0cc061SDimitry Andric       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2106ff0cc061SDimitry Andric 
2107ff0cc061SDimitry Andric     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2108ff0cc061SDimitry Andric       // Cost of the address calculation
2109ff0cc061SDimitry Andric       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2110ff0cc061SDimitry Andric       Cost += TTI.getAddressComputationCost(ValTy);
2111ff0cc061SDimitry Andric 
2112ff0cc061SDimitry Andric       // And cost of the GEP itself
2113ff0cc061SDimitry Andric       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2114ff0cc061SDimitry Andric       //       allowed for the external usage)
2115ff0cc061SDimitry Andric       if (!GEP->hasAllConstantIndices())
2116ff0cc061SDimitry Andric         Cost += 2;
2117ff0cc061SDimitry Andric 
2118ff0cc061SDimitry Andric     } else {
2119ff0cc061SDimitry Andric       llvm_unreachable("unsupported instruciton type during rematerialization");
2120ff0cc061SDimitry Andric     }
2121ff0cc061SDimitry Andric   }
2122ff0cc061SDimitry Andric 
2123ff0cc061SDimitry Andric   return Cost;
2124ff0cc061SDimitry Andric }
2125ff0cc061SDimitry Andric 
21267d523365SDimitry Andric // From the statepoint live set pick values that are cheaper to recompute then
21277d523365SDimitry Andric // to relocate. Remove this values from the live set, rematerialize them after
2128ff0cc061SDimitry Andric // statepoint and record them in "Info" structure. Note that similar to
2129ff0cc061SDimitry Andric // relocated values we don't do any user adjustments here.
2130ff0cc061SDimitry Andric static void rematerializeLiveValues(CallSite CS,
2131ff0cc061SDimitry Andric                                     PartiallyConstructedSafepointRecord &Info,
2132ff0cc061SDimitry Andric                                     TargetTransformInfo &TTI) {
2133ff0cc061SDimitry Andric   const unsigned int ChainLengthThreshold = 10;
2134ff0cc061SDimitry Andric 
2135ff0cc061SDimitry Andric   // Record values we are going to delete from this statepoint live set.
2136ff0cc061SDimitry Andric   // We can not di this in following loop due to iterator invalidation.
2137ff0cc061SDimitry Andric   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2138ff0cc061SDimitry Andric 
21397d523365SDimitry Andric   for (Value *LiveValue: Info.LiveSet) {
2140ff0cc061SDimitry Andric     // For each live pointer find it's defining chain
2141ff0cc061SDimitry Andric     SmallVector<Instruction *, 3> ChainToBase;
21427d523365SDimitry Andric     assert(Info.PointerToBase.count(LiveValue));
2143ff0cc061SDimitry Andric     bool FoundChain =
2144ff0cc061SDimitry Andric       findRematerializableChainToBasePointer(ChainToBase,
2145ff0cc061SDimitry Andric                                              LiveValue,
2146ff0cc061SDimitry Andric                                              Info.PointerToBase[LiveValue]);
2147ff0cc061SDimitry Andric     // Nothing to do, or chain is too long
2148ff0cc061SDimitry Andric     if (!FoundChain ||
2149ff0cc061SDimitry Andric         ChainToBase.size() == 0 ||
2150ff0cc061SDimitry Andric         ChainToBase.size() > ChainLengthThreshold)
2151ff0cc061SDimitry Andric       continue;
2152ff0cc061SDimitry Andric 
2153ff0cc061SDimitry Andric     // Compute cost of this chain
2154ff0cc061SDimitry Andric     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2155ff0cc061SDimitry Andric     // TODO: We can also account for cases when we will be able to remove some
2156ff0cc061SDimitry Andric     //       of the rematerialized values by later optimization passes. I.e if
2157ff0cc061SDimitry Andric     //       we rematerialized several intersecting chains. Or if original values
2158ff0cc061SDimitry Andric     //       don't have any uses besides this statepoint.
2159ff0cc061SDimitry Andric 
2160ff0cc061SDimitry Andric     // For invokes we need to rematerialize each chain twice - for normal and
2161ff0cc061SDimitry Andric     // for unwind basic blocks. Model this by multiplying cost by two.
2162ff0cc061SDimitry Andric     if (CS.isInvoke()) {
2163ff0cc061SDimitry Andric       Cost *= 2;
2164ff0cc061SDimitry Andric     }
2165ff0cc061SDimitry Andric     // If it's too expensive - skip it
2166ff0cc061SDimitry Andric     if (Cost >= RematerializationThreshold)
2167ff0cc061SDimitry Andric       continue;
2168ff0cc061SDimitry Andric 
2169ff0cc061SDimitry Andric     // Remove value from the live set
2170ff0cc061SDimitry Andric     LiveValuesToBeDeleted.push_back(LiveValue);
2171ff0cc061SDimitry Andric 
2172ff0cc061SDimitry Andric     // Clone instructions and record them inside "Info" structure
2173ff0cc061SDimitry Andric 
2174ff0cc061SDimitry Andric     // Walk backwards to visit top-most instructions first
2175ff0cc061SDimitry Andric     std::reverse(ChainToBase.begin(), ChainToBase.end());
2176ff0cc061SDimitry Andric 
2177ff0cc061SDimitry Andric     // Utility function which clones all instructions from "ChainToBase"
2178ff0cc061SDimitry Andric     // and inserts them before "InsertBefore". Returns rematerialized value
2179ff0cc061SDimitry Andric     // which should be used after statepoint.
2180ff0cc061SDimitry Andric     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2181ff0cc061SDimitry Andric       Instruction *LastClonedValue = nullptr;
2182ff0cc061SDimitry Andric       Instruction *LastValue = nullptr;
2183ff0cc061SDimitry Andric       for (Instruction *Instr: ChainToBase) {
2184ff0cc061SDimitry Andric         // Only GEP's and casts are suported as we need to be careful to not
2185ff0cc061SDimitry Andric         // introduce any new uses of pointers not in the liveset.
2186ff0cc061SDimitry Andric         // Note that it's fine to introduce new uses of pointers which were
2187ff0cc061SDimitry Andric         // otherwise not used after this statepoint.
2188ff0cc061SDimitry Andric         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2189ff0cc061SDimitry Andric 
2190ff0cc061SDimitry Andric         Instruction *ClonedValue = Instr->clone();
2191ff0cc061SDimitry Andric         ClonedValue->insertBefore(InsertBefore);
2192ff0cc061SDimitry Andric         ClonedValue->setName(Instr->getName() + ".remat");
2193ff0cc061SDimitry Andric 
2194ff0cc061SDimitry Andric         // If it is not first instruction in the chain then it uses previously
2195ff0cc061SDimitry Andric         // cloned value. We should update it to use cloned value.
2196ff0cc061SDimitry Andric         if (LastClonedValue) {
2197ff0cc061SDimitry Andric           assert(LastValue);
2198ff0cc061SDimitry Andric           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2199ff0cc061SDimitry Andric #ifndef NDEBUG
2200ff0cc061SDimitry Andric           // Assert that cloned instruction does not use any instructions from
2201ff0cc061SDimitry Andric           // this chain other than LastClonedValue
2202ff0cc061SDimitry Andric           for (auto OpValue : ClonedValue->operand_values()) {
2203ff0cc061SDimitry Andric             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2204ff0cc061SDimitry Andric                        ChainToBase.end() &&
2205ff0cc061SDimitry Andric                    "incorrect use in rematerialization chain");
2206ff0cc061SDimitry Andric           }
2207ff0cc061SDimitry Andric #endif
2208ff0cc061SDimitry Andric         }
2209ff0cc061SDimitry Andric 
2210ff0cc061SDimitry Andric         LastClonedValue = ClonedValue;
2211ff0cc061SDimitry Andric         LastValue = Instr;
2212ff0cc061SDimitry Andric       }
2213ff0cc061SDimitry Andric       assert(LastClonedValue);
2214ff0cc061SDimitry Andric       return LastClonedValue;
2215ff0cc061SDimitry Andric     };
2216ff0cc061SDimitry Andric 
2217ff0cc061SDimitry Andric     // Different cases for calls and invokes. For invokes we need to clone
2218ff0cc061SDimitry Andric     // instructions both on normal and unwind path.
2219ff0cc061SDimitry Andric     if (CS.isCall()) {
2220ff0cc061SDimitry Andric       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2221ff0cc061SDimitry Andric       assert(InsertBefore);
2222ff0cc061SDimitry Andric       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2223ff0cc061SDimitry Andric       Info.RematerializedValues[RematerializedValue] = LiveValue;
2224ff0cc061SDimitry Andric     } else {
2225ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2226ff0cc061SDimitry Andric 
2227ff0cc061SDimitry Andric       Instruction *NormalInsertBefore =
22287d523365SDimitry Andric           &*Invoke->getNormalDest()->getFirstInsertionPt();
2229ff0cc061SDimitry Andric       Instruction *UnwindInsertBefore =
22307d523365SDimitry Andric           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2231ff0cc061SDimitry Andric 
2232ff0cc061SDimitry Andric       Instruction *NormalRematerializedValue =
2233ff0cc061SDimitry Andric           rematerializeChain(NormalInsertBefore);
2234ff0cc061SDimitry Andric       Instruction *UnwindRematerializedValue =
2235ff0cc061SDimitry Andric           rematerializeChain(UnwindInsertBefore);
2236ff0cc061SDimitry Andric 
2237ff0cc061SDimitry Andric       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2238ff0cc061SDimitry Andric       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2239ff0cc061SDimitry Andric     }
2240ff0cc061SDimitry Andric   }
2241ff0cc061SDimitry Andric 
2242ff0cc061SDimitry Andric   // Remove rematerializaed values from the live set
2243ff0cc061SDimitry Andric   for (auto LiveValue: LiveValuesToBeDeleted) {
22447d523365SDimitry Andric     Info.LiveSet.erase(LiveValue);
2245ff0cc061SDimitry Andric   }
2246ff0cc061SDimitry Andric }
2247ff0cc061SDimitry Andric 
22487d523365SDimitry Andric static bool insertParsePoints(Function &F, DominatorTree &DT,
22497d523365SDimitry Andric                               TargetTransformInfo &TTI,
22507d523365SDimitry Andric                               SmallVectorImpl<CallSite> &ToUpdate) {
2251ff0cc061SDimitry Andric #ifndef NDEBUG
2252ff0cc061SDimitry Andric   // sanity check the input
22537d523365SDimitry Andric   std::set<CallSite> Uniqued;
22547d523365SDimitry Andric   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
22557d523365SDimitry Andric   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2256ff0cc061SDimitry Andric 
22577d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2258ff0cc061SDimitry Andric     assert(CS.getInstruction()->getParent()->getParent() == &F);
22597d523365SDimitry Andric     assert((UseDeoptBundles || isStatepoint(CS)) &&
22607d523365SDimitry Andric            "expected to already be a deopt statepoint");
2261ff0cc061SDimitry Andric   }
2262ff0cc061SDimitry Andric #endif
2263ff0cc061SDimitry Andric 
2264ff0cc061SDimitry Andric   // When inserting gc.relocates for invokes, we need to be able to insert at
2265ff0cc061SDimitry Andric   // the top of the successor blocks.  See the comment on
2266ff0cc061SDimitry Andric   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2267ff0cc061SDimitry Andric   // may restructure the CFG.
22687d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2269ff0cc061SDimitry Andric     if (!CS.isInvoke())
2270ff0cc061SDimitry Andric       continue;
22717d523365SDimitry Andric     auto *II = cast<InvokeInst>(CS.getInstruction());
22727d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
22737d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2274ff0cc061SDimitry Andric   }
2275ff0cc061SDimitry Andric 
2276ff0cc061SDimitry Andric   // A list of dummy calls added to the IR to keep various values obviously
2277ff0cc061SDimitry Andric   // live in the IR.  We'll remove all of these when done.
22787d523365SDimitry Andric   SmallVector<CallInst *, 64> Holders;
2279ff0cc061SDimitry Andric 
2280ff0cc061SDimitry Andric   // Insert a dummy call with all of the arguments to the vm_state we'll need
2281ff0cc061SDimitry Andric   // for the actual safepoint insertion.  This ensures reference arguments in
2282ff0cc061SDimitry Andric   // the deopt argument list are considered live through the safepoint (and
2283ff0cc061SDimitry Andric   // thus makes sure they get relocated.)
22847d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2285ff0cc061SDimitry Andric     SmallVector<Value *, 64> DeoptValues;
22867d523365SDimitry Andric 
22877d523365SDimitry Andric     iterator_range<const Use *> DeoptStateRange =
22887d523365SDimitry Andric         UseDeoptBundles
22897d523365SDimitry Andric             ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
22907d523365SDimitry Andric             : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
22917d523365SDimitry Andric 
22927d523365SDimitry Andric     for (Value *Arg : DeoptStateRange) {
2293ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2294ff0cc061SDimitry Andric              "support for FCA unimplemented");
2295ff0cc061SDimitry Andric       if (isHandledGCPointerType(Arg->getType()))
2296ff0cc061SDimitry Andric         DeoptValues.push_back(Arg);
2297ff0cc061SDimitry Andric     }
22987d523365SDimitry Andric 
22997d523365SDimitry Andric     insertUseHolderAfter(CS, DeoptValues, Holders);
2300ff0cc061SDimitry Andric   }
2301ff0cc061SDimitry Andric 
23027d523365SDimitry Andric   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2303ff0cc061SDimitry Andric 
23047d523365SDimitry Andric   // A) Identify all gc pointers which are statically live at the given call
2305ff0cc061SDimitry Andric   // site.
23067d523365SDimitry Andric   findLiveReferences(F, DT, ToUpdate, Records);
2307ff0cc061SDimitry Andric 
2308ff0cc061SDimitry Andric   // B) Find the base pointers for each live pointer
2309ff0cc061SDimitry Andric   /* scope for caching */ {
2310ff0cc061SDimitry Andric     // Cache the 'defining value' relation used in the computation and
2311ff0cc061SDimitry Andric     // insertion of base phis and selects.  This ensures that we don't insert
2312ff0cc061SDimitry Andric     // large numbers of duplicate base_phis.
2313ff0cc061SDimitry Andric     DefiningValueMapTy DVCache;
2314ff0cc061SDimitry Andric 
23157d523365SDimitry Andric     for (size_t i = 0; i < Records.size(); i++) {
23167d523365SDimitry Andric       PartiallyConstructedSafepointRecord &info = Records[i];
23177d523365SDimitry Andric       findBasePointers(DT, DVCache, ToUpdate[i], info);
2318ff0cc061SDimitry Andric     }
2319ff0cc061SDimitry Andric   } // end of cache scope
2320ff0cc061SDimitry Andric 
2321ff0cc061SDimitry Andric   // The base phi insertion logic (for any safepoint) may have inserted new
2322ff0cc061SDimitry Andric   // instructions which are now live at some safepoint.  The simplest such
2323ff0cc061SDimitry Andric   // example is:
2324ff0cc061SDimitry Andric   // loop:
2325ff0cc061SDimitry Andric   //   phi a  <-- will be a new base_phi here
2326ff0cc061SDimitry Andric   //   safepoint 1 <-- that needs to be live here
2327ff0cc061SDimitry Andric   //   gep a + 1
2328ff0cc061SDimitry Andric   //   safepoint 2
2329ff0cc061SDimitry Andric   //   br loop
2330ff0cc061SDimitry Andric   // We insert some dummy calls after each safepoint to definitely hold live
2331ff0cc061SDimitry Andric   // the base pointers which were identified for that safepoint.  We'll then
2332ff0cc061SDimitry Andric   // ask liveness for _every_ base inserted to see what is now live.  Then we
2333ff0cc061SDimitry Andric   // remove the dummy calls.
23347d523365SDimitry Andric   Holders.reserve(Holders.size() + Records.size());
23357d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
23367d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
2337ff0cc061SDimitry Andric 
2338ff0cc061SDimitry Andric     SmallVector<Value *, 128> Bases;
23397d523365SDimitry Andric     for (auto Pair : Info.PointerToBase)
2340ff0cc061SDimitry Andric       Bases.push_back(Pair.second);
23417d523365SDimitry Andric 
23427d523365SDimitry Andric     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2343ff0cc061SDimitry Andric   }
2344ff0cc061SDimitry Andric 
2345ff0cc061SDimitry Andric   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2346ff0cc061SDimitry Andric   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2347ff0cc061SDimitry Andric   // not the key issue.
23487d523365SDimitry Andric   recomputeLiveInValues(F, DT, ToUpdate, Records);
2349ff0cc061SDimitry Andric 
2350ff0cc061SDimitry Andric   if (PrintBasePointers) {
23517d523365SDimitry Andric     for (auto &Info : Records) {
2352ff0cc061SDimitry Andric       errs() << "Base Pairs: (w/Relocation)\n";
23537d523365SDimitry Andric       for (auto Pair : Info.PointerToBase) {
23547d523365SDimitry Andric         errs() << " derived ";
23557d523365SDimitry Andric         Pair.first->printAsOperand(errs(), false);
23567d523365SDimitry Andric         errs() << " base ";
23577d523365SDimitry Andric         Pair.second->printAsOperand(errs(), false);
23587d523365SDimitry Andric         errs() << "\n";
2359ff0cc061SDimitry Andric       }
2360ff0cc061SDimitry Andric     }
2361ff0cc061SDimitry Andric   }
23627d523365SDimitry Andric 
23637d523365SDimitry Andric   // It is possible that non-constant live variables have a constant base.  For
23647d523365SDimitry Andric   // example, a GEP with a variable offset from a global.  In this case we can
23657d523365SDimitry Andric   // remove it from the liveset.  We already don't add constants to the liveset
23667d523365SDimitry Andric   // because we assume they won't move at runtime and the GC doesn't need to be
23677d523365SDimitry Andric   // informed about them.  The same reasoning applies if the base is constant.
23687d523365SDimitry Andric   // Note that the relocation placement code relies on this filtering for
23697d523365SDimitry Andric   // correctness as it expects the base to be in the liveset, which isn't true
23707d523365SDimitry Andric   // if the base is constant.
23717d523365SDimitry Andric   for (auto &Info : Records)
23727d523365SDimitry Andric     for (auto &BasePair : Info.PointerToBase)
23737d523365SDimitry Andric       if (isa<Constant>(BasePair.second))
23747d523365SDimitry Andric         Info.LiveSet.erase(BasePair.first);
23757d523365SDimitry Andric 
23767d523365SDimitry Andric   for (CallInst *CI : Holders)
23777d523365SDimitry Andric     CI->eraseFromParent();
23787d523365SDimitry Andric 
23797d523365SDimitry Andric   Holders.clear();
2380ff0cc061SDimitry Andric 
23813dac3a9bSDimitry Andric   // Do a limited scalarization of any live at safepoint vector values which
23823dac3a9bSDimitry Andric   // contain pointers.  This enables this pass to run after vectorization at
23833dac3a9bSDimitry Andric   // the cost of some possible performance loss.  TODO: it would be nice to
23843dac3a9bSDimitry Andric   // natively support vectors all the way through the backend so we don't need
23853dac3a9bSDimitry Andric   // to scalarize here.
23867d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
23877d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
23887d523365SDimitry Andric     Instruction *Statepoint = ToUpdate[i].getInstruction();
23897d523365SDimitry Andric     splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
23907d523365SDimitry Andric                       Info.PointerToBase, DT);
23913dac3a9bSDimitry Andric   }
23923dac3a9bSDimitry Andric 
2393ff0cc061SDimitry Andric   // In order to reduce live set of statepoint we might choose to rematerialize
23947d523365SDimitry Andric   // some values instead of relocating them. This is purely an optimization and
2395ff0cc061SDimitry Andric   // does not influence correctness.
23967d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
23977d523365SDimitry Andric     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2398ff0cc061SDimitry Andric 
23997d523365SDimitry Andric   // We need this to safely RAUW and delete call or invoke return values that
24007d523365SDimitry Andric   // may themselves be live over a statepoint.  For details, please see usage in
24017d523365SDimitry Andric   // makeStatepointExplicitImpl.
24027d523365SDimitry Andric   std::vector<DeferredReplacement> Replacements;
2403ff0cc061SDimitry Andric 
2404ff0cc061SDimitry Andric   // Now run through and replace the existing statepoints with new ones with
2405ff0cc061SDimitry Andric   // the live variables listed.  We do not yet update uses of the values being
2406ff0cc061SDimitry Andric   // relocated. We have references to live variables that need to
2407ff0cc061SDimitry Andric   // survive to the last iteration of this loop.  (By construction, the
2408ff0cc061SDimitry Andric   // previous statepoint can not be a live variable, thus we can and remove
2409ff0cc061SDimitry Andric   // the old statepoint calls as we go.)
24107d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
24117d523365SDimitry Andric     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
24127d523365SDimitry Andric 
24137d523365SDimitry Andric   ToUpdate.clear(); // prevent accident use of invalid CallSites
24147d523365SDimitry Andric 
24157d523365SDimitry Andric   for (auto &PR : Replacements)
24167d523365SDimitry Andric     PR.doReplacement();
24177d523365SDimitry Andric 
24187d523365SDimitry Andric   Replacements.clear();
24197d523365SDimitry Andric 
24207d523365SDimitry Andric   for (auto &Info : Records) {
24217d523365SDimitry Andric     // These live sets may contain state Value pointers, since we replaced calls
24227d523365SDimitry Andric     // with operand bundles with calls wrapped in gc.statepoint, and some of
24237d523365SDimitry Andric     // those calls may have been def'ing live gc pointers.  Clear these out to
24247d523365SDimitry Andric     // avoid accidentally using them.
24257d523365SDimitry Andric     //
24267d523365SDimitry Andric     // TODO: We should create a separate data structure that does not contain
24277d523365SDimitry Andric     // these live sets, and migrate to using that data structure from this point
24287d523365SDimitry Andric     // onward.
24297d523365SDimitry Andric     Info.LiveSet.clear();
24307d523365SDimitry Andric     Info.PointerToBase.clear();
2431ff0cc061SDimitry Andric   }
2432ff0cc061SDimitry Andric 
2433ff0cc061SDimitry Andric   // Do all the fixups of the original live variables to their relocated selves
24347d523365SDimitry Andric   SmallVector<Value *, 128> Live;
24357d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
24367d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
24377d523365SDimitry Andric 
2438ff0cc061SDimitry Andric     // We can't simply save the live set from the original insertion.  One of
2439ff0cc061SDimitry Andric     // the live values might be the result of a call which needs a safepoint.
2440ff0cc061SDimitry Andric     // That Value* no longer exists and we need to use the new gc_result.
2441ff0cc061SDimitry Andric     // Thankfully, the live set is embedded in the statepoint (and updated), so
2442ff0cc061SDimitry Andric     // we just grab that.
24437d523365SDimitry Andric     Statepoint Statepoint(Info.StatepointToken);
24447d523365SDimitry Andric     Live.insert(Live.end(), Statepoint.gc_args_begin(),
24457d523365SDimitry Andric                 Statepoint.gc_args_end());
2446ff0cc061SDimitry Andric #ifndef NDEBUG
2447ff0cc061SDimitry Andric     // Do some basic sanity checks on our liveness results before performing
2448ff0cc061SDimitry Andric     // relocation.  Relocation can and will turn mistakes in liveness results
2449ff0cc061SDimitry Andric     // into non-sensical code which is must harder to debug.
2450ff0cc061SDimitry Andric     // TODO: It would be nice to test consistency as well
24517d523365SDimitry Andric     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2452ff0cc061SDimitry Andric            "statepoint must be reachable or liveness is meaningless");
24537d523365SDimitry Andric     for (Value *V : Statepoint.gc_args()) {
2454ff0cc061SDimitry Andric       if (!isa<Instruction>(V))
2455ff0cc061SDimitry Andric         // Non-instruction values trivial dominate all possible uses
2456ff0cc061SDimitry Andric         continue;
24577d523365SDimitry Andric       auto *LiveInst = cast<Instruction>(V);
2458ff0cc061SDimitry Andric       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2459ff0cc061SDimitry Andric              "unreachable values should never be live");
24607d523365SDimitry Andric       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2461ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2462ff0cc061SDimitry Andric     }
2463ff0cc061SDimitry Andric #endif
2464ff0cc061SDimitry Andric   }
24657d523365SDimitry Andric   unique_unsorted(Live);
2466ff0cc061SDimitry Andric 
2467ff0cc061SDimitry Andric #ifndef NDEBUG
2468ff0cc061SDimitry Andric   // sanity check
24697d523365SDimitry Andric   for (auto *Ptr : Live)
24707d523365SDimitry Andric     assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
2471ff0cc061SDimitry Andric #endif
2472ff0cc061SDimitry Andric 
24737d523365SDimitry Andric   relocationViaAlloca(F, DT, Live, Records);
24747d523365SDimitry Andric   return !Records.empty();
2475ff0cc061SDimitry Andric }
2476ff0cc061SDimitry Andric 
247797bc6c73SDimitry Andric // Handles both return values and arguments for Functions and CallSites.
247897bc6c73SDimitry Andric template <typename AttrHolder>
24797d523365SDimitry Andric static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
248097bc6c73SDimitry Andric                                       unsigned Index) {
248197bc6c73SDimitry Andric   AttrBuilder R;
248297bc6c73SDimitry Andric   if (AH.getDereferenceableBytes(Index))
248397bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
248497bc6c73SDimitry Andric                                   AH.getDereferenceableBytes(Index)));
248597bc6c73SDimitry Andric   if (AH.getDereferenceableOrNullBytes(Index))
248697bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
248797bc6c73SDimitry Andric                                   AH.getDereferenceableOrNullBytes(Index)));
24887d523365SDimitry Andric   if (AH.doesNotAlias(Index))
24897d523365SDimitry Andric     R.addAttribute(Attribute::NoAlias);
249097bc6c73SDimitry Andric 
249197bc6c73SDimitry Andric   if (!R.empty())
249297bc6c73SDimitry Andric     AH.setAttributes(AH.getAttributes().removeAttributes(
249397bc6c73SDimitry Andric         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
249497bc6c73SDimitry Andric }
249597bc6c73SDimitry Andric 
249697bc6c73SDimitry Andric void
24977d523365SDimitry Andric RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
249897bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
249997bc6c73SDimitry Andric 
250097bc6c73SDimitry Andric   for (Argument &A : F.args())
250197bc6c73SDimitry Andric     if (isa<PointerType>(A.getType()))
25027d523365SDimitry Andric       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
250397bc6c73SDimitry Andric 
250497bc6c73SDimitry Andric   if (isa<PointerType>(F.getReturnType()))
25057d523365SDimitry Andric     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
250697bc6c73SDimitry Andric }
250797bc6c73SDimitry Andric 
25087d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
250997bc6c73SDimitry Andric   if (F.empty())
251097bc6c73SDimitry Andric     return;
251197bc6c73SDimitry Andric 
251297bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
251397bc6c73SDimitry Andric   MDBuilder Builder(Ctx);
251497bc6c73SDimitry Andric 
25157d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
251697bc6c73SDimitry Andric     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
251797bc6c73SDimitry Andric       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
251897bc6c73SDimitry Andric       bool IsImmutableTBAA =
251997bc6c73SDimitry Andric           MD->getNumOperands() == 4 &&
252097bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
252197bc6c73SDimitry Andric 
252297bc6c73SDimitry Andric       if (!IsImmutableTBAA)
252397bc6c73SDimitry Andric         continue; // no work to do, MD_tbaa is already marked mutable
252497bc6c73SDimitry Andric 
252597bc6c73SDimitry Andric       MDNode *Base = cast<MDNode>(MD->getOperand(0));
252697bc6c73SDimitry Andric       MDNode *Access = cast<MDNode>(MD->getOperand(1));
252797bc6c73SDimitry Andric       uint64_t Offset =
252897bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
252997bc6c73SDimitry Andric 
253097bc6c73SDimitry Andric       MDNode *MutableTBAA =
253197bc6c73SDimitry Andric           Builder.createTBAAStructTagNode(Base, Access, Offset);
253297bc6c73SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
253397bc6c73SDimitry Andric     }
253497bc6c73SDimitry Andric 
253597bc6c73SDimitry Andric     if (CallSite CS = CallSite(&I)) {
253697bc6c73SDimitry Andric       for (int i = 0, e = CS.arg_size(); i != e; i++)
253797bc6c73SDimitry Andric         if (isa<PointerType>(CS.getArgument(i)->getType()))
25387d523365SDimitry Andric           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
253997bc6c73SDimitry Andric       if (isa<PointerType>(CS.getType()))
25407d523365SDimitry Andric         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
254197bc6c73SDimitry Andric     }
254297bc6c73SDimitry Andric   }
254397bc6c73SDimitry Andric }
254497bc6c73SDimitry Andric 
2545ff0cc061SDimitry Andric /// Returns true if this function should be rewritten by this pass.  The main
2546ff0cc061SDimitry Andric /// point of this function is as an extension point for custom logic.
2547ff0cc061SDimitry Andric static bool shouldRewriteStatepointsIn(Function &F) {
2548ff0cc061SDimitry Andric   // TODO: This should check the GCStrategy
2549ff0cc061SDimitry Andric   if (F.hasGC()) {
2550ff0cc061SDimitry Andric     const char *FunctionGCName = F.getGC();
2551ff0cc061SDimitry Andric     const StringRef StatepointExampleName("statepoint-example");
2552ff0cc061SDimitry Andric     const StringRef CoreCLRName("coreclr");
2553ff0cc061SDimitry Andric     return (StatepointExampleName == FunctionGCName) ||
2554ff0cc061SDimitry Andric            (CoreCLRName == FunctionGCName);
2555ff0cc061SDimitry Andric   } else
2556ff0cc061SDimitry Andric     return false;
2557ff0cc061SDimitry Andric }
2558ff0cc061SDimitry Andric 
25597d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
256097bc6c73SDimitry Andric #ifndef NDEBUG
256197bc6c73SDimitry Andric   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
256297bc6c73SDimitry Andric          "precondition!");
256397bc6c73SDimitry Andric #endif
256497bc6c73SDimitry Andric 
256597bc6c73SDimitry Andric   for (Function &F : M)
25667d523365SDimitry Andric     stripNonValidAttributesFromPrototype(F);
256797bc6c73SDimitry Andric 
256897bc6c73SDimitry Andric   for (Function &F : M)
25697d523365SDimitry Andric     stripNonValidAttributesFromBody(F);
257097bc6c73SDimitry Andric }
257197bc6c73SDimitry Andric 
2572ff0cc061SDimitry Andric bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2573ff0cc061SDimitry Andric   // Nothing to do for declarations.
2574ff0cc061SDimitry Andric   if (F.isDeclaration() || F.empty())
2575ff0cc061SDimitry Andric     return false;
2576ff0cc061SDimitry Andric 
2577ff0cc061SDimitry Andric   // Policy choice says not to rewrite - the most common reason is that we're
2578ff0cc061SDimitry Andric   // compiling code without a GCStrategy.
2579ff0cc061SDimitry Andric   if (!shouldRewriteStatepointsIn(F))
2580ff0cc061SDimitry Andric     return false;
2581ff0cc061SDimitry Andric 
258297bc6c73SDimitry Andric   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
25837d523365SDimitry Andric   TargetTransformInfo &TTI =
25847d523365SDimitry Andric       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
25857d523365SDimitry Andric 
25867d523365SDimitry Andric   auto NeedsRewrite = [](Instruction &I) {
25877d523365SDimitry Andric     if (UseDeoptBundles) {
25887d523365SDimitry Andric       if (ImmutableCallSite CS = ImmutableCallSite(&I))
25897d523365SDimitry Andric         return !callsGCLeafFunction(CS);
25907d523365SDimitry Andric       return false;
25917d523365SDimitry Andric     }
25927d523365SDimitry Andric 
25937d523365SDimitry Andric     return isStatepoint(I);
25947d523365SDimitry Andric   };
2595ff0cc061SDimitry Andric 
2596ff0cc061SDimitry Andric   // Gather all the statepoints which need rewritten.  Be careful to only
2597ff0cc061SDimitry Andric   // consider those in reachable code since we need to ask dominance queries
2598ff0cc061SDimitry Andric   // when rewriting.  We'll delete the unreachable ones in a moment.
2599ff0cc061SDimitry Andric   SmallVector<CallSite, 64> ParsePointNeeded;
2600ff0cc061SDimitry Andric   bool HasUnreachableStatepoint = false;
26017d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
2602ff0cc061SDimitry Andric     // TODO: only the ones with the flag set!
26037d523365SDimitry Andric     if (NeedsRewrite(I)) {
2604ff0cc061SDimitry Andric       if (DT.isReachableFromEntry(I.getParent()))
2605ff0cc061SDimitry Andric         ParsePointNeeded.push_back(CallSite(&I));
2606ff0cc061SDimitry Andric       else
2607ff0cc061SDimitry Andric         HasUnreachableStatepoint = true;
2608ff0cc061SDimitry Andric     }
2609ff0cc061SDimitry Andric   }
2610ff0cc061SDimitry Andric 
2611ff0cc061SDimitry Andric   bool MadeChange = false;
2612ff0cc061SDimitry Andric 
2613ff0cc061SDimitry Andric   // Delete any unreachable statepoints so that we don't have unrewritten
2614ff0cc061SDimitry Andric   // statepoints surviving this pass.  This makes testing easier and the
2615ff0cc061SDimitry Andric   // resulting IR less confusing to human readers.  Rather than be fancy, we
2616ff0cc061SDimitry Andric   // just reuse a utility function which removes the unreachable blocks.
2617ff0cc061SDimitry Andric   if (HasUnreachableStatepoint)
2618ff0cc061SDimitry Andric     MadeChange |= removeUnreachableBlocks(F);
2619ff0cc061SDimitry Andric 
2620ff0cc061SDimitry Andric   // Return early if no work to do.
2621ff0cc061SDimitry Andric   if (ParsePointNeeded.empty())
2622ff0cc061SDimitry Andric     return MadeChange;
2623ff0cc061SDimitry Andric 
2624ff0cc061SDimitry Andric   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2625ff0cc061SDimitry Andric   // These are created by LCSSA.  They have the effect of increasing the size
2626ff0cc061SDimitry Andric   // of liveness sets for no good reason.  It may be harder to do this post
2627ff0cc061SDimitry Andric   // insertion since relocations and base phis can confuse things.
2628ff0cc061SDimitry Andric   for (BasicBlock &BB : F)
2629ff0cc061SDimitry Andric     if (BB.getUniquePredecessor()) {
2630ff0cc061SDimitry Andric       MadeChange = true;
2631ff0cc061SDimitry Andric       FoldSingleEntryPHINodes(&BB);
2632ff0cc061SDimitry Andric     }
2633ff0cc061SDimitry Andric 
26347d523365SDimitry Andric   // Before we start introducing relocations, we want to tweak the IR a bit to
26357d523365SDimitry Andric   // avoid unfortunate code generation effects.  The main example is that we
26367d523365SDimitry Andric   // want to try to make sure the comparison feeding a branch is after any
26377d523365SDimitry Andric   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
26387d523365SDimitry Andric   // values feeding a branch after relocation.  This is semantically correct,
26397d523365SDimitry Andric   // but results in extra register pressure since both the pre-relocation and
26407d523365SDimitry Andric   // post-relocation copies must be available in registers.  For code without
26417d523365SDimitry Andric   // relocations this is handled elsewhere, but teaching the scheduler to
26427d523365SDimitry Andric   // reverse the transform we're about to do would be slightly complex.
26437d523365SDimitry Andric   // Note: This may extend the live range of the inputs to the icmp and thus
26447d523365SDimitry Andric   // increase the liveset of any statepoint we move over.  This is profitable
26457d523365SDimitry Andric   // as long as all statepoints are in rare blocks.  If we had in-register
26467d523365SDimitry Andric   // lowering for live values this would be a much safer transform.
26477d523365SDimitry Andric   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
26487d523365SDimitry Andric     if (auto *BI = dyn_cast<BranchInst>(TI))
26497d523365SDimitry Andric       if (BI->isConditional())
26507d523365SDimitry Andric         return dyn_cast<Instruction>(BI->getCondition());
26517d523365SDimitry Andric     // TODO: Extend this to handle switches
26527d523365SDimitry Andric     return nullptr;
26537d523365SDimitry Andric   };
26547d523365SDimitry Andric   for (BasicBlock &BB : F) {
26557d523365SDimitry Andric     TerminatorInst *TI = BB.getTerminator();
26567d523365SDimitry Andric     if (auto *Cond = getConditionInst(TI))
26577d523365SDimitry Andric       // TODO: Handle more than just ICmps here.  We should be able to move
26587d523365SDimitry Andric       // most instructions without side effects or memory access.
26597d523365SDimitry Andric       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
26607d523365SDimitry Andric         MadeChange = true;
26617d523365SDimitry Andric         Cond->moveBefore(TI);
26627d523365SDimitry Andric       }
26637d523365SDimitry Andric   }
26647d523365SDimitry Andric 
26657d523365SDimitry Andric   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2666ff0cc061SDimitry Andric   return MadeChange;
2667ff0cc061SDimitry Andric }
2668ff0cc061SDimitry Andric 
2669ff0cc061SDimitry Andric // liveness computation via standard dataflow
2670ff0cc061SDimitry Andric // -------------------------------------------------------------------
2671ff0cc061SDimitry Andric 
2672ff0cc061SDimitry Andric // TODO: Consider using bitvectors for liveness, the set of potentially
2673ff0cc061SDimitry Andric // interesting values should be small and easy to pre-compute.
2674ff0cc061SDimitry Andric 
2675ff0cc061SDimitry Andric /// Compute the live-in set for the location rbegin starting from
2676ff0cc061SDimitry Andric /// the live-out set of the basic block
2677ff0cc061SDimitry Andric static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2678ff0cc061SDimitry Andric                                 BasicBlock::reverse_iterator rend,
2679ff0cc061SDimitry Andric                                 DenseSet<Value *> &LiveTmp) {
2680ff0cc061SDimitry Andric 
2681ff0cc061SDimitry Andric   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2682ff0cc061SDimitry Andric     Instruction *I = &*ritr;
2683ff0cc061SDimitry Andric 
2684ff0cc061SDimitry Andric     // KILL/Def - Remove this definition from LiveIn
2685ff0cc061SDimitry Andric     LiveTmp.erase(I);
2686ff0cc061SDimitry Andric 
2687ff0cc061SDimitry Andric     // Don't consider *uses* in PHI nodes, we handle their contribution to
2688ff0cc061SDimitry Andric     // predecessor blocks when we seed the LiveOut sets
2689ff0cc061SDimitry Andric     if (isa<PHINode>(I))
2690ff0cc061SDimitry Andric       continue;
2691ff0cc061SDimitry Andric 
2692ff0cc061SDimitry Andric     // USE - Add to the LiveIn set for this instruction
2693ff0cc061SDimitry Andric     for (Value *V : I->operands()) {
2694ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2695ff0cc061SDimitry Andric              "support for FCA unimplemented");
2696ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2697ff0cc061SDimitry Andric         // The choice to exclude all things constant here is slightly subtle.
26987d523365SDimitry Andric         // There are two independent reasons:
2699ff0cc061SDimitry Andric         // - We assume that things which are constant (from LLVM's definition)
2700ff0cc061SDimitry Andric         // do not move at runtime.  For example, the address of a global
2701ff0cc061SDimitry Andric         // variable is fixed, even though it's contents may not be.
2702ff0cc061SDimitry Andric         // - Second, we can't disallow arbitrary inttoptr constants even
2703ff0cc061SDimitry Andric         // if the language frontend does.  Optimization passes are free to
2704ff0cc061SDimitry Andric         // locally exploit facts without respect to global reachability.  This
2705ff0cc061SDimitry Andric         // can create sections of code which are dynamically unreachable and
2706ff0cc061SDimitry Andric         // contain just about anything.  (see constants.ll in tests)
2707ff0cc061SDimitry Andric         LiveTmp.insert(V);
2708ff0cc061SDimitry Andric       }
2709ff0cc061SDimitry Andric     }
2710ff0cc061SDimitry Andric   }
2711ff0cc061SDimitry Andric }
2712ff0cc061SDimitry Andric 
2713ff0cc061SDimitry Andric static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2714ff0cc061SDimitry Andric 
2715ff0cc061SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
2716ff0cc061SDimitry Andric     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2717ff0cc061SDimitry Andric     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2718ff0cc061SDimitry Andric       PHINode *Phi = cast<PHINode>(&*I);
2719ff0cc061SDimitry Andric       Value *V = Phi->getIncomingValueForBlock(BB);
2720ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2721ff0cc061SDimitry Andric              "support for FCA unimplemented");
2722ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2723ff0cc061SDimitry Andric         LiveTmp.insert(V);
2724ff0cc061SDimitry Andric       }
2725ff0cc061SDimitry Andric     }
2726ff0cc061SDimitry Andric   }
2727ff0cc061SDimitry Andric }
2728ff0cc061SDimitry Andric 
2729ff0cc061SDimitry Andric static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2730ff0cc061SDimitry Andric   DenseSet<Value *> KillSet;
2731ff0cc061SDimitry Andric   for (Instruction &I : *BB)
2732ff0cc061SDimitry Andric     if (isHandledGCPointerType(I.getType()))
2733ff0cc061SDimitry Andric       KillSet.insert(&I);
2734ff0cc061SDimitry Andric   return KillSet;
2735ff0cc061SDimitry Andric }
2736ff0cc061SDimitry Andric 
2737ff0cc061SDimitry Andric #ifndef NDEBUG
2738ff0cc061SDimitry Andric /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2739ff0cc061SDimitry Andric /// sanity check for the liveness computation.
2740ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2741ff0cc061SDimitry Andric                           TerminatorInst *TI, bool TermOkay = false) {
2742ff0cc061SDimitry Andric   for (Value *V : Live) {
2743ff0cc061SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V)) {
2744ff0cc061SDimitry Andric       // The terminator can be a member of the LiveOut set.  LLVM's definition
2745ff0cc061SDimitry Andric       // of instruction dominance states that V does not dominate itself.  As
2746ff0cc061SDimitry Andric       // such, we need to special case this to allow it.
2747ff0cc061SDimitry Andric       if (TermOkay && TI == I)
2748ff0cc061SDimitry Andric         continue;
2749ff0cc061SDimitry Andric       assert(DT.dominates(I, TI) &&
2750ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2751ff0cc061SDimitry Andric     }
2752ff0cc061SDimitry Andric   }
2753ff0cc061SDimitry Andric }
2754ff0cc061SDimitry Andric 
2755ff0cc061SDimitry Andric /// Check that all the liveness sets used during the computation of liveness
2756ff0cc061SDimitry Andric /// obey basic SSA properties.  This is useful for finding cases where we miss
2757ff0cc061SDimitry Andric /// a def.
2758ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2759ff0cc061SDimitry Andric                           BasicBlock &BB) {
2760ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2761ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2762ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2763ff0cc061SDimitry Andric }
2764ff0cc061SDimitry Andric #endif
2765ff0cc061SDimitry Andric 
2766ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
2767ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data) {
2768ff0cc061SDimitry Andric 
2769ff0cc061SDimitry Andric   SmallSetVector<BasicBlock *, 200> Worklist;
2770ff0cc061SDimitry Andric   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2771ff0cc061SDimitry Andric     // We use a SetVector so that we don't have duplicates in the worklist.
2772ff0cc061SDimitry Andric     Worklist.insert(pred_begin(BB), pred_end(BB));
2773ff0cc061SDimitry Andric   };
2774ff0cc061SDimitry Andric   auto NextItem = [&]() {
2775ff0cc061SDimitry Andric     BasicBlock *BB = Worklist.back();
2776ff0cc061SDimitry Andric     Worklist.pop_back();
2777ff0cc061SDimitry Andric     return BB;
2778ff0cc061SDimitry Andric   };
2779ff0cc061SDimitry Andric 
2780ff0cc061SDimitry Andric   // Seed the liveness for each individual block
2781ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2782ff0cc061SDimitry Andric     Data.KillSet[&BB] = computeKillSet(&BB);
2783ff0cc061SDimitry Andric     Data.LiveSet[&BB].clear();
2784ff0cc061SDimitry Andric     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2785ff0cc061SDimitry Andric 
2786ff0cc061SDimitry Andric #ifndef NDEBUG
2787ff0cc061SDimitry Andric     for (Value *Kill : Data.KillSet[&BB])
2788ff0cc061SDimitry Andric       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2789ff0cc061SDimitry Andric #endif
2790ff0cc061SDimitry Andric 
2791ff0cc061SDimitry Andric     Data.LiveOut[&BB] = DenseSet<Value *>();
2792ff0cc061SDimitry Andric     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2793ff0cc061SDimitry Andric     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2794ff0cc061SDimitry Andric     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2795ff0cc061SDimitry Andric     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2796ff0cc061SDimitry Andric     if (!Data.LiveIn[&BB].empty())
2797ff0cc061SDimitry Andric       AddPredsToWorklist(&BB);
2798ff0cc061SDimitry Andric   }
2799ff0cc061SDimitry Andric 
2800ff0cc061SDimitry Andric   // Propagate that liveness until stable
2801ff0cc061SDimitry Andric   while (!Worklist.empty()) {
2802ff0cc061SDimitry Andric     BasicBlock *BB = NextItem();
2803ff0cc061SDimitry Andric 
2804ff0cc061SDimitry Andric     // Compute our new liveout set, then exit early if it hasn't changed
2805ff0cc061SDimitry Andric     // despite the contribution of our successor.
2806ff0cc061SDimitry Andric     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2807ff0cc061SDimitry Andric     const auto OldLiveOutSize = LiveOut.size();
2808ff0cc061SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
2809ff0cc061SDimitry Andric       assert(Data.LiveIn.count(Succ));
2810ff0cc061SDimitry Andric       set_union(LiveOut, Data.LiveIn[Succ]);
2811ff0cc061SDimitry Andric     }
2812ff0cc061SDimitry Andric     // assert OutLiveOut is a subset of LiveOut
2813ff0cc061SDimitry Andric     if (OldLiveOutSize == LiveOut.size()) {
2814ff0cc061SDimitry Andric       // If the sets are the same size, then we didn't actually add anything
2815ff0cc061SDimitry Andric       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2816ff0cc061SDimitry Andric       // hasn't changed.
2817ff0cc061SDimitry Andric       continue;
2818ff0cc061SDimitry Andric     }
2819ff0cc061SDimitry Andric     Data.LiveOut[BB] = LiveOut;
2820ff0cc061SDimitry Andric 
2821ff0cc061SDimitry Andric     // Apply the effects of this basic block
2822ff0cc061SDimitry Andric     DenseSet<Value *> LiveTmp = LiveOut;
2823ff0cc061SDimitry Andric     set_union(LiveTmp, Data.LiveSet[BB]);
2824ff0cc061SDimitry Andric     set_subtract(LiveTmp, Data.KillSet[BB]);
2825ff0cc061SDimitry Andric 
2826ff0cc061SDimitry Andric     assert(Data.LiveIn.count(BB));
2827ff0cc061SDimitry Andric     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2828ff0cc061SDimitry Andric     // assert: OldLiveIn is a subset of LiveTmp
2829ff0cc061SDimitry Andric     if (OldLiveIn.size() != LiveTmp.size()) {
2830ff0cc061SDimitry Andric       Data.LiveIn[BB] = LiveTmp;
2831ff0cc061SDimitry Andric       AddPredsToWorklist(BB);
2832ff0cc061SDimitry Andric     }
2833ff0cc061SDimitry Andric   } // while( !worklist.empty() )
2834ff0cc061SDimitry Andric 
2835ff0cc061SDimitry Andric #ifndef NDEBUG
28367d523365SDimitry Andric   // Sanity check our output against SSA properties.  This helps catch any
2837ff0cc061SDimitry Andric   // missing kills during the above iteration.
2838ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2839ff0cc061SDimitry Andric     checkBasicSSA(DT, Data, BB);
2840ff0cc061SDimitry Andric   }
2841ff0cc061SDimitry Andric #endif
2842ff0cc061SDimitry Andric }
2843ff0cc061SDimitry Andric 
2844ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2845ff0cc061SDimitry Andric                               StatepointLiveSetTy &Out) {
2846ff0cc061SDimitry Andric 
2847ff0cc061SDimitry Andric   BasicBlock *BB = Inst->getParent();
2848ff0cc061SDimitry Andric 
2849ff0cc061SDimitry Andric   // Note: The copy is intentional and required
2850ff0cc061SDimitry Andric   assert(Data.LiveOut.count(BB));
2851ff0cc061SDimitry Andric   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2852ff0cc061SDimitry Andric 
2853ff0cc061SDimitry Andric   // We want to handle the statepoint itself oddly.  It's
2854ff0cc061SDimitry Andric   // call result is not live (normal), nor are it's arguments
2855ff0cc061SDimitry Andric   // (unless they're used again later).  This adjustment is
2856ff0cc061SDimitry Andric   // specifically what we need to relocate
28577d523365SDimitry Andric   BasicBlock::reverse_iterator rend(Inst->getIterator());
2858ff0cc061SDimitry Andric   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2859ff0cc061SDimitry Andric   LiveOut.erase(Inst);
2860ff0cc061SDimitry Andric   Out.insert(LiveOut.begin(), LiveOut.end());
2861ff0cc061SDimitry Andric }
2862ff0cc061SDimitry Andric 
2863ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2864ff0cc061SDimitry Andric                                   const CallSite &CS,
2865ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &Info) {
2866ff0cc061SDimitry Andric   Instruction *Inst = CS.getInstruction();
2867ff0cc061SDimitry Andric   StatepointLiveSetTy Updated;
2868ff0cc061SDimitry Andric   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2869ff0cc061SDimitry Andric 
2870ff0cc061SDimitry Andric #ifndef NDEBUG
2871ff0cc061SDimitry Andric   DenseSet<Value *> Bases;
2872ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase) {
2873ff0cc061SDimitry Andric     Bases.insert(KVPair.second);
2874ff0cc061SDimitry Andric   }
2875ff0cc061SDimitry Andric #endif
2876ff0cc061SDimitry Andric   // We may have base pointers which are now live that weren't before.  We need
2877ff0cc061SDimitry Andric   // to update the PointerToBase structure to reflect this.
2878ff0cc061SDimitry Andric   for (auto V : Updated)
2879ff0cc061SDimitry Andric     if (!Info.PointerToBase.count(V)) {
2880ff0cc061SDimitry Andric       assert(Bases.count(V) && "can't find base for unexpected live value");
2881ff0cc061SDimitry Andric       Info.PointerToBase[V] = V;
2882ff0cc061SDimitry Andric       continue;
2883ff0cc061SDimitry Andric     }
2884ff0cc061SDimitry Andric 
2885ff0cc061SDimitry Andric #ifndef NDEBUG
2886ff0cc061SDimitry Andric   for (auto V : Updated) {
2887ff0cc061SDimitry Andric     assert(Info.PointerToBase.count(V) &&
2888ff0cc061SDimitry Andric            "must be able to find base for live value");
2889ff0cc061SDimitry Andric   }
2890ff0cc061SDimitry Andric #endif
2891ff0cc061SDimitry Andric 
2892ff0cc061SDimitry Andric   // Remove any stale base mappings - this can happen since our liveness is
2893ff0cc061SDimitry Andric   // more precise then the one inherent in the base pointer analysis
2894ff0cc061SDimitry Andric   DenseSet<Value *> ToErase;
2895ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2896ff0cc061SDimitry Andric     if (!Updated.count(KVPair.first))
2897ff0cc061SDimitry Andric       ToErase.insert(KVPair.first);
2898ff0cc061SDimitry Andric   for (auto V : ToErase)
2899ff0cc061SDimitry Andric     Info.PointerToBase.erase(V);
2900ff0cc061SDimitry Andric 
2901ff0cc061SDimitry Andric #ifndef NDEBUG
2902ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2903ff0cc061SDimitry Andric     assert(Updated.count(KVPair.first) && "record for non-live value");
2904ff0cc061SDimitry Andric #endif
2905ff0cc061SDimitry Andric 
29067d523365SDimitry Andric   Info.LiveSet = Updated;
2907ff0cc061SDimitry Andric }
2908