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