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/ADT/SetOperations.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/DenseSet.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/IRBuilder.h" 25 #include "llvm/IR/InstIterator.h" 26 #include "llvm/IR/Instructions.h" 27 #include "llvm/IR/Intrinsics.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Statepoint.h" 31 #include "llvm/IR/Value.h" 32 #include "llvm/IR/Verifier.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Transforms/Scalar.h" 36 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 37 #include "llvm/Transforms/Utils/Cloning.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 40 41 #define DEBUG_TYPE "rewrite-statepoints-for-gc" 42 43 using namespace llvm; 44 45 // Print tracing output 46 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden, 47 cl::init(false)); 48 49 // Print the liveset found at the insert location 50 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden, 51 cl::init(false)); 52 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", 53 cl::Hidden, cl::init(false)); 54 // Print out the base pointers for debugging 55 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", 56 cl::Hidden, cl::init(false)); 57 58 namespace { 59 struct RewriteStatepointsForGC : public FunctionPass { 60 static char ID; // Pass identification, replacement for typeid 61 62 RewriteStatepointsForGC() : FunctionPass(ID) { 63 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry()); 64 } 65 bool runOnFunction(Function &F) override; 66 67 void getAnalysisUsage(AnalysisUsage &AU) const override { 68 // We add and rewrite a bunch of instructions, but don't really do much 69 // else. We could in theory preserve a lot more analyses here. 70 AU.addRequired<DominatorTreeWrapperPass>(); 71 } 72 }; 73 } // namespace 74 75 char RewriteStatepointsForGC::ID = 0; 76 77 FunctionPass *llvm::createRewriteStatepointsForGCPass() { 78 return new RewriteStatepointsForGC(); 79 } 80 81 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc", 82 "Make relocations explicit at statepoints", false, false) 83 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 84 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc", 85 "Make relocations explicit at statepoints", false, false) 86 87 namespace { 88 // The type of the internal cache used inside the findBasePointers family 89 // of functions. From the callers perspective, this is an opaque type and 90 // should not be inspected. 91 // 92 // In the actual implementation this caches two relations: 93 // - The base relation itself (i.e. this pointer is based on that one) 94 // - The base defining value relation (i.e. before base_phi insertion) 95 // Generally, after the execution of a full findBasePointer call, only the 96 // base relation will remain. Internally, we add a mixture of the two 97 // types, then update all the second type to the first type 98 typedef std::map<Value *, Value *> DefiningValueMapTy; 99 typedef std::set<llvm::Value *> StatepointLiveSetTy; 100 101 struct PartiallyConstructedSafepointRecord { 102 /// The set of values known to be live accross this safepoint 103 StatepointLiveSetTy liveset; 104 105 /// Mapping from live pointers to a base-defining-value 106 DenseMap<llvm::Value *, llvm::Value *> PointerToBase; 107 108 /// Any new values which were added to the IR during base pointer analysis 109 /// for this safepoint 110 DenseSet<llvm::Value *> NewInsertedDefs; 111 112 /// The *new* gc.statepoint instruction itself. This produces the token 113 /// that normal path gc.relocates and the gc.result are tied to. 114 Instruction *StatepointToken; 115 116 /// Instruction to which exceptional gc relocates are attached 117 /// Makes it easier to iterate through them during relocationViaAlloca. 118 Instruction *UnwindToken; 119 }; 120 } 121 122 // TODO: Once we can get to the GCStrategy, this becomes 123 // Optional<bool> isGCManagedPointer(const Value *V) const override { 124 125 static bool isGCPointerType(const Type *T) { 126 if (const PointerType *PT = dyn_cast<PointerType>(T)) 127 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our 128 // GC managed heap. We know that a pointer into this heap needs to be 129 // updated and that no other pointer does. 130 return (1 == PT->getAddressSpace()); 131 return false; 132 } 133 134 /// Return true if the Value is a gc reference type which is potentially used 135 /// after the instruction 'loc'. This is only used with the edge reachability 136 /// liveness code. Note: It is assumed the V dominates loc. 137 static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT, 138 LoopInfo *LI) { 139 if (!isGCPointerType(V.getType())) 140 return false; 141 142 if (V.use_empty()) 143 return false; 144 145 // Given assumption that V dominates loc, this may be live 146 return true; 147 } 148 149 #ifndef NDEBUG 150 static bool isAggWhichContainsGCPtrType(Type *Ty) { 151 if (VectorType *VT = dyn_cast<VectorType>(Ty)) 152 return isGCPointerType(VT->getScalarType()); 153 else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 154 return isGCPointerType(AT->getElementType()) || 155 isAggWhichContainsGCPtrType(AT->getElementType()); 156 } else if (StructType *ST = dyn_cast<StructType>(Ty)) { 157 bool UnsupportedType = false; 158 for (Type *SubType : ST->subtypes()) 159 UnsupportedType |= 160 isGCPointerType(SubType) || isAggWhichContainsGCPtrType(SubType); 161 return UnsupportedType; 162 } else 163 return false; 164 } 165 #endif 166 167 // Conservatively identifies any definitions which might be live at the 168 // given instruction. The analysis is performed immediately before the 169 // given instruction. Values defined by that instruction are not considered 170 // live. Values used by that instruction are considered live. 171 // 172 // preconditions: valid IR graph, term is either a terminator instruction or 173 // a call instruction, pred is the basic block of term, DT, LI are valid 174 // 175 // side effects: none, does not mutate IR 176 // 177 // postconditions: populates liveValues as discussed above 178 static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred, 179 DominatorTree &DT, LoopInfo *LI, 180 std::set<llvm::Value *> &liveValues) { 181 liveValues.clear(); 182 183 assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator()); 184 185 Function *F = pred->getParent(); 186 187 auto is_live_gc_reference = 188 [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); }; 189 190 // Are there any gc pointer arguments live over this point? This needs to be 191 // special cased since arguments aren't defined in basic blocks. 192 for (Argument &arg : F->args()) { 193 assert(!isAggWhichContainsGCPtrType(arg.getType()) && 194 "support for FCA unimplemented"); 195 196 if (is_live_gc_reference(arg)) { 197 liveValues.insert(&arg); 198 } 199 } 200 201 // Walk through all dominating blocks - the ones which can contain 202 // definitions used in this block - and check to see if any of the values 203 // they define are used in locations potentially reachable from the 204 // interesting instruction. 205 BasicBlock *BBI = pred; 206 while (true) { 207 if (TraceLSP) { 208 errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n"; 209 } 210 assert(DT.dominates(BBI, pred)); 211 assert(isPotentiallyReachable(BBI, pred, &DT) && 212 "dominated block must be reachable"); 213 214 // Walk through the instructions in dominating blocks and keep any 215 // that have a use potentially reachable from the block we're 216 // considering putting the safepoint in 217 for (Instruction &inst : *BBI) { 218 if (TraceLSP) { 219 errs() << "[LSP] Looking at instruction "; 220 inst.dump(); 221 } 222 223 if (pred == BBI && (&inst) == term) { 224 if (TraceLSP) { 225 errs() << "[LSP] stopped because we encountered the safepoint " 226 "instruction.\n"; 227 } 228 229 // If we're in the block which defines the interesting instruction, 230 // we don't want to include any values as live which are defined 231 // _after_ the interesting line or as part of the line itself 232 // i.e. "term" is the call instruction for a call safepoint, the 233 // results of the call should not be considered live in that stackmap 234 break; 235 } 236 237 assert(!isAggWhichContainsGCPtrType(inst.getType()) && 238 "support for FCA unimplemented"); 239 240 if (is_live_gc_reference(inst)) { 241 if (TraceLSP) { 242 errs() << "[LSP] found live value for this safepoint "; 243 inst.dump(); 244 term->dump(); 245 } 246 liveValues.insert(&inst); 247 } 248 } 249 if (!DT.getNode(BBI)->getIDom()) { 250 assert(BBI == &F->getEntryBlock() && 251 "failed to find a dominator for something other than " 252 "the entry block"); 253 break; 254 } 255 BBI = DT.getNode(BBI)->getIDom()->getBlock(); 256 } 257 } 258 259 static bool order_by_name(llvm::Value *a, llvm::Value *b) { 260 if (a->hasName() && b->hasName()) { 261 return -1 == a->getName().compare(b->getName()); 262 } else if (a->hasName() && !b->hasName()) { 263 return true; 264 } else if (!a->hasName() && b->hasName()) { 265 return false; 266 } else { 267 // Better than nothing, but not stable 268 return a < b; 269 } 270 } 271 272 /// Find the initial live set. Note that due to base pointer 273 /// insertion, the live set may be incomplete. 274 static void 275 analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS, 276 PartiallyConstructedSafepointRecord &result) { 277 Instruction *inst = CS.getInstruction(); 278 279 BasicBlock *BB = inst->getParent(); 280 std::set<Value *> liveset; 281 findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset); 282 283 if (PrintLiveSet) { 284 // Note: This output is used by several of the test cases 285 // The order of elemtns in a set is not stable, put them in a vec and sort 286 // by name 287 SmallVector<Value *, 64> temp; 288 temp.insert(temp.end(), liveset.begin(), liveset.end()); 289 std::sort(temp.begin(), temp.end(), order_by_name); 290 errs() << "Live Variables:\n"; 291 for (Value *V : temp) { 292 errs() << " " << V->getName(); // no newline 293 V->dump(); 294 } 295 } 296 if (PrintLiveSetSize) { 297 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n"; 298 errs() << "Number live values: " << liveset.size() << "\n"; 299 } 300 result.liveset = liveset; 301 } 302 303 /// True iff this value is the null pointer constant (of any pointer type) 304 static bool isNullConstant(Value *V) { 305 return isa<Constant>(V) && isa<PointerType>(V->getType()) && 306 cast<Constant>(V)->isNullValue(); 307 } 308 309 /// Helper function for findBasePointer - Will return a value which either a) 310 /// defines the base pointer for the input or b) blocks the simple search 311 /// (i.e. a PHI or Select of two derived pointers) 312 static Value *findBaseDefiningValue(Value *I) { 313 assert(I->getType()->isPointerTy() && 314 "Illegal to ask for the base pointer of a non-pointer type"); 315 316 // There are instructions which can never return gc pointer values. Sanity 317 // check 318 // that this is actually true. 319 assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 320 !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers"); 321 assert((!isa<Instruction>(I) || isa<InvokeInst>(I) || 322 !cast<Instruction>(I)->isTerminator()) && 323 "With the exception of invoke terminators don't define values"); 324 assert(!isa<StoreInst>(I) && !isa<FenceInst>(I) && 325 "Can't be definitions to start with"); 326 assert(!isa<ICmpInst>(I) && !isa<FCmpInst>(I) && 327 "Comparisons don't give ops"); 328 // There's a bunch of instructions which just don't make sense to apply to 329 // a pointer. The only valid reason for this would be pointer bit 330 // twiddling which we're just not going to support. 331 assert((!isa<Instruction>(I) || !cast<Instruction>(I)->isBinaryOp()) && 332 "Binary ops on pointer values are meaningless. Unless your " 333 "bit-twiddling which we don't support"); 334 335 if (Argument *Arg = dyn_cast<Argument>(I)) { 336 // An incoming argument to the function is a base pointer 337 // We should have never reached here if this argument isn't an gc value 338 assert(Arg->getType()->isPointerTy() && 339 "Base for pointer must be another pointer"); 340 return Arg; 341 } 342 343 if (GlobalVariable *global = dyn_cast<GlobalVariable>(I)) { 344 // base case 345 assert(global->getType()->isPointerTy() && 346 "Base for pointer must be another pointer"); 347 return global; 348 } 349 350 // inlining could possibly introduce phi node that contains 351 // undef if callee has multiple returns 352 if (UndefValue *undef = dyn_cast<UndefValue>(I)) { 353 assert(undef->getType()->isPointerTy() && 354 "Base for pointer must be another pointer"); 355 return undef; // utterly meaningless, but useful for dealing with 356 // partially optimized code. 357 } 358 359 // Due to inheritance, this must be _after_ the global variable and undef 360 // checks 361 if (Constant *con = dyn_cast<Constant>(I)) { 362 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) && 363 "order of checks wrong!"); 364 // Note: Finding a constant base for something marked for relocation 365 // doesn't really make sense. The most likely case is either a) some 366 // screwed up the address space usage or b) your validating against 367 // compiled C++ code w/o the proper separation. The only real exception 368 // is a null pointer. You could have generic code written to index of 369 // off a potentially null value and have proven it null. We also use 370 // null pointers in dead paths of relocation phis (which we might later 371 // want to find a base pointer for). 372 assert(con->getType()->isPointerTy() && 373 "Base for pointer must be another pointer"); 374 assert(con->isNullValue() && "null is the only case which makes sense"); 375 return con; 376 } 377 378 if (CastInst *CI = dyn_cast<CastInst>(I)) { 379 Value *def = CI->stripPointerCasts(); 380 assert(def->getType()->isPointerTy() && 381 "Base for pointer must be another pointer"); 382 if (isa<CastInst>(def)) { 383 // If we find a cast instruction here, it means we've found a cast 384 // which is not simply a pointer cast (i.e. an inttoptr). We don't 385 // know how to handle int->ptr conversion. 386 llvm_unreachable("Can not find the base pointers for an inttoptr cast"); 387 } 388 assert(!isa<CastInst>(def) && "shouldn't find another cast here"); 389 return findBaseDefiningValue(def); 390 } 391 392 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 393 if (LI->getType()->isPointerTy()) { 394 Value *Op = LI->getOperand(0); 395 (void)Op; 396 // Has to be a pointer to an gc object, or possibly an array of such? 397 assert(Op->getType()->isPointerTy()); 398 return LI; // The value loaded is an gc base itself 399 } 400 } 401 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { 402 Value *Op = GEP->getOperand(0); 403 if (Op->getType()->isPointerTy()) { 404 return findBaseDefiningValue(Op); // The base of this GEP is the base 405 } 406 } 407 408 if (AllocaInst *alloc = dyn_cast<AllocaInst>(I)) { 409 // An alloca represents a conceptual stack slot. It's the slot itself 410 // that the GC needs to know about, not the value in the slot. 411 assert(alloc->getType()->isPointerTy() && 412 "Base for pointer must be another pointer"); 413 return alloc; 414 } 415 416 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 417 switch (II->getIntrinsicID()) { 418 default: 419 // fall through to general call handling 420 break; 421 case Intrinsic::experimental_gc_statepoint: 422 case Intrinsic::experimental_gc_result_float: 423 case Intrinsic::experimental_gc_result_int: 424 llvm_unreachable("these don't produce pointers"); 425 case Intrinsic::experimental_gc_result_ptr: 426 // This is just a special case of the CallInst check below to handle a 427 // statepoint with deopt args which hasn't been rewritten for GC yet. 428 // TODO: Assert that the statepoint isn't rewritten yet. 429 return II; 430 case Intrinsic::experimental_gc_relocate: { 431 // Rerunning safepoint insertion after safepoints are already 432 // inserted is not supported. It could probably be made to work, 433 // but why are you doing this? There's no good reason. 434 llvm_unreachable("repeat safepoint insertion is not supported"); 435 } 436 case Intrinsic::gcroot: 437 // Currently, this mechanism hasn't been extended to work with gcroot. 438 // There's no reason it couldn't be, but I haven't thought about the 439 // implications much. 440 llvm_unreachable( 441 "interaction with the gcroot mechanism is not supported"); 442 } 443 } 444 // We assume that functions in the source language only return base 445 // pointers. This should probably be generalized via attributes to support 446 // both source language and internal functions. 447 if (CallInst *call = dyn_cast<CallInst>(I)) { 448 assert(call->getType()->isPointerTy() && 449 "Base for pointer must be another pointer"); 450 return call; 451 } 452 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) { 453 assert(invoke->getType()->isPointerTy() && 454 "Base for pointer must be another pointer"); 455 return invoke; 456 } 457 458 // I have absolutely no idea how to implement this part yet. It's not 459 // neccessarily hard, I just haven't really looked at it yet. 460 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented"); 461 462 if (AtomicCmpXchgInst *cas = dyn_cast<AtomicCmpXchgInst>(I)) { 463 // A CAS is effectively a atomic store and load combined under a 464 // predicate. From the perspective of base pointers, we just treat it 465 // like a load. We loaded a pointer from a address in memory, that value 466 // had better be a valid base pointer. 467 return cas->getPointerOperand(); 468 } 469 if (AtomicRMWInst *atomic = dyn_cast<AtomicRMWInst>(I)) { 470 assert(AtomicRMWInst::Xchg == atomic->getOperation() && 471 "All others are binary ops which don't apply to base pointers"); 472 // semantically, a load, store pair. Treat it the same as a standard load 473 return atomic->getPointerOperand(); 474 } 475 476 // The aggregate ops. Aggregates can either be in the heap or on the 477 // stack, but in either case, this is simply a field load. As a result, 478 // this is a defining definition of the base just like a load is. 479 if (ExtractValueInst *ev = dyn_cast<ExtractValueInst>(I)) { 480 return ev; 481 } 482 483 // We should never see an insert vector since that would require we be 484 // tracing back a struct value not a pointer value. 485 assert(!isa<InsertValueInst>(I) && 486 "Base pointer for a struct is meaningless"); 487 488 // The last two cases here don't return a base pointer. Instead, they 489 // return a value which dynamically selects from amoung several base 490 // derived pointers (each with it's own base potentially). It's the job of 491 // the caller to resolve these. 492 if (SelectInst *select = dyn_cast<SelectInst>(I)) { 493 return select; 494 } 495 if (PHINode *phi = dyn_cast<PHINode>(I)) { 496 return phi; 497 } 498 499 errs() << "unknown type: " << *I << "\n"; 500 llvm_unreachable("unknown type"); 501 return nullptr; 502 } 503 504 /// Returns the base defining value for this value. 505 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) { 506 Value *&Cached = cache[I]; 507 if (!Cached) { 508 Cached = findBaseDefiningValue(I); 509 } 510 assert(cache[I] != nullptr); 511 512 if (TraceLSP) { 513 errs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName() 514 << "\n"; 515 } 516 return Cached; 517 } 518 519 /// Return a base pointer for this value if known. Otherwise, return it's 520 /// base defining value. 521 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) { 522 Value *def = findBaseDefiningValueCached(I, cache); 523 auto Found = cache.find(def); 524 if (Found != cache.end()) { 525 // Either a base-of relation, or a self reference. Caller must check. 526 return Found->second; 527 } 528 // Only a BDV available 529 return def; 530 } 531 532 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV, 533 /// is it known to be a base pointer? Or do we need to continue searching. 534 static bool isKnownBaseResult(Value *v) { 535 if (!isa<PHINode>(v) && !isa<SelectInst>(v)) { 536 // no recursion possible 537 return true; 538 } 539 if (cast<Instruction>(v)->getMetadata("is_base_value")) { 540 // This is a previously inserted base phi or select. We know 541 // that this is a base value. 542 return true; 543 } 544 545 // We need to keep searching 546 return false; 547 } 548 549 // TODO: find a better name for this 550 namespace { 551 class PhiState { 552 public: 553 enum Status { Unknown, Base, Conflict }; 554 555 PhiState(Status s, Value *b = nullptr) : status(s), base(b) { 556 assert(status != Base || b); 557 } 558 PhiState(Value *b) : status(Base), base(b) {} 559 PhiState() : status(Unknown), base(nullptr) {} 560 PhiState(const PhiState &other) : status(other.status), base(other.base) { 561 assert(status != Base || base); 562 } 563 564 Status getStatus() const { return status; } 565 Value *getBase() const { return base; } 566 567 bool isBase() const { return getStatus() == Base; } 568 bool isUnknown() const { return getStatus() == Unknown; } 569 bool isConflict() const { return getStatus() == Conflict; } 570 571 bool operator==(const PhiState &other) const { 572 return base == other.base && status == other.status; 573 } 574 575 bool operator!=(const PhiState &other) const { return !(*this == other); } 576 577 void dump() { 578 errs() << status << " (" << base << " - " 579 << (base ? base->getName() : "nullptr") << "): "; 580 } 581 582 private: 583 Status status; 584 Value *base; // non null only if status == base 585 }; 586 587 typedef std::map<Value *, PhiState> ConflictStateMapTy; 588 // Values of type PhiState form a lattice, and this is a helper 589 // class that implementes the meet operation. The meat of the meet 590 // operation is implemented in MeetPhiStates::pureMeet 591 class MeetPhiStates { 592 public: 593 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates. 594 explicit MeetPhiStates(const ConflictStateMapTy &phiStates) 595 : phiStates(phiStates) {} 596 597 // Destructively meet the current result with the base V. V can 598 // either be a merge instruction (SelectInst / PHINode), in which 599 // case its status is looked up in the phiStates map; or a regular 600 // SSA value, in which case it is assumed to be a base. 601 void meetWith(Value *V) { 602 PhiState otherState = getStateForBDV(V); 603 assert((MeetPhiStates::pureMeet(otherState, currentResult) == 604 MeetPhiStates::pureMeet(currentResult, otherState)) && 605 "math is wrong: meet does not commute!"); 606 currentResult = MeetPhiStates::pureMeet(otherState, currentResult); 607 } 608 609 PhiState getResult() const { return currentResult; } 610 611 private: 612 const ConflictStateMapTy &phiStates; 613 PhiState currentResult; 614 615 /// Return a phi state for a base defining value. We'll generate a new 616 /// base state for known bases and expect to find a cached state otherwise 617 PhiState getStateForBDV(Value *baseValue) { 618 if (isKnownBaseResult(baseValue)) { 619 return PhiState(baseValue); 620 } else { 621 return lookupFromMap(baseValue); 622 } 623 } 624 625 PhiState lookupFromMap(Value *V) { 626 auto I = phiStates.find(V); 627 assert(I != phiStates.end() && "lookup failed!"); 628 return I->second; 629 } 630 631 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) { 632 switch (stateA.getStatus()) { 633 case PhiState::Unknown: 634 return stateB; 635 636 case PhiState::Base: 637 assert(stateA.getBase() && "can't be null"); 638 if (stateB.isUnknown()) { 639 return stateA; 640 } else if (stateB.isBase()) { 641 if (stateA.getBase() == stateB.getBase()) { 642 assert(stateA == stateB && "equality broken!"); 643 return stateA; 644 } 645 return PhiState(PhiState::Conflict); 646 } else { 647 assert(stateB.isConflict() && "only three states!"); 648 return PhiState(PhiState::Conflict); 649 } 650 651 case PhiState::Conflict: 652 return stateA; 653 } 654 llvm_unreachable("only three states!"); 655 } 656 }; 657 } 658 /// For a given value or instruction, figure out what base ptr it's derived 659 /// from. For gc objects, this is simply itself. On success, returns a value 660 /// which is the base pointer. (This is reliable and can be used for 661 /// relocation.) On failure, returns nullptr. 662 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache, 663 DenseSet<llvm::Value *> &NewInsertedDefs) { 664 Value *def = findBaseOrBDV(I, cache); 665 666 if (isKnownBaseResult(def)) { 667 return def; 668 } 669 670 // Here's the rough algorithm: 671 // - For every SSA value, construct a mapping to either an actual base 672 // pointer or a PHI which obscures the base pointer. 673 // - Construct a mapping from PHI to unknown TOP state. Use an 674 // optimistic algorithm to propagate base pointer information. Lattice 675 // looks like: 676 // UNKNOWN 677 // b1 b2 b3 b4 678 // CONFLICT 679 // When algorithm terminates, all PHIs will either have a single concrete 680 // base or be in a conflict state. 681 // - For every conflict, insert a dummy PHI node without arguments. Add 682 // these to the base[Instruction] = BasePtr mapping. For every 683 // non-conflict, add the actual base. 684 // - For every conflict, add arguments for the base[a] of each input 685 // arguments. 686 // 687 // Note: A simpler form of this would be to add the conflict form of all 688 // PHIs without running the optimistic algorithm. This would be 689 // analougous to pessimistic data flow and would likely lead to an 690 // overall worse solution. 691 692 ConflictStateMapTy states; 693 states[def] = PhiState(); 694 // Recursively fill in all phis & selects reachable from the initial one 695 // for which we don't already know a definite base value for 696 // PERF: Yes, this is as horribly inefficient as it looks. 697 bool done = false; 698 while (!done) { 699 done = true; 700 for (auto Pair : states) { 701 Value *v = Pair.first; 702 assert(!isKnownBaseResult(v) && "why did it get added?"); 703 if (PHINode *phi = dyn_cast<PHINode>(v)) { 704 unsigned NumPHIValues = phi->getNumIncomingValues(); 705 assert(NumPHIValues > 0 && "zero input phis are illegal"); 706 for (unsigned i = 0; i != NumPHIValues; ++i) { 707 Value *InVal = phi->getIncomingValue(i); 708 Value *local = findBaseOrBDV(InVal, cache); 709 if (!isKnownBaseResult(local) && states.find(local) == states.end()) { 710 states[local] = PhiState(); 711 done = false; 712 } 713 } 714 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) { 715 Value *local = findBaseOrBDV(sel->getTrueValue(), cache); 716 if (!isKnownBaseResult(local) && states.find(local) == states.end()) { 717 states[local] = PhiState(); 718 done = false; 719 } 720 local = findBaseOrBDV(sel->getFalseValue(), cache); 721 if (!isKnownBaseResult(local) && states.find(local) == states.end()) { 722 states[local] = PhiState(); 723 done = false; 724 } 725 } 726 } 727 } 728 729 if (TraceLSP) { 730 errs() << "States after initialization:\n"; 731 for (auto Pair : states) { 732 Instruction *v = cast<Instruction>(Pair.first); 733 PhiState state = Pair.second; 734 state.dump(); 735 v->dump(); 736 } 737 } 738 739 // TODO: come back and revisit the state transitions around inputs which 740 // have reached conflict state. The current version seems too conservative. 741 742 bool progress = true; 743 size_t oldSize = 0; 744 while (progress) { 745 oldSize = states.size(); 746 progress = false; 747 for (auto Pair : states) { 748 MeetPhiStates calculateMeet(states); 749 Value *v = Pair.first; 750 assert(!isKnownBaseResult(v) && "why did it get added?"); 751 assert(isa<SelectInst>(v) || isa<PHINode>(v)); 752 if (SelectInst *select = dyn_cast<SelectInst>(v)) { 753 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache)); 754 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache)); 755 } else if (PHINode *phi = dyn_cast<PHINode>(v)) { 756 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) { 757 calculateMeet.meetWith( 758 findBaseOrBDV(phi->getIncomingValue(i), cache)); 759 } 760 } else { 761 llvm_unreachable("no such state expected"); 762 } 763 764 PhiState oldState = states[v]; 765 PhiState newState = calculateMeet.getResult(); 766 if (oldState != newState) { 767 progress = true; 768 states[v] = newState; 769 } 770 } 771 772 assert(oldSize <= states.size()); 773 assert(oldSize == states.size() || progress); 774 } 775 776 if (TraceLSP) { 777 errs() << "States after meet iteration:\n"; 778 for (auto Pair : states) { 779 Instruction *v = cast<Instruction>(Pair.first); 780 PhiState state = Pair.second; 781 state.dump(); 782 v->dump(); 783 } 784 } 785 786 // Insert Phis for all conflicts 787 for (auto Pair : states) { 788 Instruction *v = cast<Instruction>(Pair.first); 789 PhiState state = Pair.second; 790 assert(!isKnownBaseResult(v) && "why did it get added?"); 791 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!"); 792 if (state.isConflict()) { 793 if (isa<PHINode>(v)) { 794 int num_preds = 795 std::distance(pred_begin(v->getParent()), pred_end(v->getParent())); 796 assert(num_preds > 0 && "how did we reach here"); 797 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v); 798 NewInsertedDefs.insert(phi); 799 // Add metadata marking this as a base value 800 auto *const_1 = ConstantInt::get( 801 Type::getInt32Ty( 802 v->getParent()->getParent()->getParent()->getContext()), 803 1); 804 auto MDConst = ConstantAsMetadata::get(const_1); 805 MDNode *md = MDNode::get( 806 v->getParent()->getParent()->getParent()->getContext(), MDConst); 807 phi->setMetadata("is_base_value", md); 808 states[v] = PhiState(PhiState::Conflict, phi); 809 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) { 810 // The undef will be replaced later 811 UndefValue *undef = UndefValue::get(sel->getType()); 812 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef, 813 undef, "base_select", sel); 814 NewInsertedDefs.insert(basesel); 815 // Add metadata marking this as a base value 816 auto *const_1 = ConstantInt::get( 817 Type::getInt32Ty( 818 v->getParent()->getParent()->getParent()->getContext()), 819 1); 820 auto MDConst = ConstantAsMetadata::get(const_1); 821 MDNode *md = MDNode::get( 822 v->getParent()->getParent()->getParent()->getContext(), MDConst); 823 basesel->setMetadata("is_base_value", md); 824 states[v] = PhiState(PhiState::Conflict, basesel); 825 } else 826 llvm_unreachable("unknown conflict type"); 827 } 828 } 829 830 // Fixup all the inputs of the new PHIs 831 for (auto Pair : states) { 832 Instruction *v = cast<Instruction>(Pair.first); 833 PhiState state = Pair.second; 834 835 assert(!isKnownBaseResult(v) && "why did it get added?"); 836 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!"); 837 if (state.isConflict()) { 838 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) { 839 PHINode *phi = cast<PHINode>(v); 840 unsigned NumPHIValues = phi->getNumIncomingValues(); 841 for (unsigned i = 0; i < NumPHIValues; i++) { 842 Value *InVal = phi->getIncomingValue(i); 843 BasicBlock *InBB = phi->getIncomingBlock(i); 844 845 // If we've already seen InBB, add the same incoming value 846 // we added for it earlier. The IR verifier requires phi 847 // nodes with multiple entries from the same basic block 848 // to have the same incoming value for each of those 849 // entries. If we don't do this check here and basephi 850 // has a different type than base, we'll end up adding two 851 // bitcasts (and hence two distinct values) as incoming 852 // values for the same basic block. 853 854 int blockIndex = basephi->getBasicBlockIndex(InBB); 855 if (blockIndex != -1) { 856 Value *oldBase = basephi->getIncomingValue(blockIndex); 857 basephi->addIncoming(oldBase, InBB); 858 #ifndef NDEBUG 859 Value *base = findBaseOrBDV(InVal, cache); 860 if (!isKnownBaseResult(base)) { 861 // Either conflict or base. 862 assert(states.count(base)); 863 base = states[base].getBase(); 864 assert(base != nullptr && "unknown PhiState!"); 865 assert(NewInsertedDefs.count(base) && 866 "should have already added this in a prev. iteration!"); 867 } 868 869 // In essense this assert states: the only way two 870 // values incoming from the same basic block may be 871 // different is by being different bitcasts of the same 872 // value. A cleanup that remains TODO is changing 873 // findBaseOrBDV to return an llvm::Value of the correct 874 // type (and still remain pure). This will remove the 875 // need to add bitcasts. 876 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() && 877 "sanity -- findBaseOrBDV should be pure!"); 878 #endif 879 continue; 880 } 881 882 // Find either the defining value for the PHI or the normal base for 883 // a non-phi node 884 Value *base = findBaseOrBDV(InVal, cache); 885 if (!isKnownBaseResult(base)) { 886 // Either conflict or base. 887 assert(states.count(base)); 888 base = states[base].getBase(); 889 assert(base != nullptr && "unknown PhiState!"); 890 } 891 assert(base && "can't be null"); 892 // Must use original input BB since base may not be Instruction 893 // The cast is needed since base traversal may strip away bitcasts 894 if (base->getType() != basephi->getType()) { 895 base = new BitCastInst(base, basephi->getType(), "cast", 896 InBB->getTerminator()); 897 NewInsertedDefs.insert(base); 898 } 899 basephi->addIncoming(base, InBB); 900 } 901 assert(basephi->getNumIncomingValues() == NumPHIValues); 902 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) { 903 SelectInst *sel = cast<SelectInst>(v); 904 // Operand 1 & 2 are true, false path respectively. TODO: refactor to 905 // something more safe and less hacky. 906 for (int i = 1; i <= 2; i++) { 907 Value *InVal = sel->getOperand(i); 908 // Find either the defining value for the PHI or the normal base for 909 // a non-phi node 910 Value *base = findBaseOrBDV(InVal, cache); 911 if (!isKnownBaseResult(base)) { 912 // Either conflict or base. 913 assert(states.count(base)); 914 base = states[base].getBase(); 915 assert(base != nullptr && "unknown PhiState!"); 916 } 917 assert(base && "can't be null"); 918 // Must use original input BB since base may not be Instruction 919 // The cast is needed since base traversal may strip away bitcasts 920 if (base->getType() != basesel->getType()) { 921 base = new BitCastInst(base, basesel->getType(), "cast", basesel); 922 NewInsertedDefs.insert(base); 923 } 924 basesel->setOperand(i, base); 925 } 926 } else 927 llvm_unreachable("unexpected conflict type"); 928 } 929 } 930 931 // Cache all of our results so we can cheaply reuse them 932 // NOTE: This is actually two caches: one of the base defining value 933 // relation and one of the base pointer relation! FIXME 934 for (auto item : states) { 935 Value *v = item.first; 936 Value *base = item.second.getBase(); 937 assert(v && base); 938 assert(!isKnownBaseResult(v) && "why did it get added?"); 939 940 if (TraceLSP) { 941 std::string fromstr = 942 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "") 943 : "none"; 944 errs() << "Updating base value cache" 945 << " for: " << (v->hasName() ? v->getName() : "") 946 << " from: " << fromstr 947 << " to: " << (base->hasName() ? base->getName() : "") << "\n"; 948 } 949 950 assert(isKnownBaseResult(base) && 951 "must be something we 'know' is a base pointer"); 952 if (cache.count(v)) { 953 // Once we transition from the BDV relation being store in the cache to 954 // the base relation being stored, it must be stable 955 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) && 956 "base relation should be stable"); 957 } 958 cache[v] = base; 959 } 960 assert(cache.find(def) != cache.end()); 961 return cache[def]; 962 } 963 964 // For a set of live pointers (base and/or derived), identify the base 965 // pointer of the object which they are derived from. This routine will 966 // mutate the IR graph as needed to make the 'base' pointer live at the 967 // definition site of 'derived'. This ensures that any use of 'derived' can 968 // also use 'base'. This may involve the insertion of a number of 969 // additional PHI nodes. 970 // 971 // preconditions: live is a set of pointer type Values 972 // 973 // side effects: may insert PHI nodes into the existing CFG, will preserve 974 // CFG, will not remove or mutate any existing nodes 975 // 976 // post condition: PointerToBase contains one (derived, base) pair for every 977 // pointer in live. Note that derived can be equal to base if the original 978 // pointer was a base pointer. 979 static void findBasePointers(const std::set<llvm::Value *> &live, 980 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase, 981 DominatorTree *DT, DefiningValueMapTy &DVCache, 982 DenseSet<llvm::Value *> &NewInsertedDefs) { 983 for (Value *ptr : live) { 984 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs); 985 assert(base && "failed to find base pointer"); 986 PointerToBase[ptr] = base; 987 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) || 988 DT->dominates(cast<Instruction>(base)->getParent(), 989 cast<Instruction>(ptr)->getParent())) && 990 "The base we found better dominate the derived pointer"); 991 992 if (isNullConstant(base)) 993 // If you see this trip and like to live really dangerously, the code 994 // should be correct, just with idioms the verifier can't handle. You 995 // can try disabling the verifier at your own substaintial risk. 996 llvm_unreachable("the relocation code needs adjustment to handle the" 997 "relocation of a null pointer constant without causing" 998 "false positives in the safepoint ir verifier."); 999 } 1000 } 1001 1002 /// Find the required based pointers (and adjust the live set) for the given 1003 /// parse point. 1004 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache, 1005 const CallSite &CS, 1006 PartiallyConstructedSafepointRecord &result) { 1007 DenseMap<llvm::Value *, llvm::Value *> PointerToBase; 1008 DenseSet<llvm::Value *> NewInsertedDefs; 1009 findBasePointers(result.liveset, PointerToBase, &DT, DVCache, NewInsertedDefs); 1010 1011 if (PrintBasePointers) { 1012 errs() << "Base Pairs (w/o Relocation):\n"; 1013 for (auto Pair : PointerToBase) { 1014 errs() << " derived %" << Pair.first->getName() << " base %" 1015 << Pair.second->getName() << "\n"; 1016 } 1017 } 1018 1019 result.PointerToBase = PointerToBase; 1020 result.NewInsertedDefs = NewInsertedDefs; 1021 } 1022 1023 /// Check for liveness of items in the insert defs and add them to the live 1024 /// and base pointer sets 1025 static void fixupLiveness(DominatorTree &DT, const CallSite &CS, 1026 const std::set<Value *> &allInsertedDefs, 1027 PartiallyConstructedSafepointRecord &result) { 1028 Instruction *inst = CS.getInstruction(); 1029 1030 auto liveset = result.liveset; 1031 auto PointerToBase = result.PointerToBase; 1032 1033 auto is_live_gc_reference = 1034 [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); }; 1035 1036 // For each new definition, check to see if a) the definition dominates the 1037 // instruction we're interested in, and b) one of the uses of that definition 1038 // is edge-reachable from the instruction we're interested in. This is the 1039 // same definition of liveness we used in the intial liveness analysis 1040 for (Value *newDef : allInsertedDefs) { 1041 if (liveset.count(newDef)) { 1042 // already live, no action needed 1043 continue; 1044 } 1045 1046 // PERF: Use DT to check instruction domination might not be good for 1047 // compilation time, and we could change to optimal solution if this 1048 // turn to be a issue 1049 if (!DT.dominates(cast<Instruction>(newDef), inst)) { 1050 // can't possibly be live at inst 1051 continue; 1052 } 1053 1054 if (is_live_gc_reference(*newDef)) { 1055 // Add the live new defs into liveset and PointerToBase 1056 liveset.insert(newDef); 1057 PointerToBase[newDef] = newDef; 1058 } 1059 } 1060 1061 result.liveset = liveset; 1062 result.PointerToBase = PointerToBase; 1063 } 1064 1065 static void fixupLiveReferences( 1066 Function &F, DominatorTree &DT, Pass *P, 1067 const std::set<llvm::Value *> &allInsertedDefs, 1068 std::vector<CallSite> &toUpdate, 1069 std::vector<struct PartiallyConstructedSafepointRecord> &records) { 1070 for (size_t i = 0; i < records.size(); i++) { 1071 struct PartiallyConstructedSafepointRecord &info = records[i]; 1072 CallSite &CS = toUpdate[i]; 1073 fixupLiveness(DT, CS, allInsertedDefs, info); 1074 } 1075 } 1076 1077 // Normalize basic block to make it ready to be target of invoke statepoint. 1078 // It means spliting it to have single predecessor. Return newly created BB 1079 // ready to be successor of invoke statepoint. 1080 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB, 1081 BasicBlock *InvokeParent, 1082 Pass *P) { 1083 BasicBlock *ret = BB; 1084 1085 if (!BB->getUniquePredecessor()) { 1086 ret = SplitBlockPredecessors(BB, InvokeParent, ""); 1087 } 1088 1089 // Another requirement for such basic blocks is to not have any phi nodes. 1090 // Since we just ensured that new BB will have single predecessor, 1091 // all phi nodes in it will have one value. Here it would be naturall place 1092 // to 1093 // remove them all. But we can not do this because we are risking to remove 1094 // one of the values stored in liveset of another statepoint. We will do it 1095 // later after placing all safepoints. 1096 1097 return ret; 1098 } 1099 1100 static int find_index(const SmallVectorImpl<Value *> &livevec, Value *val) { 1101 auto itr = std::find(livevec.begin(), livevec.end(), val); 1102 assert(livevec.end() != itr); 1103 size_t index = std::distance(livevec.begin(), itr); 1104 assert(index < livevec.size()); 1105 return index; 1106 } 1107 1108 // Create new attribute set containing only attributes which can be transfered 1109 // from original call to the safepoint. 1110 static AttributeSet legalizeCallAttributes(AttributeSet AS) { 1111 AttributeSet ret; 1112 1113 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) { 1114 unsigned index = AS.getSlotIndex(Slot); 1115 1116 if (index == AttributeSet::ReturnIndex || 1117 index == AttributeSet::FunctionIndex) { 1118 1119 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end; 1120 ++it) { 1121 Attribute attr = *it; 1122 1123 // Do not allow certain attributes - just skip them 1124 // Safepoint can not be read only or read none. 1125 if (attr.hasAttribute(Attribute::ReadNone) || 1126 attr.hasAttribute(Attribute::ReadOnly)) 1127 continue; 1128 1129 ret = ret.addAttributes( 1130 AS.getContext(), index, 1131 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr))); 1132 } 1133 } 1134 1135 // Just skip parameter attributes for now 1136 } 1137 1138 return ret; 1139 } 1140 1141 /// Helper function to place all gc relocates necessary for the given 1142 /// statepoint. 1143 /// Inputs: 1144 /// liveVariables - list of variables to be relocated. 1145 /// liveStart - index of the first live variable. 1146 /// basePtrs - base pointers. 1147 /// statepointToken - statepoint instruction to which relocates should be 1148 /// bound. 1149 /// Builder - Llvm IR builder to be used to construct new calls. 1150 /// Returns array with newly created relocates. 1151 static std::vector<llvm::Instruction *> 1152 CreateGCRelocates(const SmallVectorImpl<llvm::Value *> &liveVariables, 1153 const int liveStart, 1154 const SmallVectorImpl<llvm::Value *> &basePtrs, 1155 Instruction *statepointToken, IRBuilder<> Builder) { 1156 1157 std::vector<llvm::Instruction *> newDefs; 1158 1159 Module *M = statepointToken->getParent()->getParent()->getParent(); 1160 1161 for (unsigned i = 0; i < liveVariables.size(); i++) { 1162 // We generate a (potentially) unique declaration for every pointer type 1163 // combination. This results is some blow up the function declarations in 1164 // the IR, but removes the need for argument bitcasts which shrinks the IR 1165 // greatly and makes it much more readable. 1166 std::vector<Type *> types; // one per 'any' type 1167 types.push_back(liveVariables[i]->getType()); // result type 1168 Value *gc_relocate_decl = Intrinsic::getDeclaration( 1169 M, Intrinsic::experimental_gc_relocate, types); 1170 1171 // Generate the gc.relocate call and save the result 1172 Value *baseIdx = 1173 ConstantInt::get(Type::getInt32Ty(M->getContext()), 1174 liveStart + find_index(liveVariables, basePtrs[i])); 1175 Value *liveIdx = ConstantInt::get( 1176 Type::getInt32Ty(M->getContext()), 1177 liveStart + find_index(liveVariables, liveVariables[i])); 1178 1179 // only specify a debug name if we can give a useful one 1180 Value *reloc = Builder.CreateCall3( 1181 gc_relocate_decl, statepointToken, baseIdx, liveIdx, 1182 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated" 1183 : ""); 1184 // Trick CodeGen into thinking there are lots of free registers at this 1185 // fake call. 1186 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold); 1187 1188 newDefs.push_back(cast<Instruction>(reloc)); 1189 } 1190 assert(newDefs.size() == liveVariables.size() && 1191 "missing or extra redefinition at safepoint"); 1192 1193 return newDefs; 1194 } 1195 1196 static void 1197 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */ 1198 const SmallVectorImpl<llvm::Value *> &basePtrs, 1199 const SmallVectorImpl<llvm::Value *> &liveVariables, 1200 Pass *P, 1201 PartiallyConstructedSafepointRecord &result) { 1202 assert(basePtrs.size() == liveVariables.size()); 1203 assert(isStatepoint(CS) && 1204 "This method expects to be rewriting a statepoint"); 1205 1206 BasicBlock *BB = CS.getInstruction()->getParent(); 1207 assert(BB); 1208 Function *F = BB->getParent(); 1209 assert(F && "must be set"); 1210 Module *M = F->getParent(); 1211 (void)M; 1212 assert(M && "must be set"); 1213 1214 // We're not changing the function signature of the statepoint since the gc 1215 // arguments go into the var args section. 1216 Function *gc_statepoint_decl = CS.getCalledFunction(); 1217 1218 // Then go ahead and use the builder do actually do the inserts. We insert 1219 // immediately before the previous instruction under the assumption that all 1220 // arguments will be available here. We can't insert afterwards since we may 1221 // be replacing a terminator. 1222 Instruction *insertBefore = CS.getInstruction(); 1223 IRBuilder<> Builder(insertBefore); 1224 // Copy all of the arguments from the original statepoint - this includes the 1225 // target, call args, and deopt args 1226 std::vector<llvm::Value *> args; 1227 args.insert(args.end(), CS.arg_begin(), CS.arg_end()); 1228 // TODO: Clear the 'needs rewrite' flag 1229 1230 // add all the pointers to be relocated (gc arguments) 1231 // Capture the start of the live variable list for use in the gc_relocates 1232 const int live_start = args.size(); 1233 args.insert(args.end(), liveVariables.begin(), liveVariables.end()); 1234 1235 // Create the statepoint given all the arguments 1236 Instruction *token = nullptr; 1237 AttributeSet return_attributes; 1238 if (CS.isCall()) { 1239 CallInst *toReplace = cast<CallInst>(CS.getInstruction()); 1240 CallInst *call = 1241 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token"); 1242 call->setTailCall(toReplace->isTailCall()); 1243 call->setCallingConv(toReplace->getCallingConv()); 1244 1245 // Currently we will fail on parameter attributes and on certain 1246 // function attributes. 1247 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes()); 1248 // In case if we can handle this set of sttributes - set up function attrs 1249 // directly on statepoint and return attrs later for gc_result intrinsic. 1250 call->setAttributes(new_attrs.getFnAttributes()); 1251 return_attributes = new_attrs.getRetAttributes(); 1252 1253 token = call; 1254 1255 // Put the following gc_result and gc_relocate calls immediately after the 1256 // the old call (which we're about to delete) 1257 BasicBlock::iterator next(toReplace); 1258 assert(BB->end() != next && "not a terminator, must have next"); 1259 next++; 1260 Instruction *IP = &*(next); 1261 Builder.SetInsertPoint(IP); 1262 Builder.SetCurrentDebugLocation(IP->getDebugLoc()); 1263 1264 } else if (CS.isInvoke()) { 1265 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction()); 1266 1267 // Insert the new invoke into the old block. We'll remove the old one in a 1268 // moment at which point this will become the new terminator for the 1269 // original block. 1270 InvokeInst *invoke = InvokeInst::Create( 1271 gc_statepoint_decl, toReplace->getNormalDest(), 1272 toReplace->getUnwindDest(), args, "", toReplace->getParent()); 1273 invoke->setCallingConv(toReplace->getCallingConv()); 1274 1275 // Currently we will fail on parameter attributes and on certain 1276 // function attributes. 1277 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes()); 1278 // In case if we can handle this set of sttributes - set up function attrs 1279 // directly on statepoint and return attrs later for gc_result intrinsic. 1280 invoke->setAttributes(new_attrs.getFnAttributes()); 1281 return_attributes = new_attrs.getRetAttributes(); 1282 1283 token = invoke; 1284 1285 // Generate gc relocates in exceptional path 1286 BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint( 1287 toReplace->getUnwindDest(), invoke->getParent(), P); 1288 1289 Instruction *IP = &*(unwindBlock->getFirstInsertionPt()); 1290 Builder.SetInsertPoint(IP); 1291 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc()); 1292 1293 // Extract second element from landingpad return value. We will attach 1294 // exceptional gc relocates to it. 1295 const unsigned idx = 1; 1296 Instruction *exceptional_token = 1297 cast<Instruction>(Builder.CreateExtractValue( 1298 unwindBlock->getLandingPadInst(), idx, "relocate_token")); 1299 result.UnwindToken = exceptional_token; 1300 1301 // Just throw away return value. We will use the one we got for normal 1302 // block. 1303 (void)CreateGCRelocates(liveVariables, live_start, basePtrs, 1304 exceptional_token, Builder); 1305 1306 // Generate gc relocates and returns for normal block 1307 BasicBlock *normalDest = normalizeBBForInvokeSafepoint( 1308 toReplace->getNormalDest(), invoke->getParent(), P); 1309 1310 IP = &*(normalDest->getFirstInsertionPt()); 1311 Builder.SetInsertPoint(IP); 1312 1313 // gc relocates will be generated later as if it were regular call 1314 // statepoint 1315 } else { 1316 llvm_unreachable("unexpect type of CallSite"); 1317 } 1318 assert(token); 1319 1320 // Take the name of the original value call if it had one. 1321 token->takeName(CS.getInstruction()); 1322 1323 // The GCResult is already inserted, we just need to find it 1324 /* scope */ { 1325 Instruction *toReplace = CS.getInstruction(); 1326 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) && 1327 "only valid use before rewrite is gc.result"); 1328 if (toReplace->hasOneUse()) { 1329 Instruction *GCResult = cast<Instruction>(*toReplace->user_begin()); 1330 assert(isGCResult(GCResult)); 1331 } 1332 } 1333 1334 // Update the gc.result of the original statepoint (if any) to use the newly 1335 // inserted statepoint. This is safe to do here since the token can't be 1336 // considered a live reference. 1337 CS.getInstruction()->replaceAllUsesWith(token); 1338 1339 result.StatepointToken = token; 1340 1341 // Second, create a gc.relocate for every live variable 1342 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder); 1343 1344 } 1345 1346 namespace { 1347 struct name_ordering { 1348 Value *base; 1349 Value *derived; 1350 bool operator()(name_ordering const &a, name_ordering const &b) { 1351 return -1 == a.derived->getName().compare(b.derived->getName()); 1352 } 1353 }; 1354 } 1355 static void stablize_order(SmallVectorImpl<Value *> &basevec, 1356 SmallVectorImpl<Value *> &livevec) { 1357 assert(basevec.size() == livevec.size()); 1358 1359 SmallVector<name_ordering, 64> temp; 1360 for (size_t i = 0; i < basevec.size(); i++) { 1361 name_ordering v; 1362 v.base = basevec[i]; 1363 v.derived = livevec[i]; 1364 temp.push_back(v); 1365 } 1366 std::sort(temp.begin(), temp.end(), name_ordering()); 1367 for (size_t i = 0; i < basevec.size(); i++) { 1368 basevec[i] = temp[i].base; 1369 livevec[i] = temp[i].derived; 1370 } 1371 } 1372 1373 // Replace an existing gc.statepoint with a new one and a set of gc.relocates 1374 // which make the relocations happening at this safepoint explicit. 1375 // 1376 // WARNING: Does not do any fixup to adjust users of the original live 1377 // values. That's the callers responsibility. 1378 static void 1379 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P, 1380 PartiallyConstructedSafepointRecord &result) { 1381 auto liveset = result.liveset; 1382 auto PointerToBase = result.PointerToBase; 1383 1384 // Convert to vector for efficient cross referencing. 1385 SmallVector<Value *, 64> basevec, livevec; 1386 livevec.reserve(liveset.size()); 1387 basevec.reserve(liveset.size()); 1388 for (Value *L : liveset) { 1389 livevec.push_back(L); 1390 1391 assert(PointerToBase.find(L) != PointerToBase.end()); 1392 Value *base = PointerToBase[L]; 1393 basevec.push_back(base); 1394 } 1395 assert(livevec.size() == basevec.size()); 1396 1397 // To make the output IR slightly more stable (for use in diffs), ensure a 1398 // fixed order of the values in the safepoint (by sorting the value name). 1399 // The order is otherwise meaningless. 1400 stablize_order(basevec, livevec); 1401 1402 // Do the actual rewriting and delete the old statepoint 1403 makeStatepointExplicitImpl(CS, basevec, livevec, P, result); 1404 CS.getInstruction()->eraseFromParent(); 1405 } 1406 1407 // Helper function for the relocationViaAlloca. 1408 // It receives iterator to the statepoint gc relocates and emits store to the 1409 // assigned 1410 // location (via allocaMap) for the each one of them. 1411 // Add visited values into the visitedLiveValues set we will later use them 1412 // for sanity check. 1413 static void 1414 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs, 1415 DenseMap<Value *, Value *> &allocaMap, 1416 DenseSet<Value *> &visitedLiveValues) { 1417 1418 for (User *U : gcRelocs) { 1419 if (!isa<IntrinsicInst>(U)) 1420 continue; 1421 1422 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U); 1423 1424 // We only care about relocates 1425 if (relocatedValue->getIntrinsicID() != 1426 Intrinsic::experimental_gc_relocate) { 1427 continue; 1428 } 1429 1430 GCRelocateOperands relocateOperands(relocatedValue); 1431 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr()); 1432 assert(allocaMap.count(originalValue)); 1433 Value *alloca = allocaMap[originalValue]; 1434 1435 // Emit store into the related alloca 1436 StoreInst *store = new StoreInst(relocatedValue, alloca); 1437 store->insertAfter(relocatedValue); 1438 1439 #ifndef NDEBUG 1440 visitedLiveValues.insert(originalValue); 1441 #endif 1442 } 1443 } 1444 1445 /// do all the relocation update via allocas and mem2reg 1446 static void relocationViaAlloca( 1447 Function &F, DominatorTree &DT, const std::vector<Value *> &live, 1448 const std::vector<struct PartiallyConstructedSafepointRecord> &records) { 1449 #ifndef NDEBUG 1450 int initialAllocaNum = 0; 1451 1452 // record initial number of allocas 1453 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end; 1454 itr++) { 1455 if (isa<AllocaInst>(*itr)) 1456 initialAllocaNum++; 1457 } 1458 #endif 1459 1460 // TODO-PERF: change data structures, reserve 1461 DenseMap<Value *, Value *> allocaMap; 1462 SmallVector<AllocaInst *, 200> PromotableAllocas; 1463 PromotableAllocas.reserve(live.size()); 1464 1465 // emit alloca for each live gc pointer 1466 for (unsigned i = 0; i < live.size(); i++) { 1467 Value *liveValue = live[i]; 1468 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "", 1469 F.getEntryBlock().getFirstNonPHI()); 1470 allocaMap[liveValue] = alloca; 1471 PromotableAllocas.push_back(alloca); 1472 } 1473 1474 // The next two loops are part of the same conceptual operation. We need to 1475 // insert a store to the alloca after the original def and at each 1476 // redefinition. We need to insert a load before each use. These are split 1477 // into distinct loops for performance reasons. 1478 1479 // update gc pointer after each statepoint 1480 // either store a relocated value or null (if no relocated value found for 1481 // this gc pointer and it is not a gc_result) 1482 // this must happen before we update the statepoint with load of alloca 1483 // otherwise we lose the link between statepoint and old def 1484 for (size_t i = 0; i < records.size(); i++) { 1485 const struct PartiallyConstructedSafepointRecord &info = records[i]; 1486 Value *Statepoint = info.StatepointToken; 1487 1488 // This will be used for consistency check 1489 DenseSet<Value *> visitedLiveValues; 1490 1491 // Insert stores for normal statepoint gc relocates 1492 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues); 1493 1494 // In case if it was invoke statepoint 1495 // we will insert stores for exceptional path gc relocates. 1496 if (isa<InvokeInst>(Statepoint)) { 1497 insertRelocationStores(info.UnwindToken->users(), 1498 allocaMap, visitedLiveValues); 1499 } 1500 1501 #ifndef NDEBUG 1502 // As a debuging aid, pretend that an unrelocated pointer becomes null at 1503 // the gc.statepoint. This will turn some subtle GC problems into slightly 1504 // easier to debug SEGVs 1505 SmallVector<AllocaInst *, 64> ToClobber; 1506 for (auto Pair : allocaMap) { 1507 Value *Def = Pair.first; 1508 AllocaInst *Alloca = cast<AllocaInst>(Pair.second); 1509 1510 // This value was relocated 1511 if (visitedLiveValues.count(Def)) { 1512 continue; 1513 } 1514 ToClobber.push_back(Alloca); 1515 } 1516 1517 auto InsertClobbersAt = [&](Instruction *IP) { 1518 for (auto *AI : ToClobber) { 1519 auto AIType = cast<PointerType>(AI->getType()); 1520 auto PT = cast<PointerType>(AIType->getElementType()); 1521 Constant *CPN = ConstantPointerNull::get(PT); 1522 StoreInst *store = new StoreInst(CPN, AI); 1523 store->insertBefore(IP); 1524 } 1525 }; 1526 1527 // Insert the clobbering stores. These may get intermixed with the 1528 // gc.results and gc.relocates, but that's fine. 1529 if (auto II = dyn_cast<InvokeInst>(Statepoint)) { 1530 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt()); 1531 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt()); 1532 } else if (auto CI = dyn_cast<CallInst>(Statepoint)) { 1533 BasicBlock::iterator Next(CI); 1534 Next++; 1535 InsertClobbersAt(Next); 1536 } else 1537 llvm_unreachable("illegal statepoint instruction type?"); 1538 #endif 1539 } 1540 // update use with load allocas and add store for gc_relocated 1541 for (auto Pair : allocaMap) { 1542 Value *def = Pair.first; 1543 Value *alloca = Pair.second; 1544 1545 // we pre-record the uses of allocas so that we dont have to worry about 1546 // later update 1547 // that change the user information. 1548 SmallVector<Instruction *, 20> uses; 1549 // PERF: trade a linear scan for repeated reallocation 1550 uses.reserve(std::distance(def->user_begin(), def->user_end())); 1551 for (User *U : def->users()) { 1552 if (!isa<ConstantExpr>(U)) { 1553 // If the def has a ConstantExpr use, then the def is either a 1554 // ConstantExpr use itself or null. In either case 1555 // (recursively in the first, directly in the second), the oop 1556 // it is ultimately dependent on is null and this particular 1557 // use does not need to be fixed up. 1558 uses.push_back(cast<Instruction>(U)); 1559 } 1560 } 1561 1562 std::sort(uses.begin(), uses.end()); 1563 auto last = std::unique(uses.begin(), uses.end()); 1564 uses.erase(last, uses.end()); 1565 1566 for (Instruction *use : uses) { 1567 if (isa<PHINode>(use)) { 1568 PHINode *phi = cast<PHINode>(use); 1569 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) { 1570 if (def == phi->getIncomingValue(i)) { 1571 LoadInst *load = new LoadInst( 1572 alloca, "", phi->getIncomingBlock(i)->getTerminator()); 1573 phi->setIncomingValue(i, load); 1574 } 1575 } 1576 } else { 1577 LoadInst *load = new LoadInst(alloca, "", use); 1578 use->replaceUsesOfWith(def, load); 1579 } 1580 } 1581 1582 // emit store for the initial gc value 1583 // store must be inserted after load, otherwise store will be in alloca's 1584 // use list and an extra load will be inserted before it 1585 StoreInst *store = new StoreInst(def, alloca); 1586 if (isa<Instruction>(def)) { 1587 store->insertAfter(cast<Instruction>(def)); 1588 } else { 1589 assert((isa<Argument>(def) || isa<GlobalVariable>(def) || 1590 (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) && 1591 "Must be argument or global"); 1592 store->insertAfter(cast<Instruction>(alloca)); 1593 } 1594 } 1595 1596 assert(PromotableAllocas.size() == live.size() && 1597 "we must have the same allocas with lives"); 1598 if (!PromotableAllocas.empty()) { 1599 // apply mem2reg to promote alloca to SSA 1600 PromoteMemToReg(PromotableAllocas, DT); 1601 } 1602 1603 #ifndef NDEBUG 1604 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end; 1605 itr++) { 1606 if (isa<AllocaInst>(*itr)) 1607 initialAllocaNum--; 1608 } 1609 assert(initialAllocaNum == 0 && "We must not introduce any extra allocas"); 1610 #endif 1611 } 1612 1613 /// Implement a unique function which doesn't require we sort the input 1614 /// vector. Doing so has the effect of changing the output of a couple of 1615 /// tests in ways which make them less useful in testing fused safepoints. 1616 template <typename T> static void unique_unsorted(std::vector<T> &vec) { 1617 DenseSet<T> seen; 1618 std::vector<T> tmp; 1619 vec.reserve(vec.size()); 1620 std::swap(tmp, vec); 1621 for (auto V : tmp) { 1622 if (seen.insert(V).second) { 1623 vec.push_back(V); 1624 } 1625 } 1626 } 1627 1628 static Function *getUseHolder(Module &M) { 1629 FunctionType *ftype = 1630 FunctionType::get(Type::getVoidTy(M.getContext()), true); 1631 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype)); 1632 return Func; 1633 } 1634 1635 /// Insert holders so that each Value is obviously live through the entire 1636 /// liftetime of the call. 1637 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values, 1638 std::vector<CallInst *> &holders) { 1639 Module *M = CS.getInstruction()->getParent()->getParent()->getParent(); 1640 Function *Func = getUseHolder(*M); 1641 if (CS.isCall()) { 1642 // For call safepoints insert dummy calls right after safepoint 1643 BasicBlock::iterator next(CS.getInstruction()); 1644 next++; 1645 CallInst *base_holder = CallInst::Create(Func, Values, "", next); 1646 holders.push_back(base_holder); 1647 } else if (CS.isInvoke()) { 1648 // For invoke safepooints insert dummy calls both in normal and 1649 // exceptional destination blocks 1650 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction()); 1651 CallInst *normal_holder = CallInst::Create( 1652 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt()); 1653 CallInst *unwind_holder = CallInst::Create( 1654 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt()); 1655 holders.push_back(normal_holder); 1656 holders.push_back(unwind_holder); 1657 } else 1658 llvm_unreachable("unsupported call type"); 1659 } 1660 1661 static void findLiveReferences( 1662 Function &F, DominatorTree &DT, Pass *P, std::vector<CallSite> &toUpdate, 1663 std::vector<struct PartiallyConstructedSafepointRecord> &records) { 1664 for (size_t i = 0; i < records.size(); i++) { 1665 struct PartiallyConstructedSafepointRecord &info = records[i]; 1666 CallSite &CS = toUpdate[i]; 1667 analyzeParsePointLiveness(DT, CS, info); 1668 } 1669 } 1670 1671 static void addBasesAsLiveValues(std::set<Value *> &liveset, 1672 DenseMap<Value *, Value *> &PointerToBase) { 1673 // Identify any base pointers which are used in this safepoint, but not 1674 // themselves relocated. We need to relocate them so that later inserted 1675 // safepoints can get the properly relocated base register. 1676 DenseSet<Value *> missing; 1677 for (Value *L : liveset) { 1678 assert(PointerToBase.find(L) != PointerToBase.end()); 1679 Value *base = PointerToBase[L]; 1680 assert(base); 1681 if (liveset.find(base) == liveset.end()) { 1682 assert(PointerToBase.find(base) == PointerToBase.end()); 1683 // uniqued by set insert 1684 missing.insert(base); 1685 } 1686 } 1687 1688 // Note that we want these at the end of the list, otherwise 1689 // register placement gets screwed up once we lower to STATEPOINT 1690 // instructions. This is an utter hack, but there doesn't seem to be a 1691 // better one. 1692 for (Value *base : missing) { 1693 assert(base); 1694 liveset.insert(base); 1695 PointerToBase[base] = base; 1696 } 1697 assert(liveset.size() == PointerToBase.size()); 1698 } 1699 1700 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P, 1701 std::vector<CallSite> &toUpdate) { 1702 #ifndef NDEBUG 1703 // sanity check the input 1704 std::set<CallSite> uniqued; 1705 uniqued.insert(toUpdate.begin(), toUpdate.end()); 1706 assert(uniqued.size() == toUpdate.size() && "no duplicates please!"); 1707 1708 for (size_t i = 0; i < toUpdate.size(); i++) { 1709 CallSite &CS = toUpdate[i]; 1710 assert(CS.getInstruction()->getParent()->getParent() == &F); 1711 assert(isStatepoint(CS) && "expected to already be a deopt statepoint"); 1712 } 1713 #endif 1714 1715 // A list of dummy calls added to the IR to keep various values obviously 1716 // live in the IR. We'll remove all of these when done. 1717 std::vector<CallInst *> holders; 1718 1719 // Insert a dummy call with all of the arguments to the vm_state we'll need 1720 // for the actual safepoint insertion. This ensures reference arguments in 1721 // the deopt argument list are considered live through the safepoint (and 1722 // thus makes sure they get relocated.) 1723 for (size_t i = 0; i < toUpdate.size(); i++) { 1724 CallSite &CS = toUpdate[i]; 1725 Statepoint StatepointCS(CS); 1726 1727 SmallVector<Value *, 64> DeoptValues; 1728 for (Use &U : StatepointCS.vm_state_args()) { 1729 Value *Arg = cast<Value>(&U); 1730 if (isGCPointerType(Arg->getType())) 1731 DeoptValues.push_back(Arg); 1732 } 1733 insertUseHolderAfter(CS, DeoptValues, holders); 1734 } 1735 1736 std::vector<struct PartiallyConstructedSafepointRecord> records; 1737 records.reserve(toUpdate.size()); 1738 for (size_t i = 0; i < toUpdate.size(); i++) { 1739 struct PartiallyConstructedSafepointRecord info; 1740 records.push_back(info); 1741 } 1742 assert(records.size() == toUpdate.size()); 1743 1744 // A) Identify all gc pointers which are staticly live at the given call 1745 // site. 1746 findLiveReferences(F, DT, P, toUpdate, records); 1747 1748 // B) Find the base pointers for each live pointer 1749 /* scope for caching */ { 1750 // Cache the 'defining value' relation used in the computation and 1751 // insertion of base phis and selects. This ensures that we don't insert 1752 // large numbers of duplicate base_phis. 1753 DefiningValueMapTy DVCache; 1754 1755 for (size_t i = 0; i < records.size(); i++) { 1756 struct PartiallyConstructedSafepointRecord &info = records[i]; 1757 CallSite &CS = toUpdate[i]; 1758 findBasePointers(DT, DVCache, CS, info); 1759 } 1760 } // end of cache scope 1761 1762 // The base phi insertion logic (for any safepoint) may have inserted new 1763 // instructions which are now live at some safepoint. The simplest such 1764 // example is: 1765 // loop: 1766 // phi a <-- will be a new base_phi here 1767 // safepoint 1 <-- that needs to be live here 1768 // gep a + 1 1769 // safepoint 2 1770 // br loop 1771 std::set<llvm::Value *> allInsertedDefs; 1772 for (size_t i = 0; i < records.size(); i++) { 1773 struct PartiallyConstructedSafepointRecord &info = records[i]; 1774 allInsertedDefs.insert(info.NewInsertedDefs.begin(), 1775 info.NewInsertedDefs.end()); 1776 } 1777 1778 // We insert some dummy calls after each safepoint to definitely hold live 1779 // the base pointers which were identified for that safepoint. We'll then 1780 // ask liveness for _every_ base inserted to see what is now live. Then we 1781 // remove the dummy calls. 1782 holders.reserve(holders.size() + records.size()); 1783 for (size_t i = 0; i < records.size(); i++) { 1784 struct PartiallyConstructedSafepointRecord &info = records[i]; 1785 CallSite &CS = toUpdate[i]; 1786 1787 SmallVector<Value *, 128> Bases; 1788 for (auto Pair : info.PointerToBase) { 1789 Bases.push_back(Pair.second); 1790 } 1791 insertUseHolderAfter(CS, Bases, holders); 1792 } 1793 1794 // Add the bases explicitly to the live vector set. This may result in a few 1795 // extra relocations, but the base has to be available whenever a pointer 1796 // derived from it is used. Thus, we need it to be part of the statepoint's 1797 // gc arguments list. TODO: Introduce an explicit notion (in the following 1798 // code) of the GC argument list as seperate from the live Values at a 1799 // given statepoint. 1800 for (size_t i = 0; i < records.size(); i++) { 1801 struct PartiallyConstructedSafepointRecord &info = records[i]; 1802 addBasesAsLiveValues(info.liveset, info.PointerToBase); 1803 } 1804 1805 // If we inserted any new values, we need to adjust our notion of what is 1806 // live at a particular safepoint. 1807 if (!allInsertedDefs.empty()) { 1808 fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records); 1809 } 1810 if (PrintBasePointers) { 1811 for (size_t i = 0; i < records.size(); i++) { 1812 struct PartiallyConstructedSafepointRecord &info = records[i]; 1813 errs() << "Base Pairs: (w/Relocation)\n"; 1814 for (auto Pair : info.PointerToBase) { 1815 errs() << " derived %" << Pair.first->getName() << " base %" 1816 << Pair.second->getName() << "\n"; 1817 } 1818 } 1819 } 1820 for (size_t i = 0; i < holders.size(); i++) { 1821 holders[i]->eraseFromParent(); 1822 holders[i] = nullptr; 1823 } 1824 holders.clear(); 1825 1826 // Now run through and replace the existing statepoints with new ones with 1827 // the live variables listed. We do not yet update uses of the values being 1828 // relocated. We have references to live variables that need to 1829 // survive to the last iteration of this loop. (By construction, the 1830 // previous statepoint can not be a live variable, thus we can and remove 1831 // the old statepoint calls as we go.) 1832 for (size_t i = 0; i < records.size(); i++) { 1833 struct PartiallyConstructedSafepointRecord &info = records[i]; 1834 CallSite &CS = toUpdate[i]; 1835 makeStatepointExplicit(DT, CS, P, info); 1836 } 1837 toUpdate.clear(); // prevent accident use of invalid CallSites 1838 1839 // In case if we inserted relocates in a different basic block than the 1840 // original safepoint (this can happen for invokes). We need to be sure that 1841 // original values were not used in any of the phi nodes at the 1842 // beginning of basic block containing them. Because we know that all such 1843 // blocks will have single predecessor we can safely assume that all phi 1844 // nodes have single entry (because of normalizeBBForInvokeSafepoint). 1845 // Just remove them all here. 1846 for (size_t i = 0; i < records.size(); i++) { 1847 Instruction *I = records[i].StatepointToken; 1848 1849 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) { 1850 FoldSingleEntryPHINodes(invoke->getNormalDest()); 1851 assert(!isa<PHINode>(invoke->getNormalDest()->begin())); 1852 1853 FoldSingleEntryPHINodes(invoke->getUnwindDest()); 1854 assert(!isa<PHINode>(invoke->getUnwindDest()->begin())); 1855 } 1856 } 1857 1858 // Do all the fixups of the original live variables to their relocated selves 1859 std::vector<Value *> live; 1860 for (size_t i = 0; i < records.size(); i++) { 1861 struct PartiallyConstructedSafepointRecord &info = records[i]; 1862 // We can't simply save the live set from the original insertion. One of 1863 // the live values might be the result of a call which needs a safepoint. 1864 // That Value* no longer exists and we need to use the new gc_result. 1865 // Thankfully, the liveset is embedded in the statepoint (and updated), so 1866 // we just grab that. 1867 Statepoint statepoint(info.StatepointToken); 1868 live.insert(live.end(), statepoint.gc_args_begin(), 1869 statepoint.gc_args_end()); 1870 } 1871 unique_unsorted(live); 1872 1873 #ifndef NDEBUG 1874 // sanity check 1875 for (auto ptr : live) { 1876 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type"); 1877 } 1878 #endif 1879 1880 relocationViaAlloca(F, DT, live, records); 1881 return !records.empty(); 1882 } 1883 1884 /// Returns true if this function should be rewritten by this pass. The main 1885 /// point of this function is as an extension point for custom logic. 1886 static bool shouldRewriteStatepointsIn(Function &F) { 1887 // TODO: This should check the GCStrategy 1888 if (F.hasGC()) { 1889 const std::string StatepointExampleName("statepoint-example"); 1890 return StatepointExampleName == F.getGC(); 1891 } else 1892 return false; 1893 } 1894 1895 bool RewriteStatepointsForGC::runOnFunction(Function &F) { 1896 // Nothing to do for declarations. 1897 if (F.isDeclaration() || F.empty()) 1898 return false; 1899 1900 // Policy choice says not to rewrite - the most common reason is that we're 1901 // compiling code without a GCStrategy. 1902 if (!shouldRewriteStatepointsIn(F)) 1903 return false; 1904 1905 // Gather all the statepoints which need rewritten. 1906 std::vector<CallSite> ParsePointNeeded; 1907 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end; 1908 itr++) { 1909 // TODO: only the ones with the flag set! 1910 if (isStatepoint(*itr)) 1911 ParsePointNeeded.push_back(CallSite(&*itr)); 1912 } 1913 1914 // Return early if no work to do. 1915 if (ParsePointNeeded.empty()) 1916 return false; 1917 1918 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1919 return insertParsePoints(F, DT, this, ParsePointNeeded); 1920 } 1921