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