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