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