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 
431ff0cc061SDimitry Andric   if (isa<GlobalVariable>(I))
432ff0cc061SDimitry Andric     // base case
4337d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
434ff0cc061SDimitry Andric 
435ff0cc061SDimitry Andric   // inlining could possibly introduce phi node that contains
436ff0cc061SDimitry Andric   // undef if callee has multiple returns
437ff0cc061SDimitry Andric   if (isa<UndefValue>(I))
438ff0cc061SDimitry Andric     // utterly meaningless, but useful for dealing with
439ff0cc061SDimitry Andric     // partially optimized code.
4407d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
441ff0cc061SDimitry Andric 
442ff0cc061SDimitry Andric   // Due to inheritance, this must be _after_ the global variable and undef
443ff0cc061SDimitry Andric   // checks
4447d523365SDimitry Andric   if (isa<Constant>(I)) {
445ff0cc061SDimitry Andric     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
446ff0cc061SDimitry Andric            "order of checks wrong!");
4477d523365SDimitry Andric     // Note: Even for frontends which don't have constant references, we can
4487d523365SDimitry Andric     // see constants appearing after optimizations.  A simple example is
4497d523365SDimitry Andric     // specialization of an address computation on null feeding into a merge
4507d523365SDimitry Andric     // point where the actual use of the now-constant input is protected by
4517d523365SDimitry Andric     // another null check.  (e.g. test4 in constants.ll)
4527d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
453ff0cc061SDimitry Andric   }
454ff0cc061SDimitry Andric 
455ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
456ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
4577d523365SDimitry Andric     // If stripping pointer casts changes the address space there is an
4587d523365SDimitry Andric     // addrspacecast in between.
4597d523365SDimitry Andric     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
4607d523365SDimitry Andric                cast<PointerType>(CI->getType())->getAddressSpace() &&
4617d523365SDimitry Andric            "unsupported addrspacecast");
462ff0cc061SDimitry Andric     // If we find a cast instruction here, it means we've found a cast which is
463ff0cc061SDimitry Andric     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
464ff0cc061SDimitry Andric     // handle int->ptr conversion.
465ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
466ff0cc061SDimitry Andric     return findBaseDefiningValue(Def);
467ff0cc061SDimitry Andric   }
468ff0cc061SDimitry Andric 
469ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
4707d523365SDimitry Andric     // The value loaded is an gc base itself
4717d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
4727d523365SDimitry Andric 
473ff0cc061SDimitry Andric 
474ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
475ff0cc061SDimitry Andric     // The base of this GEP is the base
476ff0cc061SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
477ff0cc061SDimitry Andric 
478ff0cc061SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
479ff0cc061SDimitry Andric     switch (II->getIntrinsicID()) {
480ff0cc061SDimitry Andric     default:
481ff0cc061SDimitry Andric       // fall through to general call handling
482ff0cc061SDimitry Andric       break;
483ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_statepoint:
4847d523365SDimitry Andric       llvm_unreachable("statepoints don't produce pointers");
485ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_relocate: {
486ff0cc061SDimitry Andric       // Rerunning safepoint insertion after safepoints are already
487ff0cc061SDimitry Andric       // inserted is not supported.  It could probably be made to work,
488ff0cc061SDimitry Andric       // but why are you doing this?  There's no good reason.
489ff0cc061SDimitry Andric       llvm_unreachable("repeat safepoint insertion is not supported");
490ff0cc061SDimitry Andric     }
491ff0cc061SDimitry Andric     case Intrinsic::gcroot:
492ff0cc061SDimitry Andric       // Currently, this mechanism hasn't been extended to work with gcroot.
493ff0cc061SDimitry Andric       // There's no reason it couldn't be, but I haven't thought about the
494ff0cc061SDimitry Andric       // implications much.
495ff0cc061SDimitry Andric       llvm_unreachable(
496ff0cc061SDimitry Andric           "interaction with the gcroot mechanism is not supported");
497ff0cc061SDimitry Andric     }
498ff0cc061SDimitry Andric   }
499ff0cc061SDimitry Andric   // We assume that functions in the source language only return base
500ff0cc061SDimitry Andric   // pointers.  This should probably be generalized via attributes to support
501ff0cc061SDimitry Andric   // both source language and internal functions.
502ff0cc061SDimitry Andric   if (isa<CallInst>(I) || isa<InvokeInst>(I))
5037d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
504ff0cc061SDimitry Andric 
505ff0cc061SDimitry Andric   // I have absolutely no idea how to implement this part yet.  It's not
5067d523365SDimitry Andric   // necessarily hard, I just haven't really looked at it yet.
507ff0cc061SDimitry Andric   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
508ff0cc061SDimitry Andric 
509ff0cc061SDimitry Andric   if (isa<AtomicCmpXchgInst>(I))
510ff0cc061SDimitry Andric     // A CAS is effectively a atomic store and load combined under a
511ff0cc061SDimitry Andric     // predicate.  From the perspective of base pointers, we just treat it
512ff0cc061SDimitry Andric     // like a load.
5137d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
514ff0cc061SDimitry Andric 
515ff0cc061SDimitry Andric   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
516ff0cc061SDimitry Andric                                    "binary ops which don't apply to pointers");
517ff0cc061SDimitry Andric 
518ff0cc061SDimitry Andric   // The aggregate ops.  Aggregates can either be in the heap or on the
519ff0cc061SDimitry Andric   // stack, but in either case, this is simply a field load.  As a result,
520ff0cc061SDimitry Andric   // this is a defining definition of the base just like a load is.
521ff0cc061SDimitry Andric   if (isa<ExtractValueInst>(I))
5227d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
523ff0cc061SDimitry Andric 
524ff0cc061SDimitry Andric   // We should never see an insert vector since that would require we be
525ff0cc061SDimitry Andric   // tracing back a struct value not a pointer value.
526ff0cc061SDimitry Andric   assert(!isa<InsertValueInst>(I) &&
527ff0cc061SDimitry Andric          "Base pointer for a struct is meaningless");
528ff0cc061SDimitry Andric 
5297d523365SDimitry Andric   // An extractelement produces a base result exactly when it's input does.
5307d523365SDimitry Andric   // We may need to insert a parallel instruction to extract the appropriate
5317d523365SDimitry Andric   // element out of the base vector corresponding to the input. Given this,
5327d523365SDimitry Andric   // it's analogous to the phi and select case even though it's not a merge.
5337d523365SDimitry Andric   if (isa<ExtractElementInst>(I))
5347d523365SDimitry Andric     // Note: There a lot of obvious peephole cases here.  This are deliberately
5357d523365SDimitry Andric     // handled after the main base pointer inference algorithm to make writing
5367d523365SDimitry Andric     // test cases to exercise that code easier.
5377d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
5387d523365SDimitry Andric 
539ff0cc061SDimitry Andric   // The last two cases here don't return a base pointer.  Instead, they
5407d523365SDimitry Andric   // return a value which dynamically selects from among several base
541ff0cc061SDimitry Andric   // derived pointers (each with it's own base potentially).  It's the job of
542ff0cc061SDimitry Andric   // the caller to resolve these.
543ff0cc061SDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
544ff0cc061SDimitry Andric          "missing instruction case in findBaseDefiningValing");
5457d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
546ff0cc061SDimitry Andric }
547ff0cc061SDimitry Andric 
548ff0cc061SDimitry Andric /// Returns the base defining value for this value.
549ff0cc061SDimitry Andric static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
550ff0cc061SDimitry Andric   Value *&Cached = Cache[I];
551ff0cc061SDimitry Andric   if (!Cached) {
5527d523365SDimitry Andric     Cached = findBaseDefiningValue(I).BDV;
5537d523365SDimitry Andric     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
5547d523365SDimitry Andric                  << Cached->getName() << "\n");
555ff0cc061SDimitry Andric   }
556ff0cc061SDimitry Andric   assert(Cache[I] != nullptr);
557ff0cc061SDimitry Andric   return Cached;
558ff0cc061SDimitry Andric }
559ff0cc061SDimitry Andric 
560ff0cc061SDimitry Andric /// Return a base pointer for this value if known.  Otherwise, return it's
561ff0cc061SDimitry Andric /// base defining value.
562ff0cc061SDimitry Andric static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
563ff0cc061SDimitry Andric   Value *Def = findBaseDefiningValueCached(I, Cache);
564ff0cc061SDimitry Andric   auto Found = Cache.find(Def);
565ff0cc061SDimitry Andric   if (Found != Cache.end()) {
566ff0cc061SDimitry Andric     // Either a base-of relation, or a self reference.  Caller must check.
567ff0cc061SDimitry Andric     return Found->second;
568ff0cc061SDimitry Andric   }
569ff0cc061SDimitry Andric   // Only a BDV available
570ff0cc061SDimitry Andric   return Def;
571ff0cc061SDimitry Andric }
572ff0cc061SDimitry Andric 
573ff0cc061SDimitry Andric /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
574ff0cc061SDimitry Andric /// is it known to be a base pointer?  Or do we need to continue searching.
575ff0cc061SDimitry Andric static bool isKnownBaseResult(Value *V) {
5767d523365SDimitry Andric   if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
5777d523365SDimitry Andric       !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
5787d523365SDimitry Andric       !isa<ShuffleVectorInst>(V)) {
579ff0cc061SDimitry Andric     // no recursion possible
580ff0cc061SDimitry Andric     return true;
581ff0cc061SDimitry Andric   }
582ff0cc061SDimitry Andric   if (isa<Instruction>(V) &&
583ff0cc061SDimitry Andric       cast<Instruction>(V)->getMetadata("is_base_value")) {
584ff0cc061SDimitry Andric     // This is a previously inserted base phi or select.  We know
585ff0cc061SDimitry Andric     // that this is a base value.
586ff0cc061SDimitry Andric     return true;
587ff0cc061SDimitry Andric   }
588ff0cc061SDimitry Andric 
589ff0cc061SDimitry Andric   // We need to keep searching
590ff0cc061SDimitry Andric   return false;
591ff0cc061SDimitry Andric }
592ff0cc061SDimitry Andric 
593ff0cc061SDimitry Andric namespace {
5947d523365SDimitry Andric /// Models the state of a single base defining value in the findBasePointer
5957d523365SDimitry Andric /// algorithm for determining where a new instruction is needed to propagate
5967d523365SDimitry Andric /// the base of this BDV.
5977d523365SDimitry Andric class BDVState {
598ff0cc061SDimitry Andric public:
599ff0cc061SDimitry Andric   enum Status { Unknown, Base, Conflict };
600ff0cc061SDimitry Andric 
6017d523365SDimitry Andric   BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
602ff0cc061SDimitry Andric     assert(status != Base || b);
603ff0cc061SDimitry Andric   }
6047d523365SDimitry Andric   explicit BDVState(Value *b) : status(Base), base(b) {}
6057d523365SDimitry Andric   BDVState() : status(Unknown), base(nullptr) {}
606ff0cc061SDimitry Andric 
607ff0cc061SDimitry Andric   Status getStatus() const { return status; }
608ff0cc061SDimitry Andric   Value *getBase() const { return base; }
609ff0cc061SDimitry Andric 
610ff0cc061SDimitry Andric   bool isBase() const { return getStatus() == Base; }
611ff0cc061SDimitry Andric   bool isUnknown() const { return getStatus() == Unknown; }
612ff0cc061SDimitry Andric   bool isConflict() const { return getStatus() == Conflict; }
613ff0cc061SDimitry Andric 
6147d523365SDimitry Andric   bool operator==(const BDVState &other) const {
615ff0cc061SDimitry Andric     return base == other.base && status == other.status;
616ff0cc061SDimitry Andric   }
617ff0cc061SDimitry Andric 
6187d523365SDimitry Andric   bool operator!=(const BDVState &other) const { return !(*this == other); }
619ff0cc061SDimitry Andric 
6207d523365SDimitry Andric   LLVM_DUMP_METHOD
6217d523365SDimitry Andric   void dump() const { print(dbgs()); dbgs() << '\n'; }
6227d523365SDimitry Andric 
6237d523365SDimitry Andric   void print(raw_ostream &OS) const {
6247d523365SDimitry Andric     switch (status) {
6257d523365SDimitry Andric     case Unknown:
6267d523365SDimitry Andric       OS << "U";
6277d523365SDimitry Andric       break;
6287d523365SDimitry Andric     case Base:
6297d523365SDimitry Andric       OS << "B";
6307d523365SDimitry Andric       break;
6317d523365SDimitry Andric     case Conflict:
6327d523365SDimitry Andric       OS << "C";
6337d523365SDimitry Andric       break;
6347d523365SDimitry Andric     };
6357d523365SDimitry Andric     OS << " (" << base << " - "
636ff0cc061SDimitry Andric        << (base ? base->getName() : "nullptr") << "): ";
637ff0cc061SDimitry Andric   }
638ff0cc061SDimitry Andric 
639ff0cc061SDimitry Andric private:
640ff0cc061SDimitry Andric   Status status;
6417d523365SDimitry Andric   AssertingVH<Value> base; // non null only if status == base
642ff0cc061SDimitry Andric };
643ff0cc061SDimitry Andric }
644ff0cc061SDimitry Andric 
6457d523365SDimitry Andric #ifndef NDEBUG
6467d523365SDimitry Andric static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
6477d523365SDimitry Andric   State.print(OS);
6487d523365SDimitry Andric   return OS;
6497d523365SDimitry Andric }
6507d523365SDimitry Andric #endif
6517d523365SDimitry Andric 
6527d523365SDimitry Andric namespace {
6537d523365SDimitry Andric // Values of type BDVState form a lattice, and this is a helper
6547d523365SDimitry Andric // class that implementes the meet operation.  The meat of the meet
6557d523365SDimitry Andric // operation is implemented in MeetBDVStates::pureMeet
6567d523365SDimitry Andric class MeetBDVStates {
6577d523365SDimitry Andric public:
6587d523365SDimitry Andric   /// Initializes the currentResult to the TOP state so that if can be met with
6597d523365SDimitry Andric   /// any other state to produce that state.
6607d523365SDimitry Andric   MeetBDVStates() {}
6617d523365SDimitry Andric 
6627d523365SDimitry Andric   // Destructively meet the current result with the given BDVState
6637d523365SDimitry Andric   void meetWith(BDVState otherState) {
6647d523365SDimitry Andric     currentResult = meet(otherState, currentResult);
6657d523365SDimitry Andric   }
6667d523365SDimitry Andric 
6677d523365SDimitry Andric   BDVState getResult() const { return currentResult; }
668ff0cc061SDimitry Andric 
669ff0cc061SDimitry Andric private:
6707d523365SDimitry Andric   BDVState currentResult;
671ff0cc061SDimitry Andric 
6727d523365SDimitry Andric   /// Perform a meet operation on two elements of the BDVState lattice.
6737d523365SDimitry Andric   static BDVState meet(BDVState LHS, BDVState RHS) {
6747d523365SDimitry Andric     assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
6757d523365SDimitry Andric            "math is wrong: meet does not commute!");
6767d523365SDimitry Andric     BDVState Result = pureMeet(LHS, RHS);
6777d523365SDimitry Andric     DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
6787d523365SDimitry Andric                  << " produced " << Result << "\n");
6797d523365SDimitry Andric     return Result;
680ff0cc061SDimitry Andric   }
681ff0cc061SDimitry Andric 
6827d523365SDimitry Andric   static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
683ff0cc061SDimitry Andric     switch (stateA.getStatus()) {
6847d523365SDimitry Andric     case BDVState::Unknown:
685ff0cc061SDimitry Andric       return stateB;
686ff0cc061SDimitry Andric 
6877d523365SDimitry Andric     case BDVState::Base:
688ff0cc061SDimitry Andric       assert(stateA.getBase() && "can't be null");
689ff0cc061SDimitry Andric       if (stateB.isUnknown())
690ff0cc061SDimitry Andric         return stateA;
691ff0cc061SDimitry Andric 
692ff0cc061SDimitry Andric       if (stateB.isBase()) {
693ff0cc061SDimitry Andric         if (stateA.getBase() == stateB.getBase()) {
694ff0cc061SDimitry Andric           assert(stateA == stateB && "equality broken!");
695ff0cc061SDimitry Andric           return stateA;
696ff0cc061SDimitry Andric         }
6977d523365SDimitry Andric         return BDVState(BDVState::Conflict);
698ff0cc061SDimitry Andric       }
699ff0cc061SDimitry Andric       assert(stateB.isConflict() && "only three states!");
7007d523365SDimitry Andric       return BDVState(BDVState::Conflict);
701ff0cc061SDimitry Andric 
7027d523365SDimitry Andric     case BDVState::Conflict:
703ff0cc061SDimitry Andric       return stateA;
704ff0cc061SDimitry Andric     }
705ff0cc061SDimitry Andric     llvm_unreachable("only three states!");
706ff0cc061SDimitry Andric   }
707ff0cc061SDimitry Andric };
7083dac3a9bSDimitry Andric }
7097d523365SDimitry Andric 
7107d523365SDimitry Andric 
711ff0cc061SDimitry Andric /// For a given value or instruction, figure out what base ptr it's derived
712ff0cc061SDimitry Andric /// from.  For gc objects, this is simply itself.  On success, returns a value
713ff0cc061SDimitry Andric /// which is the base pointer.  (This is reliable and can be used for
714ff0cc061SDimitry Andric /// relocation.)  On failure, returns nullptr.
715ff0cc061SDimitry Andric static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
716ff0cc061SDimitry Andric   Value *def = findBaseOrBDV(I, cache);
717ff0cc061SDimitry Andric 
718ff0cc061SDimitry Andric   if (isKnownBaseResult(def)) {
719ff0cc061SDimitry Andric     return def;
720ff0cc061SDimitry Andric   }
721ff0cc061SDimitry Andric 
722ff0cc061SDimitry Andric   // Here's the rough algorithm:
723ff0cc061SDimitry Andric   // - For every SSA value, construct a mapping to either an actual base
724ff0cc061SDimitry Andric   //   pointer or a PHI which obscures the base pointer.
725ff0cc061SDimitry Andric   // - Construct a mapping from PHI to unknown TOP state.  Use an
726ff0cc061SDimitry Andric   //   optimistic algorithm to propagate base pointer information.  Lattice
727ff0cc061SDimitry Andric   //   looks like:
728ff0cc061SDimitry Andric   //   UNKNOWN
729ff0cc061SDimitry Andric   //   b1 b2 b3 b4
730ff0cc061SDimitry Andric   //   CONFLICT
731ff0cc061SDimitry Andric   //   When algorithm terminates, all PHIs will either have a single concrete
732ff0cc061SDimitry Andric   //   base or be in a conflict state.
733ff0cc061SDimitry Andric   // - For every conflict, insert a dummy PHI node without arguments.  Add
734ff0cc061SDimitry Andric   //   these to the base[Instruction] = BasePtr mapping.  For every
735ff0cc061SDimitry Andric   //   non-conflict, add the actual base.
736ff0cc061SDimitry Andric   //  - For every conflict, add arguments for the base[a] of each input
737ff0cc061SDimitry Andric   //   arguments.
738ff0cc061SDimitry Andric   //
739ff0cc061SDimitry Andric   // Note: A simpler form of this would be to add the conflict form of all
740ff0cc061SDimitry Andric   // PHIs without running the optimistic algorithm.  This would be
7417d523365SDimitry Andric   // analogous to pessimistic data flow and would likely lead to an
742ff0cc061SDimitry Andric   // overall worse solution.
743ff0cc061SDimitry Andric 
7447d523365SDimitry Andric #ifndef NDEBUG
7457d523365SDimitry Andric   auto isExpectedBDVType = [](Value *BDV) {
7467d523365SDimitry Andric     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
7477d523365SDimitry Andric            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
7487d523365SDimitry Andric   };
7497d523365SDimitry Andric #endif
7507d523365SDimitry Andric 
7517d523365SDimitry Andric   // Once populated, will contain a mapping from each potentially non-base BDV
7527d523365SDimitry Andric   // to a lattice value (described above) which corresponds to that BDV.
7537d523365SDimitry Andric   // We use the order of insertion (DFS over the def/use graph) to provide a
7547d523365SDimitry Andric   // stable deterministic ordering for visiting DenseMaps (which are unordered)
7557d523365SDimitry Andric   // below.  This is important for deterministic compilation.
7567d523365SDimitry Andric   MapVector<Value *, BDVState> States;
7577d523365SDimitry Andric 
7587d523365SDimitry Andric   // Recursively fill in all base defining values reachable from the initial
7597d523365SDimitry Andric   // one for which we don't already know a definite base value for
7607d523365SDimitry Andric   /* scope */ {
7617d523365SDimitry Andric     SmallVector<Value*, 16> Worklist;
7627d523365SDimitry Andric     Worklist.push_back(def);
7637d523365SDimitry Andric     States.insert(std::make_pair(def, BDVState()));
7647d523365SDimitry Andric     while (!Worklist.empty()) {
7657d523365SDimitry Andric       Value *Current = Worklist.pop_back_val();
7667d523365SDimitry Andric       assert(!isKnownBaseResult(Current) && "why did it get added?");
7677d523365SDimitry Andric 
7687d523365SDimitry Andric       auto visitIncomingValue = [&](Value *InVal) {
7697d523365SDimitry Andric         Value *Base = findBaseOrBDV(InVal, cache);
7707d523365SDimitry Andric         if (isKnownBaseResult(Base))
7717d523365SDimitry Andric           // Known bases won't need new instructions introduced and can be
7727d523365SDimitry Andric           // ignored safely
7737d523365SDimitry Andric           return;
7747d523365SDimitry Andric         assert(isExpectedBDVType(Base) && "the only non-base values "
7757d523365SDimitry Andric                "we see should be base defining values");
7767d523365SDimitry Andric         if (States.insert(std::make_pair(Base, BDVState())).second)
7777d523365SDimitry Andric           Worklist.push_back(Base);
7787d523365SDimitry Andric       };
7797d523365SDimitry Andric       if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
7807d523365SDimitry Andric         for (Value *InVal : Phi->incoming_values())
7817d523365SDimitry Andric           visitIncomingValue(InVal);
7827d523365SDimitry Andric       } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
7837d523365SDimitry Andric         visitIncomingValue(Sel->getTrueValue());
7847d523365SDimitry Andric         visitIncomingValue(Sel->getFalseValue());
7857d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
7867d523365SDimitry Andric         visitIncomingValue(EE->getVectorOperand());
7877d523365SDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
7887d523365SDimitry Andric         visitIncomingValue(IE->getOperand(0)); // vector operand
7897d523365SDimitry Andric         visitIncomingValue(IE->getOperand(1)); // scalar operand
7907d523365SDimitry Andric       } else {
7917d523365SDimitry Andric         // There is one known class of instructions we know we don't handle.
7927d523365SDimitry Andric         assert(isa<ShuffleVectorInst>(Current));
7937d523365SDimitry Andric         llvm_unreachable("unimplemented instruction case");
794ff0cc061SDimitry Andric       }
795ff0cc061SDimitry Andric     }
796ff0cc061SDimitry Andric   }
797ff0cc061SDimitry Andric 
7987d523365SDimitry Andric #ifndef NDEBUG
7997d523365SDimitry Andric   DEBUG(dbgs() << "States after initialization:\n");
8007d523365SDimitry Andric   for (auto Pair : States) {
8017d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
802ff0cc061SDimitry Andric   }
8037d523365SDimitry Andric #endif
804ff0cc061SDimitry Andric 
8057d523365SDimitry Andric   // Return a phi state for a base defining value.  We'll generate a new
8067d523365SDimitry Andric   // base state for known bases and expect to find a cached state otherwise.
8077d523365SDimitry Andric   auto getStateForBDV = [&](Value *baseValue) {
8087d523365SDimitry Andric     if (isKnownBaseResult(baseValue))
8097d523365SDimitry Andric       return BDVState(baseValue);
8107d523365SDimitry Andric     auto I = States.find(baseValue);
8117d523365SDimitry Andric     assert(I != States.end() && "lookup failed!");
8127d523365SDimitry Andric     return I->second;
8137d523365SDimitry Andric   };
814ff0cc061SDimitry Andric 
815ff0cc061SDimitry Andric   bool progress = true;
816ff0cc061SDimitry Andric   while (progress) {
817ff0cc061SDimitry Andric #ifndef NDEBUG
8187d523365SDimitry Andric     const size_t oldSize = States.size();
819ff0cc061SDimitry Andric #endif
820ff0cc061SDimitry Andric     progress = false;
8217d523365SDimitry Andric     // We're only changing values in this loop, thus safe to keep iterators.
8227d523365SDimitry Andric     // Since this is computing a fixed point, the order of visit does not
8237d523365SDimitry Andric     // effect the result.  TODO: We could use a worklist here and make this run
8247d523365SDimitry Andric     // much faster.
8257d523365SDimitry Andric     for (auto Pair : States) {
8267d523365SDimitry Andric       Value *BDV = Pair.first;
8277d523365SDimitry Andric       assert(!isKnownBaseResult(BDV) && "why did it get added?");
828ff0cc061SDimitry Andric 
8297d523365SDimitry Andric       // Given an input value for the current instruction, return a BDVState
8307d523365SDimitry Andric       // instance which represents the BDV of that value.
8317d523365SDimitry Andric       auto getStateForInput = [&](Value *V) mutable {
8327d523365SDimitry Andric         Value *BDV = findBaseOrBDV(V, cache);
8337d523365SDimitry Andric         return getStateForBDV(BDV);
8347d523365SDimitry Andric       };
8357d523365SDimitry Andric 
8367d523365SDimitry Andric       MeetBDVStates calculateMeet;
8377d523365SDimitry Andric       if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
8387d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
8397d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
8407d523365SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
8417d523365SDimitry Andric         for (Value *Val : Phi->incoming_values())
8427d523365SDimitry Andric           calculateMeet.meetWith(getStateForInput(Val));
8437d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
8447d523365SDimitry Andric         // The 'meet' for an extractelement is slightly trivial, but it's still
8457d523365SDimitry Andric         // useful in that it drives us to conflict if our input is.
8467d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
8477d523365SDimitry Andric       } else {
8487d523365SDimitry Andric         // Given there's a inherent type mismatch between the operands, will
8497d523365SDimitry Andric         // *always* produce Conflict.
8507d523365SDimitry Andric         auto *IE = cast<InsertElementInst>(BDV);
8517d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
8527d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
8537d523365SDimitry Andric       }
8547d523365SDimitry Andric 
8557d523365SDimitry Andric       BDVState oldState = States[BDV];
8567d523365SDimitry Andric       BDVState newState = calculateMeet.getResult();
857ff0cc061SDimitry Andric       if (oldState != newState) {
858ff0cc061SDimitry Andric         progress = true;
8597d523365SDimitry Andric         States[BDV] = newState;
860ff0cc061SDimitry Andric       }
861ff0cc061SDimitry Andric     }
862ff0cc061SDimitry Andric 
8637d523365SDimitry Andric     assert(oldSize == States.size() &&
8647d523365SDimitry Andric            "fixed point shouldn't be adding any new nodes to state");
865ff0cc061SDimitry Andric   }
866ff0cc061SDimitry Andric 
8677d523365SDimitry Andric #ifndef NDEBUG
8687d523365SDimitry Andric   DEBUG(dbgs() << "States after meet iteration:\n");
8697d523365SDimitry Andric   for (auto Pair : States) {
8707d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
871ff0cc061SDimitry Andric   }
8727d523365SDimitry Andric #endif
873ff0cc061SDimitry Andric 
874ff0cc061SDimitry Andric   // Insert Phis for all conflicts
875ff0cc061SDimitry Andric   // TODO: adjust naming patterns to avoid this order of iteration dependency
8767d523365SDimitry Andric   for (auto Pair : States) {
8777d523365SDimitry Andric     Instruction *I = cast<Instruction>(Pair.first);
8787d523365SDimitry Andric     BDVState State = Pair.second;
8797d523365SDimitry Andric     assert(!isKnownBaseResult(I) && "why did it get added?");
8807d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
8817d523365SDimitry Andric 
8827d523365SDimitry Andric     // extractelement instructions are a bit special in that we may need to
8837d523365SDimitry Andric     // insert an extract even when we know an exact base for the instruction.
8847d523365SDimitry Andric     // The problem is that we need to convert from a vector base to a scalar
8857d523365SDimitry Andric     // base for the particular indice we're interested in.
8867d523365SDimitry Andric     if (State.isBase() && isa<ExtractElementInst>(I) &&
8877d523365SDimitry Andric         isa<VectorType>(State.getBase()->getType())) {
8887d523365SDimitry Andric       auto *EE = cast<ExtractElementInst>(I);
8897d523365SDimitry Andric       // TODO: In many cases, the new instruction is just EE itself.  We should
8907d523365SDimitry Andric       // exploit this, but can't do it here since it would break the invariant
8917d523365SDimitry Andric       // about the BDV not being known to be a base.
8927d523365SDimitry Andric       auto *BaseInst = ExtractElementInst::Create(State.getBase(),
8937d523365SDimitry Andric                                                   EE->getIndexOperand(),
8947d523365SDimitry Andric                                                   "base_ee", EE);
8957d523365SDimitry Andric       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
8967d523365SDimitry Andric       States[I] = BDVState(BDVState::Base, BaseInst);
8977d523365SDimitry Andric     }
8987d523365SDimitry Andric 
8997d523365SDimitry Andric     // Since we're joining a vector and scalar base, they can never be the
9007d523365SDimitry Andric     // same.  As a result, we should always see insert element having reached
9017d523365SDimitry Andric     // the conflict state.
9027d523365SDimitry Andric     if (isa<InsertElementInst>(I)) {
9037d523365SDimitry Andric       assert(State.isConflict());
9047d523365SDimitry Andric     }
9057d523365SDimitry Andric 
9067d523365SDimitry Andric     if (!State.isConflict())
907ff0cc061SDimitry Andric       continue;
908ff0cc061SDimitry Andric 
9097d523365SDimitry Andric     /// Create and insert a new instruction which will represent the base of
9107d523365SDimitry Andric     /// the given instruction 'I'.
9117d523365SDimitry Andric     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
9127d523365SDimitry Andric       if (isa<PHINode>(I)) {
9137d523365SDimitry Andric         BasicBlock *BB = I->getParent();
9147d523365SDimitry Andric         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
9157d523365SDimitry Andric         assert(NumPreds > 0 && "how did we reach here");
9167d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_phi");
9177d523365SDimitry Andric         return PHINode::Create(I->getType(), NumPreds, Name, I);
9187d523365SDimitry Andric       } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
919ff0cc061SDimitry Andric         // The undef will be replaced later
9207d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(Sel->getType());
9217d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_select");
9227d523365SDimitry Andric         return SelectInst::Create(Sel->getCondition(), Undef,
9237d523365SDimitry Andric                                   Undef, Name, Sel);
9247d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
9257d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
9267d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ee");
9277d523365SDimitry Andric         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
9287d523365SDimitry Andric                                           EE);
9297d523365SDimitry Andric       } else {
9307d523365SDimitry Andric         auto *IE = cast<InsertElementInst>(I);
9317d523365SDimitry Andric         UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
9327d523365SDimitry Andric         UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
9337d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ie");
9347d523365SDimitry Andric         return InsertElementInst::Create(VecUndef, ScalarUndef,
9357d523365SDimitry Andric                                          IE->getOperand(2), Name, IE);
9367d523365SDimitry Andric       }
9377d523365SDimitry Andric 
9387d523365SDimitry Andric     };
9397d523365SDimitry Andric     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
940ff0cc061SDimitry Andric     // Add metadata marking this as a base value
9417d523365SDimitry Andric     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
9427d523365SDimitry Andric     States[I] = BDVState(BDVState::Conflict, BaseInst);
943ff0cc061SDimitry Andric   }
944ff0cc061SDimitry Andric 
9457d523365SDimitry Andric   // Returns a instruction which produces the base pointer for a given
9467d523365SDimitry Andric   // instruction.  The instruction is assumed to be an input to one of the BDVs
9477d523365SDimitry Andric   // seen in the inference algorithm above.  As such, we must either already
9487d523365SDimitry Andric   // know it's base defining value is a base, or have inserted a new
9497d523365SDimitry Andric   // instruction to propagate the base of it's BDV and have entered that newly
9507d523365SDimitry Andric   // introduced instruction into the state table.  In either case, we are
9517d523365SDimitry Andric   // assured to be able to determine an instruction which produces it's base
9527d523365SDimitry Andric   // pointer.
9537d523365SDimitry Andric   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
9547d523365SDimitry Andric     Value *BDV = findBaseOrBDV(Input, cache);
9557d523365SDimitry Andric     Value *Base = nullptr;
9567d523365SDimitry Andric     if (isKnownBaseResult(BDV)) {
9577d523365SDimitry Andric       Base = BDV;
9587d523365SDimitry Andric     } else {
9597d523365SDimitry Andric       // Either conflict or base.
9607d523365SDimitry Andric       assert(States.count(BDV));
9617d523365SDimitry Andric       Base = States[BDV].getBase();
9627d523365SDimitry Andric     }
9637d523365SDimitry Andric     assert(Base && "can't be null");
9647d523365SDimitry Andric     // The cast is needed since base traversal may strip away bitcasts
9657d523365SDimitry Andric     if (Base->getType() != Input->getType() &&
9667d523365SDimitry Andric         InsertPt) {
9677d523365SDimitry Andric       Base = new BitCastInst(Base, Input->getType(), "cast",
9687d523365SDimitry Andric                              InsertPt);
9697d523365SDimitry Andric     }
9707d523365SDimitry Andric     return Base;
9717d523365SDimitry Andric   };
972ff0cc061SDimitry Andric 
9737d523365SDimitry Andric   // Fixup all the inputs of the new PHIs.  Visit order needs to be
9747d523365SDimitry Andric   // deterministic and predictable because we're naming newly created
9757d523365SDimitry Andric   // instructions.
9767d523365SDimitry Andric   for (auto Pair : States) {
9777d523365SDimitry Andric     Instruction *BDV = cast<Instruction>(Pair.first);
9787d523365SDimitry Andric     BDVState State = Pair.second;
9797d523365SDimitry Andric 
9807d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
9817d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
9827d523365SDimitry Andric     if (!State.isConflict())
983ff0cc061SDimitry Andric       continue;
984ff0cc061SDimitry Andric 
9857d523365SDimitry Andric     if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
9867d523365SDimitry Andric       PHINode *phi = cast<PHINode>(BDV);
987ff0cc061SDimitry Andric       unsigned NumPHIValues = phi->getNumIncomingValues();
988ff0cc061SDimitry Andric       for (unsigned i = 0; i < NumPHIValues; i++) {
989ff0cc061SDimitry Andric         Value *InVal = phi->getIncomingValue(i);
990ff0cc061SDimitry Andric         BasicBlock *InBB = phi->getIncomingBlock(i);
991ff0cc061SDimitry Andric 
992ff0cc061SDimitry Andric         // If we've already seen InBB, add the same incoming value
993ff0cc061SDimitry Andric         // we added for it earlier.  The IR verifier requires phi
994ff0cc061SDimitry Andric         // nodes with multiple entries from the same basic block
995ff0cc061SDimitry Andric         // to have the same incoming value for each of those
996ff0cc061SDimitry Andric         // entries.  If we don't do this check here and basephi
997ff0cc061SDimitry Andric         // has a different type than base, we'll end up adding two
998ff0cc061SDimitry Andric         // bitcasts (and hence two distinct values) as incoming
999ff0cc061SDimitry Andric         // values for the same basic block.
1000ff0cc061SDimitry Andric 
1001ff0cc061SDimitry Andric         int blockIndex = basephi->getBasicBlockIndex(InBB);
1002ff0cc061SDimitry Andric         if (blockIndex != -1) {
1003ff0cc061SDimitry Andric           Value *oldBase = basephi->getIncomingValue(blockIndex);
1004ff0cc061SDimitry Andric           basephi->addIncoming(oldBase, InBB);
1005ff0cc061SDimitry Andric 
10067d523365SDimitry Andric #ifndef NDEBUG
10077d523365SDimitry Andric           Value *Base = getBaseForInput(InVal, nullptr);
10087d523365SDimitry Andric           // In essence this assert states: the only way two
1009ff0cc061SDimitry Andric           // values incoming from the same basic block may be
1010ff0cc061SDimitry Andric           // different is by being different bitcasts of the same
1011ff0cc061SDimitry Andric           // value.  A cleanup that remains TODO is changing
1012ff0cc061SDimitry Andric           // findBaseOrBDV to return an llvm::Value of the correct
1013ff0cc061SDimitry Andric           // type (and still remain pure).  This will remove the
1014ff0cc061SDimitry Andric           // need to add bitcasts.
10157d523365SDimitry Andric           assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
1016ff0cc061SDimitry Andric                  "sanity -- findBaseOrBDV should be pure!");
1017ff0cc061SDimitry Andric #endif
1018ff0cc061SDimitry Andric           continue;
1019ff0cc061SDimitry Andric         }
1020ff0cc061SDimitry Andric 
10217d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
10227d523365SDimitry Andric         // need to insert a bitcast in the incoming block.
10237d523365SDimitry Andric         // TODO: Need to split critical edges if insertion is needed
10247d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
10257d523365SDimitry Andric         basephi->addIncoming(Base, InBB);
1026ff0cc061SDimitry Andric       }
1027ff0cc061SDimitry Andric       assert(basephi->getNumIncomingValues() == NumPHIValues);
10287d523365SDimitry Andric     } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
10297d523365SDimitry Andric       SelectInst *Sel = cast<SelectInst>(BDV);
1030ff0cc061SDimitry Andric       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1031ff0cc061SDimitry Andric       // something more safe and less hacky.
1032ff0cc061SDimitry Andric       for (int i = 1; i <= 2; i++) {
10337d523365SDimitry Andric         Value *InVal = Sel->getOperand(i);
10347d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
10357d523365SDimitry Andric         // need to insert a bitcast.
10367d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseSel);
10377d523365SDimitry Andric         BaseSel->setOperand(i, Base);
1038ff0cc061SDimitry Andric       }
10397d523365SDimitry Andric     } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
10407d523365SDimitry Andric       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
10417d523365SDimitry Andric       // Find the instruction which produces the base for each input.  We may
10427d523365SDimitry Andric       // need to insert a bitcast.
10437d523365SDimitry Andric       Value *Base = getBaseForInput(InVal, BaseEE);
10447d523365SDimitry Andric       BaseEE->setOperand(0, Base);
10457d523365SDimitry Andric     } else {
10467d523365SDimitry Andric       auto *BaseIE = cast<InsertElementInst>(State.getBase());
10477d523365SDimitry Andric       auto *BdvIE = cast<InsertElementInst>(BDV);
10487d523365SDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
10497d523365SDimitry Andric         Value *InVal = BdvIE->getOperand(OperandIdx);
10507d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseIE);
10517d523365SDimitry Andric         BaseIE->setOperand(OperandIdx, Base);
10527d523365SDimitry Andric       };
10537d523365SDimitry Andric       UpdateOperand(0); // vector operand
10547d523365SDimitry Andric       UpdateOperand(1); // scalar operand
1055ff0cc061SDimitry Andric     }
10567d523365SDimitry Andric 
1057ff0cc061SDimitry Andric   }
10587d523365SDimitry Andric 
10597d523365SDimitry Andric   // Now that we're done with the algorithm, see if we can optimize the
10607d523365SDimitry Andric   // results slightly by reducing the number of new instructions needed.
10617d523365SDimitry Andric   // Arguably, this should be integrated into the algorithm above, but
10627d523365SDimitry Andric   // doing as a post process step is easier to reason about for the moment.
10637d523365SDimitry Andric   DenseMap<Value *, Value *> ReverseMap;
10647d523365SDimitry Andric   SmallPtrSet<Instruction *, 16> NewInsts;
10657d523365SDimitry Andric   SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
10667d523365SDimitry Andric   // Note: We need to visit the states in a deterministic order.  We uses the
10677d523365SDimitry Andric   // Keys we sorted above for this purpose.  Note that we are papering over a
10687d523365SDimitry Andric   // bigger problem with the algorithm above - it's visit order is not
10697d523365SDimitry Andric   // deterministic.  A larger change is needed to fix this.
10707d523365SDimitry Andric   for (auto Pair : States) {
10717d523365SDimitry Andric     auto *BDV = Pair.first;
10727d523365SDimitry Andric     auto State = Pair.second;
10737d523365SDimitry Andric     Value *Base = State.getBase();
10747d523365SDimitry Andric     assert(BDV && Base);
10757d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
10767d523365SDimitry Andric     assert(isKnownBaseResult(Base) &&
10777d523365SDimitry Andric            "must be something we 'know' is a base pointer");
10787d523365SDimitry Andric     if (!State.isConflict())
10797d523365SDimitry Andric       continue;
10807d523365SDimitry Andric 
10817d523365SDimitry Andric     ReverseMap[Base] = BDV;
10827d523365SDimitry Andric     if (auto *BaseI = dyn_cast<Instruction>(Base)) {
10837d523365SDimitry Andric       NewInsts.insert(BaseI);
10847d523365SDimitry Andric       Worklist.insert(BaseI);
10857d523365SDimitry Andric     }
10867d523365SDimitry Andric   }
10877d523365SDimitry Andric   auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
10887d523365SDimitry Andric                                  Value *Replacement) {
10897d523365SDimitry Andric     // Add users which are new instructions (excluding self references)
10907d523365SDimitry Andric     for (User *U : BaseI->users())
10917d523365SDimitry Andric       if (auto *UI = dyn_cast<Instruction>(U))
10927d523365SDimitry Andric         if (NewInsts.count(UI) && UI != BaseI)
10937d523365SDimitry Andric           Worklist.insert(UI);
10947d523365SDimitry Andric     // Then do the actual replacement
10957d523365SDimitry Andric     NewInsts.erase(BaseI);
10967d523365SDimitry Andric     ReverseMap.erase(BaseI);
10977d523365SDimitry Andric     BaseI->replaceAllUsesWith(Replacement);
10987d523365SDimitry Andric     assert(States.count(BDV));
10997d523365SDimitry Andric     assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
11007d523365SDimitry Andric     States[BDV] = BDVState(BDVState::Conflict, Replacement);
11017d523365SDimitry Andric     BaseI->eraseFromParent();
11027d523365SDimitry Andric   };
11037d523365SDimitry Andric   const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
11047d523365SDimitry Andric   while (!Worklist.empty()) {
11057d523365SDimitry Andric     Instruction *BaseI = Worklist.pop_back_val();
11067d523365SDimitry Andric     assert(NewInsts.count(BaseI));
11077d523365SDimitry Andric     Value *Bdv = ReverseMap[BaseI];
11087d523365SDimitry Andric     if (auto *BdvI = dyn_cast<Instruction>(Bdv))
11097d523365SDimitry Andric       if (BaseI->isIdenticalTo(BdvI)) {
11107d523365SDimitry Andric         DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
11117d523365SDimitry Andric         ReplaceBaseInstWith(Bdv, BaseI, Bdv);
11127d523365SDimitry Andric         continue;
11137d523365SDimitry Andric       }
11147d523365SDimitry Andric     if (Value *V = SimplifyInstruction(BaseI, DL)) {
11157d523365SDimitry Andric       DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
11167d523365SDimitry Andric       ReplaceBaseInstWith(Bdv, BaseI, V);
11177d523365SDimitry Andric       continue;
1118ff0cc061SDimitry Andric     }
1119ff0cc061SDimitry Andric   }
1120ff0cc061SDimitry Andric 
1121ff0cc061SDimitry Andric   // Cache all of our results so we can cheaply reuse them
1122ff0cc061SDimitry Andric   // NOTE: This is actually two caches: one of the base defining value
1123ff0cc061SDimitry Andric   // relation and one of the base pointer relation!  FIXME
11247d523365SDimitry Andric   for (auto Pair : States) {
11257d523365SDimitry Andric     auto *BDV = Pair.first;
11267d523365SDimitry Andric     Value *base = Pair.second.getBase();
11277d523365SDimitry Andric     assert(BDV && base);
1128ff0cc061SDimitry Andric 
11297d523365SDimitry Andric     std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
11307d523365SDimitry Andric     DEBUG(dbgs() << "Updating base value cache"
11317d523365SDimitry Andric           << " for: " << BDV->getName()
1132ff0cc061SDimitry Andric           << " from: " << fromstr
11337d523365SDimitry Andric           << " to: " << base->getName() << "\n");
1134ff0cc061SDimitry Andric 
11357d523365SDimitry Andric     if (cache.count(BDV)) {
1136ff0cc061SDimitry Andric       // Once we transition from the BDV relation being store in the cache to
1137ff0cc061SDimitry Andric       // the base relation being stored, it must be stable
11387d523365SDimitry Andric       assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
1139ff0cc061SDimitry Andric              "base relation should be stable");
1140ff0cc061SDimitry Andric     }
11417d523365SDimitry Andric     cache[BDV] = base;
1142ff0cc061SDimitry Andric   }
11437d523365SDimitry Andric   assert(cache.count(def));
1144ff0cc061SDimitry Andric   return cache[def];
1145ff0cc061SDimitry Andric }
1146ff0cc061SDimitry Andric 
1147ff0cc061SDimitry Andric // For a set of live pointers (base and/or derived), identify the base
1148ff0cc061SDimitry Andric // pointer of the object which they are derived from.  This routine will
1149ff0cc061SDimitry Andric // mutate the IR graph as needed to make the 'base' pointer live at the
1150ff0cc061SDimitry Andric // definition site of 'derived'.  This ensures that any use of 'derived' can
1151ff0cc061SDimitry Andric // also use 'base'.  This may involve the insertion of a number of
1152ff0cc061SDimitry Andric // additional PHI nodes.
1153ff0cc061SDimitry Andric //
1154ff0cc061SDimitry Andric // preconditions: live is a set of pointer type Values
1155ff0cc061SDimitry Andric //
1156ff0cc061SDimitry Andric // side effects: may insert PHI nodes into the existing CFG, will preserve
1157ff0cc061SDimitry Andric // CFG, will not remove or mutate any existing nodes
1158ff0cc061SDimitry Andric //
1159ff0cc061SDimitry Andric // post condition: PointerToBase contains one (derived, base) pair for every
1160ff0cc061SDimitry Andric // pointer in live.  Note that derived can be equal to base if the original
1161ff0cc061SDimitry Andric // pointer was a base pointer.
1162ff0cc061SDimitry Andric static void
1163ff0cc061SDimitry Andric findBasePointers(const StatepointLiveSetTy &live,
11647d523365SDimitry Andric                  DenseMap<Value *, Value *> &PointerToBase,
1165ff0cc061SDimitry Andric                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
1166ff0cc061SDimitry Andric   // For the naming of values inserted to be deterministic - which makes for
1167ff0cc061SDimitry Andric   // much cleaner and more stable tests - we need to assign an order to the
1168ff0cc061SDimitry Andric   // live values.  DenseSets do not provide a deterministic order across runs.
1169ff0cc061SDimitry Andric   SmallVector<Value *, 64> Temp;
1170ff0cc061SDimitry Andric   Temp.insert(Temp.end(), live.begin(), live.end());
1171ff0cc061SDimitry Andric   std::sort(Temp.begin(), Temp.end(), order_by_name);
1172ff0cc061SDimitry Andric   for (Value *ptr : Temp) {
1173ff0cc061SDimitry Andric     Value *base = findBasePointer(ptr, DVCache);
1174ff0cc061SDimitry Andric     assert(base && "failed to find base pointer");
1175ff0cc061SDimitry Andric     PointerToBase[ptr] = base;
1176ff0cc061SDimitry Andric     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1177ff0cc061SDimitry Andric             DT->dominates(cast<Instruction>(base)->getParent(),
1178ff0cc061SDimitry Andric                           cast<Instruction>(ptr)->getParent())) &&
1179ff0cc061SDimitry Andric            "The base we found better dominate the derived pointer");
1180ff0cc061SDimitry Andric 
1181ff0cc061SDimitry Andric     // If you see this trip and like to live really dangerously, the code should
1182ff0cc061SDimitry Andric     // be correct, just with idioms the verifier can't handle.  You can try
11837d523365SDimitry Andric     // disabling the verifier at your own substantial risk.
1184ff0cc061SDimitry Andric     assert(!isa<ConstantPointerNull>(base) &&
1185ff0cc061SDimitry Andric            "the relocation code needs adjustment to handle the relocation of "
1186ff0cc061SDimitry Andric            "a null pointer constant without causing false positives in the "
1187ff0cc061SDimitry Andric            "safepoint ir verifier.");
1188ff0cc061SDimitry Andric   }
1189ff0cc061SDimitry Andric }
1190ff0cc061SDimitry Andric 
1191ff0cc061SDimitry Andric /// Find the required based pointers (and adjust the live set) for the given
1192ff0cc061SDimitry Andric /// parse point.
1193ff0cc061SDimitry Andric static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1194ff0cc061SDimitry Andric                              const CallSite &CS,
1195ff0cc061SDimitry Andric                              PartiallyConstructedSafepointRecord &result) {
11967d523365SDimitry Andric   DenseMap<Value *, Value *> PointerToBase;
11977d523365SDimitry Andric   findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1198ff0cc061SDimitry Andric 
1199ff0cc061SDimitry Andric   if (PrintBasePointers) {
1200ff0cc061SDimitry Andric     // Note: Need to print these in a stable order since this is checked in
1201ff0cc061SDimitry Andric     // some tests.
1202ff0cc061SDimitry Andric     errs() << "Base Pairs (w/o Relocation):\n";
1203ff0cc061SDimitry Andric     SmallVector<Value *, 64> Temp;
1204ff0cc061SDimitry Andric     Temp.reserve(PointerToBase.size());
1205ff0cc061SDimitry Andric     for (auto Pair : PointerToBase) {
1206ff0cc061SDimitry Andric       Temp.push_back(Pair.first);
1207ff0cc061SDimitry Andric     }
1208ff0cc061SDimitry Andric     std::sort(Temp.begin(), Temp.end(), order_by_name);
1209ff0cc061SDimitry Andric     for (Value *Ptr : Temp) {
1210ff0cc061SDimitry Andric       Value *Base = PointerToBase[Ptr];
12117d523365SDimitry Andric       errs() << " derived ";
12127d523365SDimitry Andric       Ptr->printAsOperand(errs(), false);
12137d523365SDimitry Andric       errs() << " base ";
12147d523365SDimitry Andric       Base->printAsOperand(errs(), false);
12157d523365SDimitry Andric       errs() << "\n";;
1216ff0cc061SDimitry Andric     }
1217ff0cc061SDimitry Andric   }
1218ff0cc061SDimitry Andric 
1219ff0cc061SDimitry Andric   result.PointerToBase = PointerToBase;
1220ff0cc061SDimitry Andric }
1221ff0cc061SDimitry Andric 
1222ff0cc061SDimitry Andric /// Given an updated version of the dataflow liveness results, update the
1223ff0cc061SDimitry Andric /// liveset and base pointer maps for the call site CS.
1224ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1225ff0cc061SDimitry Andric                                   const CallSite &CS,
1226ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &result);
1227ff0cc061SDimitry Andric 
1228ff0cc061SDimitry Andric static void recomputeLiveInValues(
12297d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1230ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1231ff0cc061SDimitry Andric   // TODO-PERF: reuse the original liveness, then simply run the dataflow
12327d523365SDimitry Andric   // again.  The old values are still live and will help it stabilize quickly.
1233ff0cc061SDimitry Andric   GCPtrLivenessData RevisedLivenessData;
1234ff0cc061SDimitry Andric   computeLiveInValues(DT, F, RevisedLivenessData);
1235ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1236ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1237ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1238ff0cc061SDimitry Andric     recomputeLiveInValues(RevisedLivenessData, CS, info);
1239ff0cc061SDimitry Andric   }
1240ff0cc061SDimitry Andric }
1241ff0cc061SDimitry Andric 
12427d523365SDimitry Andric // When inserting gc.relocate and gc.result calls, we need to ensure there are
12437d523365SDimitry Andric // no uses of the original value / return value between the gc.statepoint and
12447d523365SDimitry Andric // the gc.relocate / gc.result call.  One case which can arise is a phi node
12457d523365SDimitry Andric // starting one of the successor blocks.  We also need to be able to insert the
12467d523365SDimitry Andric // gc.relocates only on the path which goes through the statepoint.  We might
12477d523365SDimitry Andric // need to split an edge to make this possible.
1248ff0cc061SDimitry Andric static BasicBlock *
124997bc6c73SDimitry Andric normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
125097bc6c73SDimitry Andric                             DominatorTree &DT) {
1251ff0cc061SDimitry Andric   BasicBlock *Ret = BB;
12527d523365SDimitry Andric   if (!BB->getUniquePredecessor())
12537d523365SDimitry Andric     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1254ff0cc061SDimitry Andric 
12557d523365SDimitry Andric   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1256ff0cc061SDimitry Andric   // from it
1257ff0cc061SDimitry Andric   FoldSingleEntryPHINodes(Ret);
12587d523365SDimitry Andric   assert(!isa<PHINode>(Ret->begin()) &&
12597d523365SDimitry Andric          "All PHI nodes should have been removed!");
1260ff0cc061SDimitry Andric 
12617d523365SDimitry Andric   // At this point, we can safely insert a gc.relocate or gc.result as the first
12627d523365SDimitry Andric   // instruction in Ret if needed.
1263ff0cc061SDimitry Andric   return Ret;
1264ff0cc061SDimitry Andric }
1265ff0cc061SDimitry Andric 
12667d523365SDimitry Andric // Create new attribute set containing only attributes which can be transferred
1267ff0cc061SDimitry Andric // from original call to the safepoint.
1268ff0cc061SDimitry Andric static AttributeSet legalizeCallAttributes(AttributeSet AS) {
12697d523365SDimitry Andric   AttributeSet Ret;
1270ff0cc061SDimitry Andric 
1271ff0cc061SDimitry Andric   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
12727d523365SDimitry Andric     unsigned Index = AS.getSlotIndex(Slot);
1273ff0cc061SDimitry Andric 
12747d523365SDimitry Andric     if (Index == AttributeSet::ReturnIndex ||
12757d523365SDimitry Andric         Index == AttributeSet::FunctionIndex) {
1276ff0cc061SDimitry Andric 
12777d523365SDimitry Andric       for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
1278ff0cc061SDimitry Andric 
1279ff0cc061SDimitry Andric         // Do not allow certain attributes - just skip them
1280ff0cc061SDimitry Andric         // Safepoint can not be read only or read none.
12817d523365SDimitry Andric         if (Attr.hasAttribute(Attribute::ReadNone) ||
12827d523365SDimitry Andric             Attr.hasAttribute(Attribute::ReadOnly))
1283ff0cc061SDimitry Andric           continue;
1284ff0cc061SDimitry Andric 
12857d523365SDimitry Andric         // These attributes control the generation of the gc.statepoint call /
12867d523365SDimitry Andric         // invoke itself; and once the gc.statepoint is in place, they're of no
12877d523365SDimitry Andric         // use.
12887d523365SDimitry Andric         if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
12897d523365SDimitry Andric             Attr.hasAttribute("statepoint-id"))
12907d523365SDimitry Andric           continue;
12917d523365SDimitry Andric 
12927d523365SDimitry Andric         Ret = Ret.addAttributes(
12937d523365SDimitry Andric             AS.getContext(), Index,
12947d523365SDimitry Andric             AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
1295ff0cc061SDimitry Andric       }
1296ff0cc061SDimitry Andric     }
1297ff0cc061SDimitry Andric 
1298ff0cc061SDimitry Andric     // Just skip parameter attributes for now
1299ff0cc061SDimitry Andric   }
1300ff0cc061SDimitry Andric 
13017d523365SDimitry Andric   return Ret;
1302ff0cc061SDimitry Andric }
1303ff0cc061SDimitry Andric 
1304ff0cc061SDimitry Andric /// Helper function to place all gc relocates necessary for the given
1305ff0cc061SDimitry Andric /// statepoint.
1306ff0cc061SDimitry Andric /// Inputs:
1307ff0cc061SDimitry Andric ///   liveVariables - list of variables to be relocated.
1308ff0cc061SDimitry Andric ///   liveStart - index of the first live variable.
1309ff0cc061SDimitry Andric ///   basePtrs - base pointers.
1310ff0cc061SDimitry Andric ///   statepointToken - statepoint instruction to which relocates should be
1311ff0cc061SDimitry Andric ///   bound.
1312ff0cc061SDimitry Andric ///   Builder - Llvm IR builder to be used to construct new calls.
13137d523365SDimitry Andric static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1314ff0cc061SDimitry Andric                               const int LiveStart,
13157d523365SDimitry Andric                               ArrayRef<Value *> BasePtrs,
1316ff0cc061SDimitry Andric                               Instruction *StatepointToken,
1317ff0cc061SDimitry Andric                               IRBuilder<> Builder) {
13187d523365SDimitry Andric   if (LiveVariables.empty())
13197d523365SDimitry Andric     return;
1320ff0cc061SDimitry Andric 
13217d523365SDimitry Andric   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
13227d523365SDimitry Andric     auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
13237d523365SDimitry Andric     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
13247d523365SDimitry Andric     size_t Index = std::distance(LiveVec.begin(), ValIt);
13257d523365SDimitry Andric     assert(Index < LiveVec.size() && "Bug in std::find?");
13267d523365SDimitry Andric     return Index;
13277d523365SDimitry Andric   };
13287d523365SDimitry Andric 
13297d523365SDimitry Andric   // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
13307d523365SDimitry Andric   // unique declarations for each pointer type, but this proved problematic
13317d523365SDimitry Andric   // because the intrinsic mangling code is incomplete and fragile.  Since
13327d523365SDimitry Andric   // we're moving towards a single unified pointer type anyways, we can just
13337d523365SDimitry Andric   // cast everything to an i8* of the right address space.  A bitcast is added
13347d523365SDimitry Andric   // later to convert gc_relocate to the actual value's type.
13357d523365SDimitry Andric   Module *M = StatepointToken->getModule();
13367d523365SDimitry Andric   auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
13377d523365SDimitry Andric   Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
13387d523365SDimitry Andric   Value *GCRelocateDecl =
13397d523365SDimitry Andric     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1340ff0cc061SDimitry Andric 
1341ff0cc061SDimitry Andric   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1342ff0cc061SDimitry Andric     // Generate the gc.relocate call and save the result
1343ff0cc061SDimitry Andric     Value *BaseIdx =
13447d523365SDimitry Andric       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
13457d523365SDimitry Andric     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1346ff0cc061SDimitry Andric 
1347ff0cc061SDimitry Andric     // only specify a debug name if we can give a useful one
13487d523365SDimitry Andric     CallInst *Reloc = Builder.CreateCall(
1349ff0cc061SDimitry Andric         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
13507d523365SDimitry Andric         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1351ff0cc061SDimitry Andric     // Trick CodeGen into thinking there are lots of free registers at this
1352ff0cc061SDimitry Andric     // fake call.
13537d523365SDimitry Andric     Reloc->setCallingConv(CallingConv::Cold);
1354ff0cc061SDimitry Andric   }
13557d523365SDimitry Andric }
13567d523365SDimitry Andric 
13577d523365SDimitry Andric namespace {
13587d523365SDimitry Andric 
13597d523365SDimitry Andric /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
13607d523365SDimitry Andric /// avoids having to worry about keeping around dangling pointers to Values.
13617d523365SDimitry Andric class DeferredReplacement {
13627d523365SDimitry Andric   AssertingVH<Instruction> Old;
13637d523365SDimitry Andric   AssertingVH<Instruction> New;
13647d523365SDimitry Andric 
13657d523365SDimitry Andric public:
13667d523365SDimitry Andric   explicit DeferredReplacement(Instruction *Old, Instruction *New) :
13677d523365SDimitry Andric     Old(Old), New(New) {
13687d523365SDimitry Andric     assert(Old != New && "Not allowed!");
13697d523365SDimitry Andric   }
13707d523365SDimitry Andric 
13717d523365SDimitry Andric   /// Does the task represented by this instance.
13727d523365SDimitry Andric   void doReplacement() {
13737d523365SDimitry Andric     Instruction *OldI = Old;
13747d523365SDimitry Andric     Instruction *NewI = New;
13757d523365SDimitry Andric 
13767d523365SDimitry Andric     assert(OldI != NewI && "Disallowed at construction?!");
13777d523365SDimitry Andric 
13787d523365SDimitry Andric     Old = nullptr;
13797d523365SDimitry Andric     New = nullptr;
13807d523365SDimitry Andric 
13817d523365SDimitry Andric     if (NewI)
13827d523365SDimitry Andric       OldI->replaceAllUsesWith(NewI);
13837d523365SDimitry Andric     OldI->eraseFromParent();
13847d523365SDimitry Andric   }
13857d523365SDimitry Andric };
1386ff0cc061SDimitry Andric }
1387ff0cc061SDimitry Andric 
1388ff0cc061SDimitry Andric static void
13897d523365SDimitry Andric makeStatepointExplicitImpl(const CallSite CS, /* to replace */
13907d523365SDimitry Andric                            const SmallVectorImpl<Value *> &BasePtrs,
13917d523365SDimitry Andric                            const SmallVectorImpl<Value *> &LiveVariables,
13927d523365SDimitry Andric                            PartiallyConstructedSafepointRecord &Result,
13937d523365SDimitry Andric                            std::vector<DeferredReplacement> &Replacements) {
13947d523365SDimitry Andric   assert(BasePtrs.size() == LiveVariables.size());
13957d523365SDimitry Andric   assert((UseDeoptBundles || isStatepoint(CS)) &&
1396ff0cc061SDimitry Andric          "This method expects to be rewriting a statepoint");
1397ff0cc061SDimitry Andric 
1398ff0cc061SDimitry Andric   // Then go ahead and use the builder do actually do the inserts.  We insert
1399ff0cc061SDimitry Andric   // immediately before the previous instruction under the assumption that all
1400ff0cc061SDimitry Andric   // arguments will be available here.  We can't insert afterwards since we may
1401ff0cc061SDimitry Andric   // be replacing a terminator.
14027d523365SDimitry Andric   Instruction *InsertBefore = CS.getInstruction();
14037d523365SDimitry Andric   IRBuilder<> Builder(InsertBefore);
1404ff0cc061SDimitry Andric 
14057d523365SDimitry Andric   ArrayRef<Value *> GCArgs(LiveVariables);
14067d523365SDimitry Andric   uint64_t StatepointID = 0xABCDEF00;
14077d523365SDimitry Andric   uint32_t NumPatchBytes = 0;
14087d523365SDimitry Andric   uint32_t Flags = uint32_t(StatepointFlags::None);
14097d523365SDimitry Andric 
14107d523365SDimitry Andric   ArrayRef<Use> CallArgs;
14117d523365SDimitry Andric   ArrayRef<Use> DeoptArgs;
14127d523365SDimitry Andric   ArrayRef<Use> TransitionArgs;
14137d523365SDimitry Andric 
14147d523365SDimitry Andric   Value *CallTarget = nullptr;
14157d523365SDimitry Andric 
14167d523365SDimitry Andric   if (UseDeoptBundles) {
14177d523365SDimitry Andric     CallArgs = {CS.arg_begin(), CS.arg_end()};
14187d523365SDimitry Andric     DeoptArgs = GetDeoptBundleOperands(CS);
14197d523365SDimitry Andric     // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
14207d523365SDimitry Andric     // could have an operand bundle for that too.
14217d523365SDimitry Andric     AttributeSet OriginalAttrs = CS.getAttributes();
14227d523365SDimitry Andric 
14237d523365SDimitry Andric     Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
14247d523365SDimitry Andric                                                   "statepoint-id");
14257d523365SDimitry Andric     if (AttrID.isStringAttribute())
14267d523365SDimitry Andric       AttrID.getValueAsString().getAsInteger(10, StatepointID);
14277d523365SDimitry Andric 
14287d523365SDimitry Andric     Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
14297d523365SDimitry Andric         AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
14307d523365SDimitry Andric     if (AttrNumPatchBytes.isStringAttribute())
14317d523365SDimitry Andric       AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
14327d523365SDimitry Andric 
14337d523365SDimitry Andric     CallTarget = CS.getCalledValue();
14347d523365SDimitry Andric   } else {
14357d523365SDimitry Andric     // This branch will be gone soon, and we will soon only support the
14367d523365SDimitry Andric     // UseDeoptBundles == true configuration.
14377d523365SDimitry Andric     Statepoint OldSP(CS);
14387d523365SDimitry Andric     StatepointID = OldSP.getID();
14397d523365SDimitry Andric     NumPatchBytes = OldSP.getNumPatchBytes();
14407d523365SDimitry Andric     Flags = OldSP.getFlags();
14417d523365SDimitry Andric 
14427d523365SDimitry Andric     CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
14437d523365SDimitry Andric     DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
14447d523365SDimitry Andric     TransitionArgs = {OldSP.gc_transition_args_begin(),
14457d523365SDimitry Andric                       OldSP.gc_transition_args_end()};
14467d523365SDimitry Andric     CallTarget = OldSP.getCalledValue();
14477d523365SDimitry Andric   }
1448ff0cc061SDimitry Andric 
1449ff0cc061SDimitry Andric   // Create the statepoint given all the arguments
14507d523365SDimitry Andric   Instruction *Token = nullptr;
14517d523365SDimitry Andric   AttributeSet ReturnAttrs;
1452ff0cc061SDimitry Andric   if (CS.isCall()) {
14537d523365SDimitry Andric     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
14547d523365SDimitry Andric     CallInst *Call = Builder.CreateGCStatepointCall(
14557d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
14567d523365SDimitry Andric         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
14577d523365SDimitry Andric 
14587d523365SDimitry Andric     Call->setTailCall(ToReplace->isTailCall());
14597d523365SDimitry Andric     Call->setCallingConv(ToReplace->getCallingConv());
1460ff0cc061SDimitry Andric 
1461ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1462ff0cc061SDimitry Andric     // function attributes.
14637d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14647d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1465ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14667d523365SDimitry Andric     Call->setAttributes(NewAttrs.getFnAttributes());
14677d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1468ff0cc061SDimitry Andric 
14697d523365SDimitry Andric     Token = Call;
1470ff0cc061SDimitry Andric 
1471ff0cc061SDimitry Andric     // Put the following gc_result and gc_relocate calls immediately after the
1472ff0cc061SDimitry Andric     // the old call (which we're about to delete)
14737d523365SDimitry Andric     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
14747d523365SDimitry Andric     Builder.SetInsertPoint(ToReplace->getNextNode());
14757d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1476ff0cc061SDimitry Andric   } else {
14777d523365SDimitry Andric     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1478ff0cc061SDimitry Andric 
1479ff0cc061SDimitry Andric     // Insert the new invoke into the old block.  We'll remove the old one in a
1480ff0cc061SDimitry Andric     // moment at which point this will become the new terminator for the
1481ff0cc061SDimitry Andric     // original block.
14827d523365SDimitry Andric     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
14837d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
14847d523365SDimitry Andric         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
14857d523365SDimitry Andric         GCArgs, "statepoint_token");
14867d523365SDimitry Andric 
14877d523365SDimitry Andric     Invoke->setCallingConv(ToReplace->getCallingConv());
1488ff0cc061SDimitry Andric 
1489ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1490ff0cc061SDimitry Andric     // function attributes.
14917d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14927d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1493ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14947d523365SDimitry Andric     Invoke->setAttributes(NewAttrs.getFnAttributes());
14957d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1496ff0cc061SDimitry Andric 
14977d523365SDimitry Andric     Token = Invoke;
1498ff0cc061SDimitry Andric 
1499ff0cc061SDimitry Andric     // Generate gc relocates in exceptional path
15007d523365SDimitry Andric     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
15017d523365SDimitry Andric     assert(!isa<PHINode>(UnwindBlock->begin()) &&
15027d523365SDimitry Andric            UnwindBlock->getUniquePredecessor() &&
1503ff0cc061SDimitry Andric            "can't safely insert in this block!");
1504ff0cc061SDimitry Andric 
15057d523365SDimitry Andric     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
15067d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1507ff0cc061SDimitry Andric 
15087d523365SDimitry Andric     // Attach exceptional gc relocates to the landingpad.
15097d523365SDimitry Andric     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
15107d523365SDimitry Andric     Result.UnwindToken = ExceptionalToken;
1511ff0cc061SDimitry Andric 
15127d523365SDimitry Andric     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15137d523365SDimitry Andric     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
15147d523365SDimitry Andric                       Builder);
1515ff0cc061SDimitry Andric 
1516ff0cc061SDimitry Andric     // Generate gc relocates and returns for normal block
15177d523365SDimitry Andric     BasicBlock *NormalDest = ToReplace->getNormalDest();
15187d523365SDimitry Andric     assert(!isa<PHINode>(NormalDest->begin()) &&
15197d523365SDimitry Andric            NormalDest->getUniquePredecessor() &&
1520ff0cc061SDimitry Andric            "can't safely insert in this block!");
1521ff0cc061SDimitry Andric 
15227d523365SDimitry Andric     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1523ff0cc061SDimitry Andric 
1524ff0cc061SDimitry Andric     // gc relocates will be generated later as if it were regular call
1525ff0cc061SDimitry Andric     // statepoint
1526ff0cc061SDimitry Andric   }
15277d523365SDimitry Andric   assert(Token && "Should be set in one of the above branches!");
1528ff0cc061SDimitry Andric 
15297d523365SDimitry Andric   if (UseDeoptBundles) {
15307d523365SDimitry Andric     Token->setName("statepoint_token");
15317d523365SDimitry Andric     if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
15327d523365SDimitry Andric       StringRef Name =
15337d523365SDimitry Andric           CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
15347d523365SDimitry Andric       CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
15357d523365SDimitry Andric       GCResult->setAttributes(CS.getAttributes().getRetAttributes());
1536ff0cc061SDimitry Andric 
15377d523365SDimitry Andric       // We cannot RAUW or delete CS.getInstruction() because it could be in the
15387d523365SDimitry Andric       // live set of some other safepoint, in which case that safepoint's
15397d523365SDimitry Andric       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
15407d523365SDimitry Andric       // llvm::Instruction.  Instead, we defer the replacement and deletion to
15417d523365SDimitry Andric       // after the live sets have been made explicit in the IR, and we no longer
15427d523365SDimitry Andric       // have raw pointers to worry about.
15437d523365SDimitry Andric       Replacements.emplace_back(CS.getInstruction(), GCResult);
15447d523365SDimitry Andric     } else {
15457d523365SDimitry Andric       Replacements.emplace_back(CS.getInstruction(), nullptr);
15467d523365SDimitry Andric     }
15477d523365SDimitry Andric   } else {
15487d523365SDimitry Andric     assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1549ff0cc061SDimitry Andric            "only valid use before rewrite is gc.result");
15507d523365SDimitry Andric     assert(!CS.getInstruction()->hasOneUse() ||
15517d523365SDimitry Andric            isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
15527d523365SDimitry Andric 
15537d523365SDimitry Andric     // Take the name of the original statepoint token if there was one.
15547d523365SDimitry Andric     Token->takeName(CS.getInstruction());
1555ff0cc061SDimitry Andric 
1556ff0cc061SDimitry Andric     // Update the gc.result of the original statepoint (if any) to use the newly
1557ff0cc061SDimitry Andric     // inserted statepoint.  This is safe to do here since the token can't be
1558ff0cc061SDimitry Andric     // considered a live reference.
15597d523365SDimitry Andric     CS.getInstruction()->replaceAllUsesWith(Token);
15607d523365SDimitry Andric     CS.getInstruction()->eraseFromParent();
15617d523365SDimitry Andric   }
1562ff0cc061SDimitry Andric 
15637d523365SDimitry Andric   Result.StatepointToken = Token;
1564ff0cc061SDimitry Andric 
1565ff0cc061SDimitry Andric   // Second, create a gc.relocate for every live variable
15667d523365SDimitry Andric   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15677d523365SDimitry Andric   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1568ff0cc061SDimitry Andric }
1569ff0cc061SDimitry Andric 
1570ff0cc061SDimitry Andric namespace {
15717d523365SDimitry Andric struct NameOrdering {
15727d523365SDimitry Andric   Value *Base;
15737d523365SDimitry Andric   Value *Derived;
15747d523365SDimitry Andric 
15757d523365SDimitry Andric   bool operator()(NameOrdering const &a, NameOrdering const &b) {
15767d523365SDimitry Andric     return -1 == a.Derived->getName().compare(b.Derived->getName());
1577ff0cc061SDimitry Andric   }
1578ff0cc061SDimitry Andric };
1579ff0cc061SDimitry Andric }
1580ff0cc061SDimitry Andric 
15817d523365SDimitry Andric static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
15827d523365SDimitry Andric                            SmallVectorImpl<Value *> &LiveVec) {
15837d523365SDimitry Andric   assert(BaseVec.size() == LiveVec.size());
15847d523365SDimitry Andric 
15857d523365SDimitry Andric   SmallVector<NameOrdering, 64> Temp;
15867d523365SDimitry Andric   for (size_t i = 0; i < BaseVec.size(); i++) {
15877d523365SDimitry Andric     NameOrdering v;
15887d523365SDimitry Andric     v.Base = BaseVec[i];
15897d523365SDimitry Andric     v.Derived = LiveVec[i];
15907d523365SDimitry Andric     Temp.push_back(v);
1591ff0cc061SDimitry Andric   }
15927d523365SDimitry Andric 
15937d523365SDimitry Andric   std::sort(Temp.begin(), Temp.end(), NameOrdering());
15947d523365SDimitry Andric   for (size_t i = 0; i < BaseVec.size(); i++) {
15957d523365SDimitry Andric     BaseVec[i] = Temp[i].Base;
15967d523365SDimitry Andric     LiveVec[i] = Temp[i].Derived;
1597ff0cc061SDimitry Andric   }
1598ff0cc061SDimitry Andric }
1599ff0cc061SDimitry Andric 
1600ff0cc061SDimitry Andric // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1601ff0cc061SDimitry Andric // which make the relocations happening at this safepoint explicit.
1602ff0cc061SDimitry Andric //
1603ff0cc061SDimitry Andric // WARNING: Does not do any fixup to adjust users of the original live
1604ff0cc061SDimitry Andric // values.  That's the callers responsibility.
1605ff0cc061SDimitry Andric static void
16067d523365SDimitry Andric makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
16077d523365SDimitry Andric                        PartiallyConstructedSafepointRecord &Result,
16087d523365SDimitry Andric                        std::vector<DeferredReplacement> &Replacements) {
16097d523365SDimitry Andric   const auto &LiveSet = Result.LiveSet;
16107d523365SDimitry Andric   const auto &PointerToBase = Result.PointerToBase;
1611ff0cc061SDimitry Andric 
1612ff0cc061SDimitry Andric   // Convert to vector for efficient cross referencing.
16137d523365SDimitry Andric   SmallVector<Value *, 64> BaseVec, LiveVec;
16147d523365SDimitry Andric   LiveVec.reserve(LiveSet.size());
16157d523365SDimitry Andric   BaseVec.reserve(LiveSet.size());
16167d523365SDimitry Andric   for (Value *L : LiveSet) {
16177d523365SDimitry Andric     LiveVec.push_back(L);
16187d523365SDimitry Andric     assert(PointerToBase.count(L));
16197d523365SDimitry Andric     Value *Base = PointerToBase.find(L)->second;
16207d523365SDimitry Andric     BaseVec.push_back(Base);
1621ff0cc061SDimitry Andric   }
16227d523365SDimitry Andric   assert(LiveVec.size() == BaseVec.size());
1623ff0cc061SDimitry Andric 
1624ff0cc061SDimitry Andric   // To make the output IR slightly more stable (for use in diffs), ensure a
1625ff0cc061SDimitry Andric   // fixed order of the values in the safepoint (by sorting the value name).
1626ff0cc061SDimitry Andric   // The order is otherwise meaningless.
16277d523365SDimitry Andric   StabilizeOrder(BaseVec, LiveVec);
1628ff0cc061SDimitry Andric 
1629ff0cc061SDimitry Andric   // Do the actual rewriting and delete the old statepoint
16307d523365SDimitry Andric   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1631ff0cc061SDimitry Andric }
1632ff0cc061SDimitry Andric 
1633ff0cc061SDimitry Andric // Helper function for the relocationViaAlloca.
16347d523365SDimitry Andric //
16357d523365SDimitry Andric // It receives iterator to the statepoint gc relocates and emits a store to the
16367d523365SDimitry Andric // assigned location (via allocaMap) for the each one of them.  It adds the
16377d523365SDimitry Andric // visited values into the visitedLiveValues set, which we will later use them
16387d523365SDimitry Andric // for sanity checking.
1639ff0cc061SDimitry Andric static void
1640ff0cc061SDimitry Andric insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1641ff0cc061SDimitry Andric                        DenseMap<Value *, Value *> &AllocaMap,
1642ff0cc061SDimitry Andric                        DenseSet<Value *> &VisitedLiveValues) {
1643ff0cc061SDimitry Andric 
1644ff0cc061SDimitry Andric   for (User *U : GCRelocs) {
1645ff0cc061SDimitry Andric     if (!isa<IntrinsicInst>(U))
1646ff0cc061SDimitry Andric       continue;
1647ff0cc061SDimitry Andric 
1648ff0cc061SDimitry Andric     IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1649ff0cc061SDimitry Andric 
1650ff0cc061SDimitry Andric     // We only care about relocates
1651ff0cc061SDimitry Andric     if (RelocatedValue->getIntrinsicID() !=
1652ff0cc061SDimitry Andric         Intrinsic::experimental_gc_relocate) {
1653ff0cc061SDimitry Andric       continue;
1654ff0cc061SDimitry Andric     }
1655ff0cc061SDimitry Andric 
1656ff0cc061SDimitry Andric     GCRelocateOperands RelocateOperands(RelocatedValue);
1657ff0cc061SDimitry Andric     Value *OriginalValue =
1658ff0cc061SDimitry Andric         const_cast<Value *>(RelocateOperands.getDerivedPtr());
1659ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue));
1660ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1661ff0cc061SDimitry Andric 
1662ff0cc061SDimitry Andric     // Emit store into the related alloca
16637d523365SDimitry Andric     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1664ff0cc061SDimitry Andric     // the correct type according to alloca.
16657d523365SDimitry Andric     assert(RelocatedValue->getNextNode() &&
16667d523365SDimitry Andric            "Should always have one since it's not a terminator");
1667ff0cc061SDimitry Andric     IRBuilder<> Builder(RelocatedValue->getNextNode());
1668ff0cc061SDimitry Andric     Value *CastedRelocatedValue =
16697d523365SDimitry Andric       Builder.CreateBitCast(RelocatedValue,
16707d523365SDimitry Andric                             cast<AllocaInst>(Alloca)->getAllocatedType(),
16717d523365SDimitry Andric                             suffixed_name_or(RelocatedValue, ".casted", ""));
1672ff0cc061SDimitry Andric 
1673ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1674ff0cc061SDimitry Andric     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1675ff0cc061SDimitry Andric 
1676ff0cc061SDimitry Andric #ifndef NDEBUG
1677ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1678ff0cc061SDimitry Andric #endif
1679ff0cc061SDimitry Andric   }
1680ff0cc061SDimitry Andric }
1681ff0cc061SDimitry Andric 
1682ff0cc061SDimitry Andric // Helper function for the "relocationViaAlloca". Similar to the
1683ff0cc061SDimitry Andric // "insertRelocationStores" but works for rematerialized values.
1684ff0cc061SDimitry Andric static void
1685ff0cc061SDimitry Andric insertRematerializationStores(
1686ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues,
1687ff0cc061SDimitry Andric   DenseMap<Value *, Value *> &AllocaMap,
1688ff0cc061SDimitry Andric   DenseSet<Value *> &VisitedLiveValues) {
1689ff0cc061SDimitry Andric 
1690ff0cc061SDimitry Andric   for (auto RematerializedValuePair: RematerializedValues) {
1691ff0cc061SDimitry Andric     Instruction *RematerializedValue = RematerializedValuePair.first;
1692ff0cc061SDimitry Andric     Value *OriginalValue = RematerializedValuePair.second;
1693ff0cc061SDimitry Andric 
1694ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue) &&
1695ff0cc061SDimitry Andric            "Can not find alloca for rematerialized value");
1696ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1697ff0cc061SDimitry Andric 
1698ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1699ff0cc061SDimitry Andric     Store->insertAfter(RematerializedValue);
1700ff0cc061SDimitry Andric 
1701ff0cc061SDimitry Andric #ifndef NDEBUG
1702ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1703ff0cc061SDimitry Andric #endif
1704ff0cc061SDimitry Andric   }
1705ff0cc061SDimitry Andric }
1706ff0cc061SDimitry Andric 
17077d523365SDimitry Andric /// Do all the relocation update via allocas and mem2reg
1708ff0cc061SDimitry Andric static void relocationViaAlloca(
1709ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
17107d523365SDimitry Andric     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1711ff0cc061SDimitry Andric #ifndef NDEBUG
1712ff0cc061SDimitry Andric   // record initial number of (static) allocas; we'll check we have the same
1713ff0cc061SDimitry Andric   // number when we get done.
1714ff0cc061SDimitry Andric   int InitialAllocaNum = 0;
1715ff0cc061SDimitry Andric   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1716ff0cc061SDimitry Andric        I++)
1717ff0cc061SDimitry Andric     if (isa<AllocaInst>(*I))
1718ff0cc061SDimitry Andric       InitialAllocaNum++;
1719ff0cc061SDimitry Andric #endif
1720ff0cc061SDimitry Andric 
1721ff0cc061SDimitry Andric   // TODO-PERF: change data structures, reserve
1722ff0cc061SDimitry Andric   DenseMap<Value *, Value *> AllocaMap;
1723ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 200> PromotableAllocas;
1724ff0cc061SDimitry Andric   // Used later to chack that we have enough allocas to store all values
1725ff0cc061SDimitry Andric   std::size_t NumRematerializedValues = 0;
1726ff0cc061SDimitry Andric   PromotableAllocas.reserve(Live.size());
1727ff0cc061SDimitry Andric 
1728ff0cc061SDimitry Andric   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1729ff0cc061SDimitry Andric   // "PromotableAllocas"
1730ff0cc061SDimitry Andric   auto emitAllocaFor = [&](Value *LiveValue) {
1731ff0cc061SDimitry Andric     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1732ff0cc061SDimitry Andric                                         F.getEntryBlock().getFirstNonPHI());
1733ff0cc061SDimitry Andric     AllocaMap[LiveValue] = Alloca;
1734ff0cc061SDimitry Andric     PromotableAllocas.push_back(Alloca);
1735ff0cc061SDimitry Andric   };
1736ff0cc061SDimitry Andric 
17377d523365SDimitry Andric   // Emit alloca for each live gc pointer
17387d523365SDimitry Andric   for (Value *V : Live)
17397d523365SDimitry Andric     emitAllocaFor(V);
1740ff0cc061SDimitry Andric 
17417d523365SDimitry Andric   // Emit allocas for rematerialized values
17427d523365SDimitry Andric   for (const auto &Info : Records)
1743ff0cc061SDimitry Andric     for (auto RematerializedValuePair : Info.RematerializedValues) {
1744ff0cc061SDimitry Andric       Value *OriginalValue = RematerializedValuePair.second;
1745ff0cc061SDimitry Andric       if (AllocaMap.count(OriginalValue) != 0)
1746ff0cc061SDimitry Andric         continue;
1747ff0cc061SDimitry Andric 
1748ff0cc061SDimitry Andric       emitAllocaFor(OriginalValue);
1749ff0cc061SDimitry Andric       ++NumRematerializedValues;
1750ff0cc061SDimitry Andric     }
1751ff0cc061SDimitry Andric 
1752ff0cc061SDimitry Andric   // The next two loops are part of the same conceptual operation.  We need to
1753ff0cc061SDimitry Andric   // insert a store to the alloca after the original def and at each
1754ff0cc061SDimitry Andric   // redefinition.  We need to insert a load before each use.  These are split
1755ff0cc061SDimitry Andric   // into distinct loops for performance reasons.
1756ff0cc061SDimitry Andric 
17577d523365SDimitry Andric   // Update gc pointer after each statepoint: either store a relocated value or
17587d523365SDimitry Andric   // null (if no relocated value was found for this gc pointer and it is not a
17597d523365SDimitry Andric   // gc_result).  This must happen before we update the statepoint with load of
17607d523365SDimitry Andric   // alloca otherwise we lose the link between statepoint and old def.
17617d523365SDimitry Andric   for (const auto &Info : Records) {
1762ff0cc061SDimitry Andric     Value *Statepoint = Info.StatepointToken;
1763ff0cc061SDimitry Andric 
1764ff0cc061SDimitry Andric     // This will be used for consistency check
1765ff0cc061SDimitry Andric     DenseSet<Value *> VisitedLiveValues;
1766ff0cc061SDimitry Andric 
1767ff0cc061SDimitry Andric     // Insert stores for normal statepoint gc relocates
1768ff0cc061SDimitry Andric     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1769ff0cc061SDimitry Andric 
1770ff0cc061SDimitry Andric     // In case if it was invoke statepoint
1771ff0cc061SDimitry Andric     // we will insert stores for exceptional path gc relocates.
1772ff0cc061SDimitry Andric     if (isa<InvokeInst>(Statepoint)) {
1773ff0cc061SDimitry Andric       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1774ff0cc061SDimitry Andric                              VisitedLiveValues);
1775ff0cc061SDimitry Andric     }
1776ff0cc061SDimitry Andric 
1777ff0cc061SDimitry Andric     // Do similar thing with rematerialized values
1778ff0cc061SDimitry Andric     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1779ff0cc061SDimitry Andric                                   VisitedLiveValues);
1780ff0cc061SDimitry Andric 
1781ff0cc061SDimitry Andric     if (ClobberNonLive) {
17827d523365SDimitry Andric       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1783ff0cc061SDimitry Andric       // the gc.statepoint.  This will turn some subtle GC problems into
1784ff0cc061SDimitry Andric       // slightly easier to debug SEGVs.  Note that on large IR files with
1785ff0cc061SDimitry Andric       // lots of gc.statepoints this is extremely costly both memory and time
1786ff0cc061SDimitry Andric       // wise.
1787ff0cc061SDimitry Andric       SmallVector<AllocaInst *, 64> ToClobber;
1788ff0cc061SDimitry Andric       for (auto Pair : AllocaMap) {
1789ff0cc061SDimitry Andric         Value *Def = Pair.first;
1790ff0cc061SDimitry Andric         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1791ff0cc061SDimitry Andric 
1792ff0cc061SDimitry Andric         // This value was relocated
1793ff0cc061SDimitry Andric         if (VisitedLiveValues.count(Def)) {
1794ff0cc061SDimitry Andric           continue;
1795ff0cc061SDimitry Andric         }
1796ff0cc061SDimitry Andric         ToClobber.push_back(Alloca);
1797ff0cc061SDimitry Andric       }
1798ff0cc061SDimitry Andric 
1799ff0cc061SDimitry Andric       auto InsertClobbersAt = [&](Instruction *IP) {
1800ff0cc061SDimitry Andric         for (auto *AI : ToClobber) {
1801ff0cc061SDimitry Andric           auto AIType = cast<PointerType>(AI->getType());
1802ff0cc061SDimitry Andric           auto PT = cast<PointerType>(AIType->getElementType());
1803ff0cc061SDimitry Andric           Constant *CPN = ConstantPointerNull::get(PT);
1804ff0cc061SDimitry Andric           StoreInst *Store = new StoreInst(CPN, AI);
1805ff0cc061SDimitry Andric           Store->insertBefore(IP);
1806ff0cc061SDimitry Andric         }
1807ff0cc061SDimitry Andric       };
1808ff0cc061SDimitry Andric 
1809ff0cc061SDimitry Andric       // Insert the clobbering stores.  These may get intermixed with the
1810ff0cc061SDimitry Andric       // gc.results and gc.relocates, but that's fine.
1811ff0cc061SDimitry Andric       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
18127d523365SDimitry Andric         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
18137d523365SDimitry Andric         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1814ff0cc061SDimitry Andric       } else {
18157d523365SDimitry Andric         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1816ff0cc061SDimitry Andric       }
1817ff0cc061SDimitry Andric     }
1818ff0cc061SDimitry Andric   }
18197d523365SDimitry Andric 
18207d523365SDimitry Andric   // Update use with load allocas and add store for gc_relocated.
1821ff0cc061SDimitry Andric   for (auto Pair : AllocaMap) {
1822ff0cc061SDimitry Andric     Value *Def = Pair.first;
1823ff0cc061SDimitry Andric     Value *Alloca = Pair.second;
1824ff0cc061SDimitry Andric 
18257d523365SDimitry Andric     // We pre-record the uses of allocas so that we dont have to worry about
18267d523365SDimitry Andric     // later update that changes the user information..
18277d523365SDimitry Andric 
1828ff0cc061SDimitry Andric     SmallVector<Instruction *, 20> Uses;
1829ff0cc061SDimitry Andric     // PERF: trade a linear scan for repeated reallocation
1830ff0cc061SDimitry Andric     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1831ff0cc061SDimitry Andric     for (User *U : Def->users()) {
1832ff0cc061SDimitry Andric       if (!isa<ConstantExpr>(U)) {
1833ff0cc061SDimitry Andric         // If the def has a ConstantExpr use, then the def is either a
1834ff0cc061SDimitry Andric         // ConstantExpr use itself or null.  In either case
1835ff0cc061SDimitry Andric         // (recursively in the first, directly in the second), the oop
1836ff0cc061SDimitry Andric         // it is ultimately dependent on is null and this particular
1837ff0cc061SDimitry Andric         // use does not need to be fixed up.
1838ff0cc061SDimitry Andric         Uses.push_back(cast<Instruction>(U));
1839ff0cc061SDimitry Andric       }
1840ff0cc061SDimitry Andric     }
1841ff0cc061SDimitry Andric 
1842ff0cc061SDimitry Andric     std::sort(Uses.begin(), Uses.end());
1843ff0cc061SDimitry Andric     auto Last = std::unique(Uses.begin(), Uses.end());
1844ff0cc061SDimitry Andric     Uses.erase(Last, Uses.end());
1845ff0cc061SDimitry Andric 
1846ff0cc061SDimitry Andric     for (Instruction *Use : Uses) {
1847ff0cc061SDimitry Andric       if (isa<PHINode>(Use)) {
1848ff0cc061SDimitry Andric         PHINode *Phi = cast<PHINode>(Use);
1849ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1850ff0cc061SDimitry Andric           if (Def == Phi->getIncomingValue(i)) {
1851ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1852ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1853ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1854ff0cc061SDimitry Andric           }
1855ff0cc061SDimitry Andric         }
1856ff0cc061SDimitry Andric       } else {
1857ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", Use);
1858ff0cc061SDimitry Andric         Use->replaceUsesOfWith(Def, Load);
1859ff0cc061SDimitry Andric       }
1860ff0cc061SDimitry Andric     }
1861ff0cc061SDimitry Andric 
18627d523365SDimitry Andric     // Emit store for the initial gc value.  Store must be inserted after load,
18637d523365SDimitry Andric     // otherwise store will be in alloca's use list and an extra load will be
18647d523365SDimitry Andric     // inserted before it.
1865ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(Def, Alloca);
1866ff0cc061SDimitry Andric     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1867ff0cc061SDimitry Andric       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1868ff0cc061SDimitry Andric         // InvokeInst is a TerminatorInst so the store need to be inserted
1869ff0cc061SDimitry Andric         // into its normal destination block.
1870ff0cc061SDimitry Andric         BasicBlock *NormalDest = Invoke->getNormalDest();
1871ff0cc061SDimitry Andric         Store->insertBefore(NormalDest->getFirstNonPHI());
1872ff0cc061SDimitry Andric       } else {
1873ff0cc061SDimitry Andric         assert(!Inst->isTerminator() &&
1874ff0cc061SDimitry Andric                "The only TerminatorInst that can produce a value is "
1875ff0cc061SDimitry Andric                "InvokeInst which is handled above.");
1876ff0cc061SDimitry Andric         Store->insertAfter(Inst);
1877ff0cc061SDimitry Andric       }
1878ff0cc061SDimitry Andric     } else {
1879ff0cc061SDimitry Andric       assert(isa<Argument>(Def));
1880ff0cc061SDimitry Andric       Store->insertAfter(cast<Instruction>(Alloca));
1881ff0cc061SDimitry Andric     }
1882ff0cc061SDimitry Andric   }
1883ff0cc061SDimitry Andric 
1884ff0cc061SDimitry Andric   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1885ff0cc061SDimitry Andric          "we must have the same allocas with lives");
1886ff0cc061SDimitry Andric   if (!PromotableAllocas.empty()) {
18877d523365SDimitry Andric     // Apply mem2reg to promote alloca to SSA
1888ff0cc061SDimitry Andric     PromoteMemToReg(PromotableAllocas, DT);
1889ff0cc061SDimitry Andric   }
1890ff0cc061SDimitry Andric 
1891ff0cc061SDimitry Andric #ifndef NDEBUG
18927d523365SDimitry Andric   for (auto &I : F.getEntryBlock())
18937d523365SDimitry Andric     if (isa<AllocaInst>(I))
1894ff0cc061SDimitry Andric       InitialAllocaNum--;
1895ff0cc061SDimitry Andric   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1896ff0cc061SDimitry Andric #endif
1897ff0cc061SDimitry Andric }
1898ff0cc061SDimitry Andric 
1899ff0cc061SDimitry Andric /// Implement a unique function which doesn't require we sort the input
1900ff0cc061SDimitry Andric /// vector.  Doing so has the effect of changing the output of a couple of
1901ff0cc061SDimitry Andric /// tests in ways which make them less useful in testing fused safepoints.
1902ff0cc061SDimitry Andric template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
19038f0fd8f6SDimitry Andric   SmallSet<T, 8> Seen;
19048f0fd8f6SDimitry Andric   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
19058f0fd8f6SDimitry Andric               return !Seen.insert(V).second;
19068f0fd8f6SDimitry Andric             }), Vec.end());
1907ff0cc061SDimitry Andric }
1908ff0cc061SDimitry Andric 
1909ff0cc061SDimitry Andric /// Insert holders so that each Value is obviously live through the entire
1910ff0cc061SDimitry Andric /// lifetime of the call.
1911ff0cc061SDimitry Andric static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1912ff0cc061SDimitry Andric                                  SmallVectorImpl<CallInst *> &Holders) {
1913ff0cc061SDimitry Andric   if (Values.empty())
1914ff0cc061SDimitry Andric     // No values to hold live, might as well not insert the empty holder
1915ff0cc061SDimitry Andric     return;
1916ff0cc061SDimitry Andric 
19177d523365SDimitry Andric   Module *M = CS.getInstruction()->getModule();
1918ff0cc061SDimitry Andric   // Use a dummy vararg function to actually hold the values live
1919ff0cc061SDimitry Andric   Function *Func = cast<Function>(M->getOrInsertFunction(
1920ff0cc061SDimitry Andric       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1921ff0cc061SDimitry Andric   if (CS.isCall()) {
1922ff0cc061SDimitry Andric     // For call safepoints insert dummy calls right after safepoint
19237d523365SDimitry Andric     Holders.push_back(CallInst::Create(Func, Values, "",
19247d523365SDimitry Andric                                        &*++CS.getInstruction()->getIterator()));
1925ff0cc061SDimitry Andric     return;
1926ff0cc061SDimitry Andric   }
1927ff0cc061SDimitry Andric   // For invoke safepooints insert dummy calls both in normal and
1928ff0cc061SDimitry Andric   // exceptional destination blocks
1929ff0cc061SDimitry Andric   auto *II = cast<InvokeInst>(CS.getInstruction());
1930ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19317d523365SDimitry Andric       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1932ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19337d523365SDimitry Andric       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1934ff0cc061SDimitry Andric }
1935ff0cc061SDimitry Andric 
1936ff0cc061SDimitry Andric static void findLiveReferences(
19377d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1938ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1939ff0cc061SDimitry Andric   GCPtrLivenessData OriginalLivenessData;
1940ff0cc061SDimitry Andric   computeLiveInValues(DT, F, OriginalLivenessData);
1941ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1942ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1943ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1944ff0cc061SDimitry Andric     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1945ff0cc061SDimitry Andric   }
1946ff0cc061SDimitry Andric }
1947ff0cc061SDimitry Andric 
1948ff0cc061SDimitry Andric /// Remove any vector of pointers from the live set by scalarizing them over the
1949ff0cc061SDimitry Andric /// statepoint instruction.  Adds the scalarized pieces to the live set.  It
19507d523365SDimitry Andric /// would be preferable to include the vector in the statepoint itself, but
1951ff0cc061SDimitry Andric /// the lowering code currently does not handle that.  Extending it would be
1952ff0cc061SDimitry Andric /// slightly non-trivial since it requires a format change.  Given how rare
19537d523365SDimitry Andric /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1954ff0cc061SDimitry Andric static void splitVectorValues(Instruction *StatepointInst,
19553dac3a9bSDimitry Andric                               StatepointLiveSetTy &LiveSet,
19563dac3a9bSDimitry Andric                               DenseMap<Value *, Value *>& PointerToBase,
19573dac3a9bSDimitry Andric                               DominatorTree &DT) {
1958ff0cc061SDimitry Andric   SmallVector<Value *, 16> ToSplit;
1959ff0cc061SDimitry Andric   for (Value *V : LiveSet)
1960ff0cc061SDimitry Andric     if (isa<VectorType>(V->getType()))
1961ff0cc061SDimitry Andric       ToSplit.push_back(V);
1962ff0cc061SDimitry Andric 
1963ff0cc061SDimitry Andric   if (ToSplit.empty())
1964ff0cc061SDimitry Andric     return;
1965ff0cc061SDimitry Andric 
19663dac3a9bSDimitry Andric   DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
19673dac3a9bSDimitry Andric 
1968ff0cc061SDimitry Andric   Function &F = *(StatepointInst->getParent()->getParent());
1969ff0cc061SDimitry Andric 
1970ff0cc061SDimitry Andric   DenseMap<Value *, AllocaInst *> AllocaMap;
1971ff0cc061SDimitry Andric   // First is normal return, second is exceptional return (invoke only)
1972ff0cc061SDimitry Andric   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1973ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1974ff0cc061SDimitry Andric     AllocaInst *Alloca =
1975ff0cc061SDimitry Andric         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1976ff0cc061SDimitry Andric     AllocaMap[V] = Alloca;
1977ff0cc061SDimitry Andric 
1978ff0cc061SDimitry Andric     VectorType *VT = cast<VectorType>(V->getType());
1979ff0cc061SDimitry Andric     IRBuilder<> Builder(StatepointInst);
1980ff0cc061SDimitry Andric     SmallVector<Value *, 16> Elements;
1981ff0cc061SDimitry Andric     for (unsigned i = 0; i < VT->getNumElements(); i++)
1982ff0cc061SDimitry Andric       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
19833dac3a9bSDimitry Andric     ElementMapping[V] = Elements;
1984ff0cc061SDimitry Andric 
1985ff0cc061SDimitry Andric     auto InsertVectorReform = [&](Instruction *IP) {
1986ff0cc061SDimitry Andric       Builder.SetInsertPoint(IP);
1987ff0cc061SDimitry Andric       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1988ff0cc061SDimitry Andric       Value *ResultVec = UndefValue::get(VT);
1989ff0cc061SDimitry Andric       for (unsigned i = 0; i < VT->getNumElements(); i++)
1990ff0cc061SDimitry Andric         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1991ff0cc061SDimitry Andric                                                 Builder.getInt32(i));
1992ff0cc061SDimitry Andric       return ResultVec;
1993ff0cc061SDimitry Andric     };
1994ff0cc061SDimitry Andric 
1995ff0cc061SDimitry Andric     if (isa<CallInst>(StatepointInst)) {
1996ff0cc061SDimitry Andric       BasicBlock::iterator Next(StatepointInst);
1997ff0cc061SDimitry Andric       Next++;
1998ff0cc061SDimitry Andric       Instruction *IP = &*(Next);
1999ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
2000ff0cc061SDimitry Andric       Replacements[V].second = nullptr;
2001ff0cc061SDimitry Andric     } else {
2002ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
2003ff0cc061SDimitry Andric       // We've already normalized - check that we don't have shared destination
2004ff0cc061SDimitry Andric       // blocks
2005ff0cc061SDimitry Andric       BasicBlock *NormalDest = Invoke->getNormalDest();
2006ff0cc061SDimitry Andric       assert(!isa<PHINode>(NormalDest->begin()));
2007ff0cc061SDimitry Andric       BasicBlock *UnwindDest = Invoke->getUnwindDest();
2008ff0cc061SDimitry Andric       assert(!isa<PHINode>(UnwindDest->begin()));
2009ff0cc061SDimitry Andric       // Insert insert element sequences in both successors
2010ff0cc061SDimitry Andric       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
2011ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
2012ff0cc061SDimitry Andric       IP = &*(UnwindDest->getFirstInsertionPt());
2013ff0cc061SDimitry Andric       Replacements[V].second = InsertVectorReform(IP);
2014ff0cc061SDimitry Andric     }
2015ff0cc061SDimitry Andric   }
20163dac3a9bSDimitry Andric 
2017ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
2018ff0cc061SDimitry Andric     AllocaInst *Alloca = AllocaMap[V];
2019ff0cc061SDimitry Andric 
2020ff0cc061SDimitry Andric     // Capture all users before we start mutating use lists
2021ff0cc061SDimitry Andric     SmallVector<Instruction *, 16> Users;
2022ff0cc061SDimitry Andric     for (User *U : V->users())
2023ff0cc061SDimitry Andric       Users.push_back(cast<Instruction>(U));
2024ff0cc061SDimitry Andric 
2025ff0cc061SDimitry Andric     for (Instruction *I : Users) {
2026ff0cc061SDimitry Andric       if (auto Phi = dyn_cast<PHINode>(I)) {
2027ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2028ff0cc061SDimitry Andric           if (V == Phi->getIncomingValue(i)) {
2029ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
2030ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
2031ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
2032ff0cc061SDimitry Andric           }
2033ff0cc061SDimitry Andric       } else {
2034ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", I);
2035ff0cc061SDimitry Andric         I->replaceUsesOfWith(V, Load);
2036ff0cc061SDimitry Andric       }
2037ff0cc061SDimitry Andric     }
2038ff0cc061SDimitry Andric 
2039ff0cc061SDimitry Andric     // Store the original value and the replacement value into the alloca
2040ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(V, Alloca);
2041ff0cc061SDimitry Andric     if (auto I = dyn_cast<Instruction>(V))
2042ff0cc061SDimitry Andric       Store->insertAfter(I);
2043ff0cc061SDimitry Andric     else
2044ff0cc061SDimitry Andric       Store->insertAfter(Alloca);
2045ff0cc061SDimitry Andric 
2046ff0cc061SDimitry Andric     // Normal return for invoke, or call return
2047ff0cc061SDimitry Andric     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2048ff0cc061SDimitry Andric     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2049ff0cc061SDimitry Andric     // Unwind return for invoke only
2050ff0cc061SDimitry Andric     Replacement = cast_or_null<Instruction>(Replacements[V].second);
2051ff0cc061SDimitry Andric     if (Replacement)
2052ff0cc061SDimitry Andric       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2053ff0cc061SDimitry Andric   }
2054ff0cc061SDimitry Andric 
2055ff0cc061SDimitry Andric   // apply mem2reg to promote alloca to SSA
2056ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
2057ff0cc061SDimitry Andric   for (Value *V : ToSplit)
2058ff0cc061SDimitry Andric     Allocas.push_back(AllocaMap[V]);
2059ff0cc061SDimitry Andric   PromoteMemToReg(Allocas, DT);
20603dac3a9bSDimitry Andric 
20613dac3a9bSDimitry Andric   // Update our tracking of live pointers and base mappings to account for the
20623dac3a9bSDimitry Andric   // changes we just made.
20633dac3a9bSDimitry Andric   for (Value *V : ToSplit) {
20643dac3a9bSDimitry Andric     auto &Elements = ElementMapping[V];
20653dac3a9bSDimitry Andric 
20663dac3a9bSDimitry Andric     LiveSet.erase(V);
20673dac3a9bSDimitry Andric     LiveSet.insert(Elements.begin(), Elements.end());
20683dac3a9bSDimitry Andric     // We need to update the base mapping as well.
20693dac3a9bSDimitry Andric     assert(PointerToBase.count(V));
20703dac3a9bSDimitry Andric     Value *OldBase = PointerToBase[V];
20713dac3a9bSDimitry Andric     auto &BaseElements = ElementMapping[OldBase];
20723dac3a9bSDimitry Andric     PointerToBase.erase(V);
20733dac3a9bSDimitry Andric     assert(Elements.size() == BaseElements.size());
20743dac3a9bSDimitry Andric     for (unsigned i = 0; i < Elements.size(); i++) {
20753dac3a9bSDimitry Andric       Value *Elem = Elements[i];
20763dac3a9bSDimitry Andric       PointerToBase[Elem] = BaseElements[i];
20773dac3a9bSDimitry Andric     }
20783dac3a9bSDimitry Andric   }
2079ff0cc061SDimitry Andric }
2080ff0cc061SDimitry Andric 
2081ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". It walks use chain
2082ff0cc061SDimitry Andric // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2083ff0cc061SDimitry Andric // values are visited (currently it is GEP's and casts). Returns true if it
20847d523365SDimitry Andric // successfully reached "BaseValue" and false otherwise.
2085ff0cc061SDimitry Andric // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2086ff0cc061SDimitry Andric // recorded.
2087ff0cc061SDimitry Andric static bool findRematerializableChainToBasePointer(
2088ff0cc061SDimitry Andric   SmallVectorImpl<Instruction*> &ChainToBase,
2089ff0cc061SDimitry Andric   Value *CurrentValue, Value *BaseValue) {
2090ff0cc061SDimitry Andric 
2091ff0cc061SDimitry Andric   // We have found a base value
2092ff0cc061SDimitry Andric   if (CurrentValue == BaseValue) {
2093ff0cc061SDimitry Andric     return true;
2094ff0cc061SDimitry Andric   }
2095ff0cc061SDimitry Andric 
2096ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2097ff0cc061SDimitry Andric     ChainToBase.push_back(GEP);
2098ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
2099ff0cc061SDimitry Andric                                                   GEP->getPointerOperand(),
2100ff0cc061SDimitry Andric                                                   BaseValue);
2101ff0cc061SDimitry Andric   }
2102ff0cc061SDimitry Andric 
2103ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2104ff0cc061SDimitry Andric     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2105ff0cc061SDimitry Andric       return false;
2106ff0cc061SDimitry Andric 
2107ff0cc061SDimitry Andric     ChainToBase.push_back(CI);
21087d523365SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
21097d523365SDimitry Andric                                                   CI->getOperand(0), BaseValue);
2110ff0cc061SDimitry Andric   }
2111ff0cc061SDimitry Andric 
2112ff0cc061SDimitry Andric   // Not supported instruction in the chain
2113ff0cc061SDimitry Andric   return false;
2114ff0cc061SDimitry Andric }
2115ff0cc061SDimitry Andric 
2116ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". Compute cost of the use
2117ff0cc061SDimitry Andric // chain we are going to rematerialize.
2118ff0cc061SDimitry Andric static unsigned
2119ff0cc061SDimitry Andric chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2120ff0cc061SDimitry Andric                        TargetTransformInfo &TTI) {
2121ff0cc061SDimitry Andric   unsigned Cost = 0;
2122ff0cc061SDimitry Andric 
2123ff0cc061SDimitry Andric   for (Instruction *Instr : Chain) {
2124ff0cc061SDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2125ff0cc061SDimitry Andric       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2126ff0cc061SDimitry Andric              "non noop cast is found during rematerialization");
2127ff0cc061SDimitry Andric 
2128ff0cc061SDimitry Andric       Type *SrcTy = CI->getOperand(0)->getType();
2129ff0cc061SDimitry Andric       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2130ff0cc061SDimitry Andric 
2131ff0cc061SDimitry Andric     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2132ff0cc061SDimitry Andric       // Cost of the address calculation
2133ff0cc061SDimitry Andric       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2134ff0cc061SDimitry Andric       Cost += TTI.getAddressComputationCost(ValTy);
2135ff0cc061SDimitry Andric 
2136ff0cc061SDimitry Andric       // And cost of the GEP itself
2137ff0cc061SDimitry Andric       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2138ff0cc061SDimitry Andric       //       allowed for the external usage)
2139ff0cc061SDimitry Andric       if (!GEP->hasAllConstantIndices())
2140ff0cc061SDimitry Andric         Cost += 2;
2141ff0cc061SDimitry Andric 
2142ff0cc061SDimitry Andric     } else {
2143ff0cc061SDimitry Andric       llvm_unreachable("unsupported instruciton type during rematerialization");
2144ff0cc061SDimitry Andric     }
2145ff0cc061SDimitry Andric   }
2146ff0cc061SDimitry Andric 
2147ff0cc061SDimitry Andric   return Cost;
2148ff0cc061SDimitry Andric }
2149ff0cc061SDimitry Andric 
21507d523365SDimitry Andric // From the statepoint live set pick values that are cheaper to recompute then
21517d523365SDimitry Andric // to relocate. Remove this values from the live set, rematerialize them after
2152ff0cc061SDimitry Andric // statepoint and record them in "Info" structure. Note that similar to
2153ff0cc061SDimitry Andric // relocated values we don't do any user adjustments here.
2154ff0cc061SDimitry Andric static void rematerializeLiveValues(CallSite CS,
2155ff0cc061SDimitry Andric                                     PartiallyConstructedSafepointRecord &Info,
2156ff0cc061SDimitry Andric                                     TargetTransformInfo &TTI) {
2157ff0cc061SDimitry Andric   const unsigned int ChainLengthThreshold = 10;
2158ff0cc061SDimitry Andric 
2159ff0cc061SDimitry Andric   // Record values we are going to delete from this statepoint live set.
2160ff0cc061SDimitry Andric   // We can not di this in following loop due to iterator invalidation.
2161ff0cc061SDimitry Andric   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2162ff0cc061SDimitry Andric 
21637d523365SDimitry Andric   for (Value *LiveValue: Info.LiveSet) {
2164ff0cc061SDimitry Andric     // For each live pointer find it's defining chain
2165ff0cc061SDimitry Andric     SmallVector<Instruction *, 3> ChainToBase;
21667d523365SDimitry Andric     assert(Info.PointerToBase.count(LiveValue));
2167ff0cc061SDimitry Andric     bool FoundChain =
2168ff0cc061SDimitry Andric       findRematerializableChainToBasePointer(ChainToBase,
2169ff0cc061SDimitry Andric                                              LiveValue,
2170ff0cc061SDimitry Andric                                              Info.PointerToBase[LiveValue]);
2171ff0cc061SDimitry Andric     // Nothing to do, or chain is too long
2172ff0cc061SDimitry Andric     if (!FoundChain ||
2173ff0cc061SDimitry Andric         ChainToBase.size() == 0 ||
2174ff0cc061SDimitry Andric         ChainToBase.size() > ChainLengthThreshold)
2175ff0cc061SDimitry Andric       continue;
2176ff0cc061SDimitry Andric 
2177ff0cc061SDimitry Andric     // Compute cost of this chain
2178ff0cc061SDimitry Andric     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2179ff0cc061SDimitry Andric     // TODO: We can also account for cases when we will be able to remove some
2180ff0cc061SDimitry Andric     //       of the rematerialized values by later optimization passes. I.e if
2181ff0cc061SDimitry Andric     //       we rematerialized several intersecting chains. Or if original values
2182ff0cc061SDimitry Andric     //       don't have any uses besides this statepoint.
2183ff0cc061SDimitry Andric 
2184ff0cc061SDimitry Andric     // For invokes we need to rematerialize each chain twice - for normal and
2185ff0cc061SDimitry Andric     // for unwind basic blocks. Model this by multiplying cost by two.
2186ff0cc061SDimitry Andric     if (CS.isInvoke()) {
2187ff0cc061SDimitry Andric       Cost *= 2;
2188ff0cc061SDimitry Andric     }
2189ff0cc061SDimitry Andric     // If it's too expensive - skip it
2190ff0cc061SDimitry Andric     if (Cost >= RematerializationThreshold)
2191ff0cc061SDimitry Andric       continue;
2192ff0cc061SDimitry Andric 
2193ff0cc061SDimitry Andric     // Remove value from the live set
2194ff0cc061SDimitry Andric     LiveValuesToBeDeleted.push_back(LiveValue);
2195ff0cc061SDimitry Andric 
2196ff0cc061SDimitry Andric     // Clone instructions and record them inside "Info" structure
2197ff0cc061SDimitry Andric 
2198ff0cc061SDimitry Andric     // Walk backwards to visit top-most instructions first
2199ff0cc061SDimitry Andric     std::reverse(ChainToBase.begin(), ChainToBase.end());
2200ff0cc061SDimitry Andric 
2201ff0cc061SDimitry Andric     // Utility function which clones all instructions from "ChainToBase"
2202ff0cc061SDimitry Andric     // and inserts them before "InsertBefore". Returns rematerialized value
2203ff0cc061SDimitry Andric     // which should be used after statepoint.
2204ff0cc061SDimitry Andric     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2205ff0cc061SDimitry Andric       Instruction *LastClonedValue = nullptr;
2206ff0cc061SDimitry Andric       Instruction *LastValue = nullptr;
2207ff0cc061SDimitry Andric       for (Instruction *Instr: ChainToBase) {
2208ff0cc061SDimitry Andric         // Only GEP's and casts are suported as we need to be careful to not
2209ff0cc061SDimitry Andric         // introduce any new uses of pointers not in the liveset.
2210ff0cc061SDimitry Andric         // Note that it's fine to introduce new uses of pointers which were
2211ff0cc061SDimitry Andric         // otherwise not used after this statepoint.
2212ff0cc061SDimitry Andric         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2213ff0cc061SDimitry Andric 
2214ff0cc061SDimitry Andric         Instruction *ClonedValue = Instr->clone();
2215ff0cc061SDimitry Andric         ClonedValue->insertBefore(InsertBefore);
2216ff0cc061SDimitry Andric         ClonedValue->setName(Instr->getName() + ".remat");
2217ff0cc061SDimitry Andric 
2218ff0cc061SDimitry Andric         // If it is not first instruction in the chain then it uses previously
2219ff0cc061SDimitry Andric         // cloned value. We should update it to use cloned value.
2220ff0cc061SDimitry Andric         if (LastClonedValue) {
2221ff0cc061SDimitry Andric           assert(LastValue);
2222ff0cc061SDimitry Andric           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2223ff0cc061SDimitry Andric #ifndef NDEBUG
2224ff0cc061SDimitry Andric           // Assert that cloned instruction does not use any instructions from
2225ff0cc061SDimitry Andric           // this chain other than LastClonedValue
2226ff0cc061SDimitry Andric           for (auto OpValue : ClonedValue->operand_values()) {
2227ff0cc061SDimitry Andric             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2228ff0cc061SDimitry Andric                        ChainToBase.end() &&
2229ff0cc061SDimitry Andric                    "incorrect use in rematerialization chain");
2230ff0cc061SDimitry Andric           }
2231ff0cc061SDimitry Andric #endif
2232ff0cc061SDimitry Andric         }
2233ff0cc061SDimitry Andric 
2234ff0cc061SDimitry Andric         LastClonedValue = ClonedValue;
2235ff0cc061SDimitry Andric         LastValue = Instr;
2236ff0cc061SDimitry Andric       }
2237ff0cc061SDimitry Andric       assert(LastClonedValue);
2238ff0cc061SDimitry Andric       return LastClonedValue;
2239ff0cc061SDimitry Andric     };
2240ff0cc061SDimitry Andric 
2241ff0cc061SDimitry Andric     // Different cases for calls and invokes. For invokes we need to clone
2242ff0cc061SDimitry Andric     // instructions both on normal and unwind path.
2243ff0cc061SDimitry Andric     if (CS.isCall()) {
2244ff0cc061SDimitry Andric       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2245ff0cc061SDimitry Andric       assert(InsertBefore);
2246ff0cc061SDimitry Andric       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2247ff0cc061SDimitry Andric       Info.RematerializedValues[RematerializedValue] = LiveValue;
2248ff0cc061SDimitry Andric     } else {
2249ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2250ff0cc061SDimitry Andric 
2251ff0cc061SDimitry Andric       Instruction *NormalInsertBefore =
22527d523365SDimitry Andric           &*Invoke->getNormalDest()->getFirstInsertionPt();
2253ff0cc061SDimitry Andric       Instruction *UnwindInsertBefore =
22547d523365SDimitry Andric           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2255ff0cc061SDimitry Andric 
2256ff0cc061SDimitry Andric       Instruction *NormalRematerializedValue =
2257ff0cc061SDimitry Andric           rematerializeChain(NormalInsertBefore);
2258ff0cc061SDimitry Andric       Instruction *UnwindRematerializedValue =
2259ff0cc061SDimitry Andric           rematerializeChain(UnwindInsertBefore);
2260ff0cc061SDimitry Andric 
2261ff0cc061SDimitry Andric       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2262ff0cc061SDimitry Andric       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2263ff0cc061SDimitry Andric     }
2264ff0cc061SDimitry Andric   }
2265ff0cc061SDimitry Andric 
2266ff0cc061SDimitry Andric   // Remove rematerializaed values from the live set
2267ff0cc061SDimitry Andric   for (auto LiveValue: LiveValuesToBeDeleted) {
22687d523365SDimitry Andric     Info.LiveSet.erase(LiveValue);
2269ff0cc061SDimitry Andric   }
2270ff0cc061SDimitry Andric }
2271ff0cc061SDimitry Andric 
22727d523365SDimitry Andric static bool insertParsePoints(Function &F, DominatorTree &DT,
22737d523365SDimitry Andric                               TargetTransformInfo &TTI,
22747d523365SDimitry Andric                               SmallVectorImpl<CallSite> &ToUpdate) {
2275ff0cc061SDimitry Andric #ifndef NDEBUG
2276ff0cc061SDimitry Andric   // sanity check the input
22777d523365SDimitry Andric   std::set<CallSite> Uniqued;
22787d523365SDimitry Andric   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
22797d523365SDimitry Andric   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2280ff0cc061SDimitry Andric 
22817d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2282ff0cc061SDimitry Andric     assert(CS.getInstruction()->getParent()->getParent() == &F);
22837d523365SDimitry Andric     assert((UseDeoptBundles || isStatepoint(CS)) &&
22847d523365SDimitry Andric            "expected to already be a deopt statepoint");
2285ff0cc061SDimitry Andric   }
2286ff0cc061SDimitry Andric #endif
2287ff0cc061SDimitry Andric 
2288ff0cc061SDimitry Andric   // When inserting gc.relocates for invokes, we need to be able to insert at
2289ff0cc061SDimitry Andric   // the top of the successor blocks.  See the comment on
2290ff0cc061SDimitry Andric   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2291ff0cc061SDimitry Andric   // may restructure the CFG.
22927d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2293ff0cc061SDimitry Andric     if (!CS.isInvoke())
2294ff0cc061SDimitry Andric       continue;
22957d523365SDimitry Andric     auto *II = cast<InvokeInst>(CS.getInstruction());
22967d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
22977d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2298ff0cc061SDimitry Andric   }
2299ff0cc061SDimitry Andric 
2300ff0cc061SDimitry Andric   // A list of dummy calls added to the IR to keep various values obviously
2301ff0cc061SDimitry Andric   // live in the IR.  We'll remove all of these when done.
23027d523365SDimitry Andric   SmallVector<CallInst *, 64> Holders;
2303ff0cc061SDimitry Andric 
2304ff0cc061SDimitry Andric   // Insert a dummy call with all of the arguments to the vm_state we'll need
2305ff0cc061SDimitry Andric   // for the actual safepoint insertion.  This ensures reference arguments in
2306ff0cc061SDimitry Andric   // the deopt argument list are considered live through the safepoint (and
2307ff0cc061SDimitry Andric   // thus makes sure they get relocated.)
23087d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2309ff0cc061SDimitry Andric     SmallVector<Value *, 64> DeoptValues;
23107d523365SDimitry Andric 
23117d523365SDimitry Andric     iterator_range<const Use *> DeoptStateRange =
23127d523365SDimitry Andric         UseDeoptBundles
23137d523365SDimitry Andric             ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
23147d523365SDimitry Andric             : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
23157d523365SDimitry Andric 
23167d523365SDimitry Andric     for (Value *Arg : DeoptStateRange) {
2317ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2318ff0cc061SDimitry Andric              "support for FCA unimplemented");
2319ff0cc061SDimitry Andric       if (isHandledGCPointerType(Arg->getType()))
2320ff0cc061SDimitry Andric         DeoptValues.push_back(Arg);
2321ff0cc061SDimitry Andric     }
23227d523365SDimitry Andric 
23237d523365SDimitry Andric     insertUseHolderAfter(CS, DeoptValues, Holders);
2324ff0cc061SDimitry Andric   }
2325ff0cc061SDimitry Andric 
23267d523365SDimitry Andric   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2327ff0cc061SDimitry Andric 
23287d523365SDimitry Andric   // A) Identify all gc pointers which are statically live at the given call
2329ff0cc061SDimitry Andric   // site.
23307d523365SDimitry Andric   findLiveReferences(F, DT, ToUpdate, Records);
2331ff0cc061SDimitry Andric 
2332ff0cc061SDimitry Andric   // B) Find the base pointers for each live pointer
2333ff0cc061SDimitry Andric   /* scope for caching */ {
2334ff0cc061SDimitry Andric     // Cache the 'defining value' relation used in the computation and
2335ff0cc061SDimitry Andric     // insertion of base phis and selects.  This ensures that we don't insert
2336ff0cc061SDimitry Andric     // large numbers of duplicate base_phis.
2337ff0cc061SDimitry Andric     DefiningValueMapTy DVCache;
2338ff0cc061SDimitry Andric 
23397d523365SDimitry Andric     for (size_t i = 0; i < Records.size(); i++) {
23407d523365SDimitry Andric       PartiallyConstructedSafepointRecord &info = Records[i];
23417d523365SDimitry Andric       findBasePointers(DT, DVCache, ToUpdate[i], info);
2342ff0cc061SDimitry Andric     }
2343ff0cc061SDimitry Andric   } // end of cache scope
2344ff0cc061SDimitry Andric 
2345ff0cc061SDimitry Andric   // The base phi insertion logic (for any safepoint) may have inserted new
2346ff0cc061SDimitry Andric   // instructions which are now live at some safepoint.  The simplest such
2347ff0cc061SDimitry Andric   // example is:
2348ff0cc061SDimitry Andric   // loop:
2349ff0cc061SDimitry Andric   //   phi a  <-- will be a new base_phi here
2350ff0cc061SDimitry Andric   //   safepoint 1 <-- that needs to be live here
2351ff0cc061SDimitry Andric   //   gep a + 1
2352ff0cc061SDimitry Andric   //   safepoint 2
2353ff0cc061SDimitry Andric   //   br loop
2354ff0cc061SDimitry Andric   // We insert some dummy calls after each safepoint to definitely hold live
2355ff0cc061SDimitry Andric   // the base pointers which were identified for that safepoint.  We'll then
2356ff0cc061SDimitry Andric   // ask liveness for _every_ base inserted to see what is now live.  Then we
2357ff0cc061SDimitry Andric   // remove the dummy calls.
23587d523365SDimitry Andric   Holders.reserve(Holders.size() + Records.size());
23597d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
23607d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
2361ff0cc061SDimitry Andric 
2362ff0cc061SDimitry Andric     SmallVector<Value *, 128> Bases;
23637d523365SDimitry Andric     for (auto Pair : Info.PointerToBase)
2364ff0cc061SDimitry Andric       Bases.push_back(Pair.second);
23657d523365SDimitry Andric 
23667d523365SDimitry Andric     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2367ff0cc061SDimitry Andric   }
2368ff0cc061SDimitry Andric 
2369ff0cc061SDimitry Andric   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2370ff0cc061SDimitry Andric   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2371ff0cc061SDimitry Andric   // not the key issue.
23727d523365SDimitry Andric   recomputeLiveInValues(F, DT, ToUpdate, Records);
2373ff0cc061SDimitry Andric 
2374ff0cc061SDimitry Andric   if (PrintBasePointers) {
23757d523365SDimitry Andric     for (auto &Info : Records) {
2376ff0cc061SDimitry Andric       errs() << "Base Pairs: (w/Relocation)\n";
23777d523365SDimitry Andric       for (auto Pair : Info.PointerToBase) {
23787d523365SDimitry Andric         errs() << " derived ";
23797d523365SDimitry Andric         Pair.first->printAsOperand(errs(), false);
23807d523365SDimitry Andric         errs() << " base ";
23817d523365SDimitry Andric         Pair.second->printAsOperand(errs(), false);
23827d523365SDimitry Andric         errs() << "\n";
2383ff0cc061SDimitry Andric       }
2384ff0cc061SDimitry Andric     }
2385ff0cc061SDimitry Andric   }
23867d523365SDimitry Andric 
23877d523365SDimitry Andric   // It is possible that non-constant live variables have a constant base.  For
23887d523365SDimitry Andric   // example, a GEP with a variable offset from a global.  In this case we can
23897d523365SDimitry Andric   // remove it from the liveset.  We already don't add constants to the liveset
23907d523365SDimitry Andric   // because we assume they won't move at runtime and the GC doesn't need to be
23917d523365SDimitry Andric   // informed about them.  The same reasoning applies if the base is constant.
23927d523365SDimitry Andric   // Note that the relocation placement code relies on this filtering for
23937d523365SDimitry Andric   // correctness as it expects the base to be in the liveset, which isn't true
23947d523365SDimitry Andric   // if the base is constant.
23957d523365SDimitry Andric   for (auto &Info : Records)
23967d523365SDimitry Andric     for (auto &BasePair : Info.PointerToBase)
23977d523365SDimitry Andric       if (isa<Constant>(BasePair.second))
23987d523365SDimitry Andric         Info.LiveSet.erase(BasePair.first);
23997d523365SDimitry Andric 
24007d523365SDimitry Andric   for (CallInst *CI : Holders)
24017d523365SDimitry Andric     CI->eraseFromParent();
24027d523365SDimitry Andric 
24037d523365SDimitry Andric   Holders.clear();
2404ff0cc061SDimitry Andric 
24053dac3a9bSDimitry Andric   // Do a limited scalarization of any live at safepoint vector values which
24063dac3a9bSDimitry Andric   // contain pointers.  This enables this pass to run after vectorization at
24073dac3a9bSDimitry Andric   // the cost of some possible performance loss.  TODO: it would be nice to
24083dac3a9bSDimitry Andric   // natively support vectors all the way through the backend so we don't need
24093dac3a9bSDimitry Andric   // to scalarize here.
24107d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
24117d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
24127d523365SDimitry Andric     Instruction *Statepoint = ToUpdate[i].getInstruction();
24137d523365SDimitry Andric     splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
24147d523365SDimitry Andric                       Info.PointerToBase, DT);
24153dac3a9bSDimitry Andric   }
24163dac3a9bSDimitry Andric 
2417ff0cc061SDimitry Andric   // In order to reduce live set of statepoint we might choose to rematerialize
24187d523365SDimitry Andric   // some values instead of relocating them. This is purely an optimization and
2419ff0cc061SDimitry Andric   // does not influence correctness.
24207d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
24217d523365SDimitry Andric     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2422ff0cc061SDimitry Andric 
24237d523365SDimitry Andric   // We need this to safely RAUW and delete call or invoke return values that
24247d523365SDimitry Andric   // may themselves be live over a statepoint.  For details, please see usage in
24257d523365SDimitry Andric   // makeStatepointExplicitImpl.
24267d523365SDimitry Andric   std::vector<DeferredReplacement> Replacements;
2427ff0cc061SDimitry Andric 
2428ff0cc061SDimitry Andric   // Now run through and replace the existing statepoints with new ones with
2429ff0cc061SDimitry Andric   // the live variables listed.  We do not yet update uses of the values being
2430ff0cc061SDimitry Andric   // relocated. We have references to live variables that need to
2431ff0cc061SDimitry Andric   // survive to the last iteration of this loop.  (By construction, the
2432ff0cc061SDimitry Andric   // previous statepoint can not be a live variable, thus we can and remove
2433ff0cc061SDimitry Andric   // the old statepoint calls as we go.)
24347d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
24357d523365SDimitry Andric     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
24367d523365SDimitry Andric 
24377d523365SDimitry Andric   ToUpdate.clear(); // prevent accident use of invalid CallSites
24387d523365SDimitry Andric 
24397d523365SDimitry Andric   for (auto &PR : Replacements)
24407d523365SDimitry Andric     PR.doReplacement();
24417d523365SDimitry Andric 
24427d523365SDimitry Andric   Replacements.clear();
24437d523365SDimitry Andric 
24447d523365SDimitry Andric   for (auto &Info : Records) {
24457d523365SDimitry Andric     // These live sets may contain state Value pointers, since we replaced calls
24467d523365SDimitry Andric     // with operand bundles with calls wrapped in gc.statepoint, and some of
24477d523365SDimitry Andric     // those calls may have been def'ing live gc pointers.  Clear these out to
24487d523365SDimitry Andric     // avoid accidentally using them.
24497d523365SDimitry Andric     //
24507d523365SDimitry Andric     // TODO: We should create a separate data structure that does not contain
24517d523365SDimitry Andric     // these live sets, and migrate to using that data structure from this point
24527d523365SDimitry Andric     // onward.
24537d523365SDimitry Andric     Info.LiveSet.clear();
24547d523365SDimitry Andric     Info.PointerToBase.clear();
2455ff0cc061SDimitry Andric   }
2456ff0cc061SDimitry Andric 
2457ff0cc061SDimitry Andric   // Do all the fixups of the original live variables to their relocated selves
24587d523365SDimitry Andric   SmallVector<Value *, 128> Live;
24597d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
24607d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
24617d523365SDimitry Andric 
2462ff0cc061SDimitry Andric     // We can't simply save the live set from the original insertion.  One of
2463ff0cc061SDimitry Andric     // the live values might be the result of a call which needs a safepoint.
2464ff0cc061SDimitry Andric     // That Value* no longer exists and we need to use the new gc_result.
2465ff0cc061SDimitry Andric     // Thankfully, the live set is embedded in the statepoint (and updated), so
2466ff0cc061SDimitry Andric     // we just grab that.
24677d523365SDimitry Andric     Statepoint Statepoint(Info.StatepointToken);
24687d523365SDimitry Andric     Live.insert(Live.end(), Statepoint.gc_args_begin(),
24697d523365SDimitry Andric                 Statepoint.gc_args_end());
2470ff0cc061SDimitry Andric #ifndef NDEBUG
2471ff0cc061SDimitry Andric     // Do some basic sanity checks on our liveness results before performing
2472ff0cc061SDimitry Andric     // relocation.  Relocation can and will turn mistakes in liveness results
2473ff0cc061SDimitry Andric     // into non-sensical code which is must harder to debug.
2474ff0cc061SDimitry Andric     // TODO: It would be nice to test consistency as well
24757d523365SDimitry Andric     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2476ff0cc061SDimitry Andric            "statepoint must be reachable or liveness is meaningless");
24777d523365SDimitry Andric     for (Value *V : Statepoint.gc_args()) {
2478ff0cc061SDimitry Andric       if (!isa<Instruction>(V))
2479ff0cc061SDimitry Andric         // Non-instruction values trivial dominate all possible uses
2480ff0cc061SDimitry Andric         continue;
24817d523365SDimitry Andric       auto *LiveInst = cast<Instruction>(V);
2482ff0cc061SDimitry Andric       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2483ff0cc061SDimitry Andric              "unreachable values should never be live");
24847d523365SDimitry Andric       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2485ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2486ff0cc061SDimitry Andric     }
2487ff0cc061SDimitry Andric #endif
2488ff0cc061SDimitry Andric   }
24897d523365SDimitry Andric   unique_unsorted(Live);
2490ff0cc061SDimitry Andric 
2491ff0cc061SDimitry Andric #ifndef NDEBUG
2492ff0cc061SDimitry Andric   // sanity check
24937d523365SDimitry Andric   for (auto *Ptr : Live)
24947d523365SDimitry Andric     assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
2495ff0cc061SDimitry Andric #endif
2496ff0cc061SDimitry Andric 
24977d523365SDimitry Andric   relocationViaAlloca(F, DT, Live, Records);
24987d523365SDimitry Andric   return !Records.empty();
2499ff0cc061SDimitry Andric }
2500ff0cc061SDimitry Andric 
250197bc6c73SDimitry Andric // Handles both return values and arguments for Functions and CallSites.
250297bc6c73SDimitry Andric template <typename AttrHolder>
25037d523365SDimitry Andric static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
250497bc6c73SDimitry Andric                                       unsigned Index) {
250597bc6c73SDimitry Andric   AttrBuilder R;
250697bc6c73SDimitry Andric   if (AH.getDereferenceableBytes(Index))
250797bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
250897bc6c73SDimitry Andric                                   AH.getDereferenceableBytes(Index)));
250997bc6c73SDimitry Andric   if (AH.getDereferenceableOrNullBytes(Index))
251097bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
251197bc6c73SDimitry Andric                                   AH.getDereferenceableOrNullBytes(Index)));
25127d523365SDimitry Andric   if (AH.doesNotAlias(Index))
25137d523365SDimitry Andric     R.addAttribute(Attribute::NoAlias);
251497bc6c73SDimitry Andric 
251597bc6c73SDimitry Andric   if (!R.empty())
251697bc6c73SDimitry Andric     AH.setAttributes(AH.getAttributes().removeAttributes(
251797bc6c73SDimitry Andric         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
251897bc6c73SDimitry Andric }
251997bc6c73SDimitry Andric 
252097bc6c73SDimitry Andric void
25217d523365SDimitry Andric RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
252297bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
252397bc6c73SDimitry Andric 
252497bc6c73SDimitry Andric   for (Argument &A : F.args())
252597bc6c73SDimitry Andric     if (isa<PointerType>(A.getType()))
25267d523365SDimitry Andric       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
252797bc6c73SDimitry Andric 
252897bc6c73SDimitry Andric   if (isa<PointerType>(F.getReturnType()))
25297d523365SDimitry Andric     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
253097bc6c73SDimitry Andric }
253197bc6c73SDimitry Andric 
25327d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
253397bc6c73SDimitry Andric   if (F.empty())
253497bc6c73SDimitry Andric     return;
253597bc6c73SDimitry Andric 
253697bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
253797bc6c73SDimitry Andric   MDBuilder Builder(Ctx);
253897bc6c73SDimitry Andric 
25397d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
254097bc6c73SDimitry Andric     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
254197bc6c73SDimitry Andric       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
254297bc6c73SDimitry Andric       bool IsImmutableTBAA =
254397bc6c73SDimitry Andric           MD->getNumOperands() == 4 &&
254497bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
254597bc6c73SDimitry Andric 
254697bc6c73SDimitry Andric       if (!IsImmutableTBAA)
254797bc6c73SDimitry Andric         continue; // no work to do, MD_tbaa is already marked mutable
254897bc6c73SDimitry Andric 
254997bc6c73SDimitry Andric       MDNode *Base = cast<MDNode>(MD->getOperand(0));
255097bc6c73SDimitry Andric       MDNode *Access = cast<MDNode>(MD->getOperand(1));
255197bc6c73SDimitry Andric       uint64_t Offset =
255297bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
255397bc6c73SDimitry Andric 
255497bc6c73SDimitry Andric       MDNode *MutableTBAA =
255597bc6c73SDimitry Andric           Builder.createTBAAStructTagNode(Base, Access, Offset);
255697bc6c73SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
255797bc6c73SDimitry Andric     }
255897bc6c73SDimitry Andric 
255997bc6c73SDimitry Andric     if (CallSite CS = CallSite(&I)) {
256097bc6c73SDimitry Andric       for (int i = 0, e = CS.arg_size(); i != e; i++)
256197bc6c73SDimitry Andric         if (isa<PointerType>(CS.getArgument(i)->getType()))
25627d523365SDimitry Andric           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
256397bc6c73SDimitry Andric       if (isa<PointerType>(CS.getType()))
25647d523365SDimitry Andric         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
256597bc6c73SDimitry Andric     }
256697bc6c73SDimitry Andric   }
256797bc6c73SDimitry Andric }
256897bc6c73SDimitry Andric 
2569ff0cc061SDimitry Andric /// Returns true if this function should be rewritten by this pass.  The main
2570ff0cc061SDimitry Andric /// point of this function is as an extension point for custom logic.
2571ff0cc061SDimitry Andric static bool shouldRewriteStatepointsIn(Function &F) {
2572ff0cc061SDimitry Andric   // TODO: This should check the GCStrategy
2573ff0cc061SDimitry Andric   if (F.hasGC()) {
2574ff0cc061SDimitry Andric     const char *FunctionGCName = F.getGC();
2575ff0cc061SDimitry Andric     const StringRef StatepointExampleName("statepoint-example");
2576ff0cc061SDimitry Andric     const StringRef CoreCLRName("coreclr");
2577ff0cc061SDimitry Andric     return (StatepointExampleName == FunctionGCName) ||
2578ff0cc061SDimitry Andric            (CoreCLRName == FunctionGCName);
2579ff0cc061SDimitry Andric   } else
2580ff0cc061SDimitry Andric     return false;
2581ff0cc061SDimitry Andric }
2582ff0cc061SDimitry Andric 
25837d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
258497bc6c73SDimitry Andric #ifndef NDEBUG
258597bc6c73SDimitry Andric   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
258697bc6c73SDimitry Andric          "precondition!");
258797bc6c73SDimitry Andric #endif
258897bc6c73SDimitry Andric 
258997bc6c73SDimitry Andric   for (Function &F : M)
25907d523365SDimitry Andric     stripNonValidAttributesFromPrototype(F);
259197bc6c73SDimitry Andric 
259297bc6c73SDimitry Andric   for (Function &F : M)
25937d523365SDimitry Andric     stripNonValidAttributesFromBody(F);
259497bc6c73SDimitry Andric }
259597bc6c73SDimitry Andric 
2596ff0cc061SDimitry Andric bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2597ff0cc061SDimitry Andric   // Nothing to do for declarations.
2598ff0cc061SDimitry Andric   if (F.isDeclaration() || F.empty())
2599ff0cc061SDimitry Andric     return false;
2600ff0cc061SDimitry Andric 
2601ff0cc061SDimitry Andric   // Policy choice says not to rewrite - the most common reason is that we're
2602ff0cc061SDimitry Andric   // compiling code without a GCStrategy.
2603ff0cc061SDimitry Andric   if (!shouldRewriteStatepointsIn(F))
2604ff0cc061SDimitry Andric     return false;
2605ff0cc061SDimitry Andric 
260697bc6c73SDimitry Andric   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
26077d523365SDimitry Andric   TargetTransformInfo &TTI =
26087d523365SDimitry Andric       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
26097d523365SDimitry Andric 
26107d523365SDimitry Andric   auto NeedsRewrite = [](Instruction &I) {
26117d523365SDimitry Andric     if (UseDeoptBundles) {
26127d523365SDimitry Andric       if (ImmutableCallSite CS = ImmutableCallSite(&I))
26137d523365SDimitry Andric         return !callsGCLeafFunction(CS);
26147d523365SDimitry Andric       return false;
26157d523365SDimitry Andric     }
26167d523365SDimitry Andric 
26177d523365SDimitry Andric     return isStatepoint(I);
26187d523365SDimitry Andric   };
2619ff0cc061SDimitry Andric 
2620ff0cc061SDimitry Andric   // Gather all the statepoints which need rewritten.  Be careful to only
2621ff0cc061SDimitry Andric   // consider those in reachable code since we need to ask dominance queries
2622ff0cc061SDimitry Andric   // when rewriting.  We'll delete the unreachable ones in a moment.
2623ff0cc061SDimitry Andric   SmallVector<CallSite, 64> ParsePointNeeded;
2624ff0cc061SDimitry Andric   bool HasUnreachableStatepoint = false;
26257d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
2626ff0cc061SDimitry Andric     // TODO: only the ones with the flag set!
26277d523365SDimitry Andric     if (NeedsRewrite(I)) {
2628ff0cc061SDimitry Andric       if (DT.isReachableFromEntry(I.getParent()))
2629ff0cc061SDimitry Andric         ParsePointNeeded.push_back(CallSite(&I));
2630ff0cc061SDimitry Andric       else
2631ff0cc061SDimitry Andric         HasUnreachableStatepoint = true;
2632ff0cc061SDimitry Andric     }
2633ff0cc061SDimitry Andric   }
2634ff0cc061SDimitry Andric 
2635ff0cc061SDimitry Andric   bool MadeChange = false;
2636ff0cc061SDimitry Andric 
2637ff0cc061SDimitry Andric   // Delete any unreachable statepoints so that we don't have unrewritten
2638ff0cc061SDimitry Andric   // statepoints surviving this pass.  This makes testing easier and the
2639ff0cc061SDimitry Andric   // resulting IR less confusing to human readers.  Rather than be fancy, we
2640ff0cc061SDimitry Andric   // just reuse a utility function which removes the unreachable blocks.
2641ff0cc061SDimitry Andric   if (HasUnreachableStatepoint)
2642ff0cc061SDimitry Andric     MadeChange |= removeUnreachableBlocks(F);
2643ff0cc061SDimitry Andric 
2644ff0cc061SDimitry Andric   // Return early if no work to do.
2645ff0cc061SDimitry Andric   if (ParsePointNeeded.empty())
2646ff0cc061SDimitry Andric     return MadeChange;
2647ff0cc061SDimitry Andric 
2648ff0cc061SDimitry Andric   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2649ff0cc061SDimitry Andric   // These are created by LCSSA.  They have the effect of increasing the size
2650ff0cc061SDimitry Andric   // of liveness sets for no good reason.  It may be harder to do this post
2651ff0cc061SDimitry Andric   // insertion since relocations and base phis can confuse things.
2652ff0cc061SDimitry Andric   for (BasicBlock &BB : F)
2653ff0cc061SDimitry Andric     if (BB.getUniquePredecessor()) {
2654ff0cc061SDimitry Andric       MadeChange = true;
2655ff0cc061SDimitry Andric       FoldSingleEntryPHINodes(&BB);
2656ff0cc061SDimitry Andric     }
2657ff0cc061SDimitry Andric 
26587d523365SDimitry Andric   // Before we start introducing relocations, we want to tweak the IR a bit to
26597d523365SDimitry Andric   // avoid unfortunate code generation effects.  The main example is that we
26607d523365SDimitry Andric   // want to try to make sure the comparison feeding a branch is after any
26617d523365SDimitry Andric   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
26627d523365SDimitry Andric   // values feeding a branch after relocation.  This is semantically correct,
26637d523365SDimitry Andric   // but results in extra register pressure since both the pre-relocation and
26647d523365SDimitry Andric   // post-relocation copies must be available in registers.  For code without
26657d523365SDimitry Andric   // relocations this is handled elsewhere, but teaching the scheduler to
26667d523365SDimitry Andric   // reverse the transform we're about to do would be slightly complex.
26677d523365SDimitry Andric   // Note: This may extend the live range of the inputs to the icmp and thus
26687d523365SDimitry Andric   // increase the liveset of any statepoint we move over.  This is profitable
26697d523365SDimitry Andric   // as long as all statepoints are in rare blocks.  If we had in-register
26707d523365SDimitry Andric   // lowering for live values this would be a much safer transform.
26717d523365SDimitry Andric   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
26727d523365SDimitry Andric     if (auto *BI = dyn_cast<BranchInst>(TI))
26737d523365SDimitry Andric       if (BI->isConditional())
26747d523365SDimitry Andric         return dyn_cast<Instruction>(BI->getCondition());
26757d523365SDimitry Andric     // TODO: Extend this to handle switches
26767d523365SDimitry Andric     return nullptr;
26777d523365SDimitry Andric   };
26787d523365SDimitry Andric   for (BasicBlock &BB : F) {
26797d523365SDimitry Andric     TerminatorInst *TI = BB.getTerminator();
26807d523365SDimitry Andric     if (auto *Cond = getConditionInst(TI))
26817d523365SDimitry Andric       // TODO: Handle more than just ICmps here.  We should be able to move
26827d523365SDimitry Andric       // most instructions without side effects or memory access.
26837d523365SDimitry Andric       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
26847d523365SDimitry Andric         MadeChange = true;
26857d523365SDimitry Andric         Cond->moveBefore(TI);
26867d523365SDimitry Andric       }
26877d523365SDimitry Andric   }
26887d523365SDimitry Andric 
26897d523365SDimitry Andric   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2690ff0cc061SDimitry Andric   return MadeChange;
2691ff0cc061SDimitry Andric }
2692ff0cc061SDimitry Andric 
2693ff0cc061SDimitry Andric // liveness computation via standard dataflow
2694ff0cc061SDimitry Andric // -------------------------------------------------------------------
2695ff0cc061SDimitry Andric 
2696ff0cc061SDimitry Andric // TODO: Consider using bitvectors for liveness, the set of potentially
2697ff0cc061SDimitry Andric // interesting values should be small and easy to pre-compute.
2698ff0cc061SDimitry Andric 
2699ff0cc061SDimitry Andric /// Compute the live-in set for the location rbegin starting from
2700ff0cc061SDimitry Andric /// the live-out set of the basic block
2701ff0cc061SDimitry Andric static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2702ff0cc061SDimitry Andric                                 BasicBlock::reverse_iterator rend,
2703ff0cc061SDimitry Andric                                 DenseSet<Value *> &LiveTmp) {
2704ff0cc061SDimitry Andric 
2705ff0cc061SDimitry Andric   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2706ff0cc061SDimitry Andric     Instruction *I = &*ritr;
2707ff0cc061SDimitry Andric 
2708ff0cc061SDimitry Andric     // KILL/Def - Remove this definition from LiveIn
2709ff0cc061SDimitry Andric     LiveTmp.erase(I);
2710ff0cc061SDimitry Andric 
2711ff0cc061SDimitry Andric     // Don't consider *uses* in PHI nodes, we handle their contribution to
2712ff0cc061SDimitry Andric     // predecessor blocks when we seed the LiveOut sets
2713ff0cc061SDimitry Andric     if (isa<PHINode>(I))
2714ff0cc061SDimitry Andric       continue;
2715ff0cc061SDimitry Andric 
2716ff0cc061SDimitry Andric     // USE - Add to the LiveIn set for this instruction
2717ff0cc061SDimitry Andric     for (Value *V : I->operands()) {
2718ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2719ff0cc061SDimitry Andric              "support for FCA unimplemented");
2720ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2721ff0cc061SDimitry Andric         // The choice to exclude all things constant here is slightly subtle.
27227d523365SDimitry Andric         // There are two independent reasons:
2723ff0cc061SDimitry Andric         // - We assume that things which are constant (from LLVM's definition)
2724ff0cc061SDimitry Andric         // do not move at runtime.  For example, the address of a global
2725ff0cc061SDimitry Andric         // variable is fixed, even though it's contents may not be.
2726ff0cc061SDimitry Andric         // - Second, we can't disallow arbitrary inttoptr constants even
2727ff0cc061SDimitry Andric         // if the language frontend does.  Optimization passes are free to
2728ff0cc061SDimitry Andric         // locally exploit facts without respect to global reachability.  This
2729ff0cc061SDimitry Andric         // can create sections of code which are dynamically unreachable and
2730ff0cc061SDimitry Andric         // contain just about anything.  (see constants.ll in tests)
2731ff0cc061SDimitry Andric         LiveTmp.insert(V);
2732ff0cc061SDimitry Andric       }
2733ff0cc061SDimitry Andric     }
2734ff0cc061SDimitry Andric   }
2735ff0cc061SDimitry Andric }
2736ff0cc061SDimitry Andric 
2737ff0cc061SDimitry Andric static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2738ff0cc061SDimitry Andric 
2739ff0cc061SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
2740ff0cc061SDimitry Andric     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2741ff0cc061SDimitry Andric     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2742ff0cc061SDimitry Andric       PHINode *Phi = cast<PHINode>(&*I);
2743ff0cc061SDimitry Andric       Value *V = Phi->getIncomingValueForBlock(BB);
2744ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2745ff0cc061SDimitry Andric              "support for FCA unimplemented");
2746ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2747ff0cc061SDimitry Andric         LiveTmp.insert(V);
2748ff0cc061SDimitry Andric       }
2749ff0cc061SDimitry Andric     }
2750ff0cc061SDimitry Andric   }
2751ff0cc061SDimitry Andric }
2752ff0cc061SDimitry Andric 
2753ff0cc061SDimitry Andric static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2754ff0cc061SDimitry Andric   DenseSet<Value *> KillSet;
2755ff0cc061SDimitry Andric   for (Instruction &I : *BB)
2756ff0cc061SDimitry Andric     if (isHandledGCPointerType(I.getType()))
2757ff0cc061SDimitry Andric       KillSet.insert(&I);
2758ff0cc061SDimitry Andric   return KillSet;
2759ff0cc061SDimitry Andric }
2760ff0cc061SDimitry Andric 
2761ff0cc061SDimitry Andric #ifndef NDEBUG
2762ff0cc061SDimitry Andric /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2763ff0cc061SDimitry Andric /// sanity check for the liveness computation.
2764ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2765ff0cc061SDimitry Andric                           TerminatorInst *TI, bool TermOkay = false) {
2766ff0cc061SDimitry Andric   for (Value *V : Live) {
2767ff0cc061SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V)) {
2768ff0cc061SDimitry Andric       // The terminator can be a member of the LiveOut set.  LLVM's definition
2769ff0cc061SDimitry Andric       // of instruction dominance states that V does not dominate itself.  As
2770ff0cc061SDimitry Andric       // such, we need to special case this to allow it.
2771ff0cc061SDimitry Andric       if (TermOkay && TI == I)
2772ff0cc061SDimitry Andric         continue;
2773ff0cc061SDimitry Andric       assert(DT.dominates(I, TI) &&
2774ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2775ff0cc061SDimitry Andric     }
2776ff0cc061SDimitry Andric   }
2777ff0cc061SDimitry Andric }
2778ff0cc061SDimitry Andric 
2779ff0cc061SDimitry Andric /// Check that all the liveness sets used during the computation of liveness
2780ff0cc061SDimitry Andric /// obey basic SSA properties.  This is useful for finding cases where we miss
2781ff0cc061SDimitry Andric /// a def.
2782ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2783ff0cc061SDimitry Andric                           BasicBlock &BB) {
2784ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2785ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2786ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2787ff0cc061SDimitry Andric }
2788ff0cc061SDimitry Andric #endif
2789ff0cc061SDimitry Andric 
2790ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
2791ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data) {
2792ff0cc061SDimitry Andric 
2793ff0cc061SDimitry Andric   SmallSetVector<BasicBlock *, 200> Worklist;
2794ff0cc061SDimitry Andric   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2795ff0cc061SDimitry Andric     // We use a SetVector so that we don't have duplicates in the worklist.
2796ff0cc061SDimitry Andric     Worklist.insert(pred_begin(BB), pred_end(BB));
2797ff0cc061SDimitry Andric   };
2798ff0cc061SDimitry Andric   auto NextItem = [&]() {
2799ff0cc061SDimitry Andric     BasicBlock *BB = Worklist.back();
2800ff0cc061SDimitry Andric     Worklist.pop_back();
2801ff0cc061SDimitry Andric     return BB;
2802ff0cc061SDimitry Andric   };
2803ff0cc061SDimitry Andric 
2804ff0cc061SDimitry Andric   // Seed the liveness for each individual block
2805ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2806ff0cc061SDimitry Andric     Data.KillSet[&BB] = computeKillSet(&BB);
2807ff0cc061SDimitry Andric     Data.LiveSet[&BB].clear();
2808ff0cc061SDimitry Andric     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2809ff0cc061SDimitry Andric 
2810ff0cc061SDimitry Andric #ifndef NDEBUG
2811ff0cc061SDimitry Andric     for (Value *Kill : Data.KillSet[&BB])
2812ff0cc061SDimitry Andric       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2813ff0cc061SDimitry Andric #endif
2814ff0cc061SDimitry Andric 
2815ff0cc061SDimitry Andric     Data.LiveOut[&BB] = DenseSet<Value *>();
2816ff0cc061SDimitry Andric     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2817ff0cc061SDimitry Andric     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2818ff0cc061SDimitry Andric     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2819ff0cc061SDimitry Andric     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2820ff0cc061SDimitry Andric     if (!Data.LiveIn[&BB].empty())
2821ff0cc061SDimitry Andric       AddPredsToWorklist(&BB);
2822ff0cc061SDimitry Andric   }
2823ff0cc061SDimitry Andric 
2824ff0cc061SDimitry Andric   // Propagate that liveness until stable
2825ff0cc061SDimitry Andric   while (!Worklist.empty()) {
2826ff0cc061SDimitry Andric     BasicBlock *BB = NextItem();
2827ff0cc061SDimitry Andric 
2828ff0cc061SDimitry Andric     // Compute our new liveout set, then exit early if it hasn't changed
2829ff0cc061SDimitry Andric     // despite the contribution of our successor.
2830ff0cc061SDimitry Andric     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2831ff0cc061SDimitry Andric     const auto OldLiveOutSize = LiveOut.size();
2832ff0cc061SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
2833ff0cc061SDimitry Andric       assert(Data.LiveIn.count(Succ));
2834ff0cc061SDimitry Andric       set_union(LiveOut, Data.LiveIn[Succ]);
2835ff0cc061SDimitry Andric     }
2836ff0cc061SDimitry Andric     // assert OutLiveOut is a subset of LiveOut
2837ff0cc061SDimitry Andric     if (OldLiveOutSize == LiveOut.size()) {
2838ff0cc061SDimitry Andric       // If the sets are the same size, then we didn't actually add anything
2839ff0cc061SDimitry Andric       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2840ff0cc061SDimitry Andric       // hasn't changed.
2841ff0cc061SDimitry Andric       continue;
2842ff0cc061SDimitry Andric     }
2843ff0cc061SDimitry Andric     Data.LiveOut[BB] = LiveOut;
2844ff0cc061SDimitry Andric 
2845ff0cc061SDimitry Andric     // Apply the effects of this basic block
2846ff0cc061SDimitry Andric     DenseSet<Value *> LiveTmp = LiveOut;
2847ff0cc061SDimitry Andric     set_union(LiveTmp, Data.LiveSet[BB]);
2848ff0cc061SDimitry Andric     set_subtract(LiveTmp, Data.KillSet[BB]);
2849ff0cc061SDimitry Andric 
2850ff0cc061SDimitry Andric     assert(Data.LiveIn.count(BB));
2851ff0cc061SDimitry Andric     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2852ff0cc061SDimitry Andric     // assert: OldLiveIn is a subset of LiveTmp
2853ff0cc061SDimitry Andric     if (OldLiveIn.size() != LiveTmp.size()) {
2854ff0cc061SDimitry Andric       Data.LiveIn[BB] = LiveTmp;
2855ff0cc061SDimitry Andric       AddPredsToWorklist(BB);
2856ff0cc061SDimitry Andric     }
2857ff0cc061SDimitry Andric   } // while( !worklist.empty() )
2858ff0cc061SDimitry Andric 
2859ff0cc061SDimitry Andric #ifndef NDEBUG
28607d523365SDimitry Andric   // Sanity check our output against SSA properties.  This helps catch any
2861ff0cc061SDimitry Andric   // missing kills during the above iteration.
2862ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2863ff0cc061SDimitry Andric     checkBasicSSA(DT, Data, BB);
2864ff0cc061SDimitry Andric   }
2865ff0cc061SDimitry Andric #endif
2866ff0cc061SDimitry Andric }
2867ff0cc061SDimitry Andric 
2868ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2869ff0cc061SDimitry Andric                               StatepointLiveSetTy &Out) {
2870ff0cc061SDimitry Andric 
2871ff0cc061SDimitry Andric   BasicBlock *BB = Inst->getParent();
2872ff0cc061SDimitry Andric 
2873ff0cc061SDimitry Andric   // Note: The copy is intentional and required
2874ff0cc061SDimitry Andric   assert(Data.LiveOut.count(BB));
2875ff0cc061SDimitry Andric   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2876ff0cc061SDimitry Andric 
2877ff0cc061SDimitry Andric   // We want to handle the statepoint itself oddly.  It's
2878ff0cc061SDimitry Andric   // call result is not live (normal), nor are it's arguments
2879ff0cc061SDimitry Andric   // (unless they're used again later).  This adjustment is
2880ff0cc061SDimitry Andric   // specifically what we need to relocate
28817d523365SDimitry Andric   BasicBlock::reverse_iterator rend(Inst->getIterator());
2882ff0cc061SDimitry Andric   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2883ff0cc061SDimitry Andric   LiveOut.erase(Inst);
2884ff0cc061SDimitry Andric   Out.insert(LiveOut.begin(), LiveOut.end());
2885ff0cc061SDimitry Andric }
2886ff0cc061SDimitry Andric 
2887ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2888ff0cc061SDimitry Andric                                   const CallSite &CS,
2889ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &Info) {
2890ff0cc061SDimitry Andric   Instruction *Inst = CS.getInstruction();
2891ff0cc061SDimitry Andric   StatepointLiveSetTy Updated;
2892ff0cc061SDimitry Andric   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2893ff0cc061SDimitry Andric 
2894ff0cc061SDimitry Andric #ifndef NDEBUG
2895ff0cc061SDimitry Andric   DenseSet<Value *> Bases;
2896ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase) {
2897ff0cc061SDimitry Andric     Bases.insert(KVPair.second);
2898ff0cc061SDimitry Andric   }
2899ff0cc061SDimitry Andric #endif
2900ff0cc061SDimitry Andric   // We may have base pointers which are now live that weren't before.  We need
2901ff0cc061SDimitry Andric   // to update the PointerToBase structure to reflect this.
2902ff0cc061SDimitry Andric   for (auto V : Updated)
2903ff0cc061SDimitry Andric     if (!Info.PointerToBase.count(V)) {
2904ff0cc061SDimitry Andric       assert(Bases.count(V) && "can't find base for unexpected live value");
2905ff0cc061SDimitry Andric       Info.PointerToBase[V] = V;
2906ff0cc061SDimitry Andric       continue;
2907ff0cc061SDimitry Andric     }
2908ff0cc061SDimitry Andric 
2909ff0cc061SDimitry Andric #ifndef NDEBUG
2910ff0cc061SDimitry Andric   for (auto V : Updated) {
2911ff0cc061SDimitry Andric     assert(Info.PointerToBase.count(V) &&
2912ff0cc061SDimitry Andric            "must be able to find base for live value");
2913ff0cc061SDimitry Andric   }
2914ff0cc061SDimitry Andric #endif
2915ff0cc061SDimitry Andric 
2916ff0cc061SDimitry Andric   // Remove any stale base mappings - this can happen since our liveness is
2917ff0cc061SDimitry Andric   // more precise then the one inherent in the base pointer analysis
2918ff0cc061SDimitry Andric   DenseSet<Value *> ToErase;
2919ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2920ff0cc061SDimitry Andric     if (!Updated.count(KVPair.first))
2921ff0cc061SDimitry Andric       ToErase.insert(KVPair.first);
2922ff0cc061SDimitry Andric   for (auto V : ToErase)
2923ff0cc061SDimitry Andric     Info.PointerToBase.erase(V);
2924ff0cc061SDimitry Andric 
2925ff0cc061SDimitry Andric #ifndef NDEBUG
2926ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2927ff0cc061SDimitry Andric     assert(Updated.count(KVPair.first) && "record for non-live value");
2928ff0cc061SDimitry Andric #endif
2929ff0cc061SDimitry Andric 
29307d523365SDimitry Andric   Info.LiveSet = Updated;
2931ff0cc061SDimitry Andric }
2932