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