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