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