1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===// 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 // This file promotes memory references to be register references. It promotes 11 // alloca instructions which only have loads and stores as uses. An alloca is 12 // transformed by using iterated dominator frontiers to place PHI nodes, then 13 // traversing the function in depth-first order to rewrite loads and stores as 14 // appropriate. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasSetTracker.h" 25 #include "llvm/Analysis/AssumptionCache.h" 26 #include "llvm/Analysis/InstructionSimplify.h" 27 #include "llvm/Analysis/IteratedDominanceFrontier.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DIBuilder.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Metadata.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/Transforms/Utils/Local.h" 41 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 42 #include <algorithm> 43 using namespace llvm; 44 45 #define DEBUG_TYPE "mem2reg" 46 47 STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block"); 48 STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store"); 49 STATISTIC(NumDeadAlloca, "Number of dead alloca's removed"); 50 STATISTIC(NumPHIInsert, "Number of PHI nodes inserted"); 51 52 bool llvm::isAllocaPromotable(const AllocaInst *AI) { 53 // FIXME: If the memory unit is of pointer or integer type, we can permit 54 // assignments to subsections of the memory unit. 55 unsigned AS = AI->getType()->getAddressSpace(); 56 57 // Only allow direct and non-volatile loads and stores... 58 for (const User *U : AI->users()) { 59 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) { 60 // Note that atomic loads can be transformed; atomic semantics do 61 // not have any meaning for a local alloca. 62 if (LI->isVolatile()) 63 return false; 64 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 65 if (SI->getOperand(0) == AI) 66 return false; // Don't allow a store OF the AI, only INTO the AI. 67 // Note that atomic stores can be transformed; atomic semantics do 68 // not have any meaning for a local alloca. 69 if (SI->isVolatile()) 70 return false; 71 } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) { 72 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 73 II->getIntrinsicID() != Intrinsic::lifetime_end) 74 return false; 75 } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) { 76 if (BCI->getType() != Type::getInt8PtrTy(U->getContext(), AS)) 77 return false; 78 if (!onlyUsedByLifetimeMarkers(BCI)) 79 return false; 80 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 81 if (GEPI->getType() != Type::getInt8PtrTy(U->getContext(), AS)) 82 return false; 83 if (!GEPI->hasAllZeroIndices()) 84 return false; 85 if (!onlyUsedByLifetimeMarkers(GEPI)) 86 return false; 87 } else { 88 return false; 89 } 90 } 91 92 return true; 93 } 94 95 namespace { 96 97 struct AllocaInfo { 98 SmallVector<BasicBlock *, 32> DefiningBlocks; 99 SmallVector<BasicBlock *, 32> UsingBlocks; 100 101 StoreInst *OnlyStore; 102 BasicBlock *OnlyBlock; 103 bool OnlyUsedInOneBlock; 104 105 Value *AllocaPointerVal; 106 DbgDeclareInst *DbgDeclare; 107 108 void clear() { 109 DefiningBlocks.clear(); 110 UsingBlocks.clear(); 111 OnlyStore = nullptr; 112 OnlyBlock = nullptr; 113 OnlyUsedInOneBlock = true; 114 AllocaPointerVal = nullptr; 115 DbgDeclare = nullptr; 116 } 117 118 /// Scan the uses of the specified alloca, filling in the AllocaInfo used 119 /// by the rest of the pass to reason about the uses of this alloca. 120 void AnalyzeAlloca(AllocaInst *AI) { 121 clear(); 122 123 // As we scan the uses of the alloca instruction, keep track of stores, 124 // and decide whether all of the loads and stores to the alloca are within 125 // the same basic block. 126 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) { 127 Instruction *User = cast<Instruction>(*UI++); 128 129 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 130 // Remember the basic blocks which define new values for the alloca 131 DefiningBlocks.push_back(SI->getParent()); 132 AllocaPointerVal = SI->getOperand(0); 133 OnlyStore = SI; 134 } else { 135 LoadInst *LI = cast<LoadInst>(User); 136 // Otherwise it must be a load instruction, keep track of variable 137 // reads. 138 UsingBlocks.push_back(LI->getParent()); 139 AllocaPointerVal = LI; 140 } 141 142 if (OnlyUsedInOneBlock) { 143 if (!OnlyBlock) 144 OnlyBlock = User->getParent(); 145 else if (OnlyBlock != User->getParent()) 146 OnlyUsedInOneBlock = false; 147 } 148 } 149 150 DbgDeclare = FindAllocaDbgDeclare(AI); 151 } 152 }; 153 154 // Data package used by RenamePass() 155 class RenamePassData { 156 public: 157 typedef std::vector<Value *> ValVector; 158 159 RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V) 160 : BB(B), Pred(P), Values(std::move(V)) {} 161 BasicBlock *BB; 162 BasicBlock *Pred; 163 ValVector Values; 164 }; 165 166 /// \brief This assigns and keeps a per-bb relative ordering of load/store 167 /// instructions in the block that directly load or store an alloca. 168 /// 169 /// This functionality is important because it avoids scanning large basic 170 /// blocks multiple times when promoting many allocas in the same block. 171 class LargeBlockInfo { 172 /// \brief For each instruction that we track, keep the index of the 173 /// instruction. 174 /// 175 /// The index starts out as the number of the instruction from the start of 176 /// the block. 177 DenseMap<const Instruction *, unsigned> InstNumbers; 178 179 public: 180 181 /// This code only looks at accesses to allocas. 182 static bool isInterestingInstruction(const Instruction *I) { 183 return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) || 184 (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1))); 185 } 186 187 /// Get or calculate the index of the specified instruction. 188 unsigned getInstructionIndex(const Instruction *I) { 189 assert(isInterestingInstruction(I) && 190 "Not a load/store to/from an alloca?"); 191 192 // If we already have this instruction number, return it. 193 DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I); 194 if (It != InstNumbers.end()) 195 return It->second; 196 197 // Scan the whole block to get the instruction. This accumulates 198 // information for every interesting instruction in the block, in order to 199 // avoid gratuitus rescans. 200 const BasicBlock *BB = I->getParent(); 201 unsigned InstNo = 0; 202 for (const Instruction &BBI : *BB) 203 if (isInterestingInstruction(&BBI)) 204 InstNumbers[&BBI] = InstNo++; 205 It = InstNumbers.find(I); 206 207 assert(It != InstNumbers.end() && "Didn't insert instruction?"); 208 return It->second; 209 } 210 211 void deleteValue(const Instruction *I) { InstNumbers.erase(I); } 212 213 void clear() { InstNumbers.clear(); } 214 }; 215 216 struct PromoteMem2Reg { 217 /// The alloca instructions being promoted. 218 std::vector<AllocaInst *> Allocas; 219 DominatorTree &DT; 220 DIBuilder DIB; 221 /// A cache of @llvm.assume intrinsics used by SimplifyInstruction. 222 AssumptionCache *AC; 223 224 const SimplifyQuery SQ; 225 /// Reverse mapping of Allocas. 226 DenseMap<AllocaInst *, unsigned> AllocaLookup; 227 228 /// \brief The PhiNodes we're adding. 229 /// 230 /// That map is used to simplify some Phi nodes as we iterate over it, so 231 /// it should have deterministic iterators. We could use a MapVector, but 232 /// since we already maintain a map from BasicBlock* to a stable numbering 233 /// (BBNumbers), the DenseMap is more efficient (also supports removal). 234 DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes; 235 236 /// For each PHI node, keep track of which entry in Allocas it corresponds 237 /// to. 238 DenseMap<PHINode *, unsigned> PhiToAllocaMap; 239 240 /// If we are updating an AliasSetTracker, then for each alloca that is of 241 /// pointer type, we keep track of what to copyValue to the inserted PHI 242 /// nodes here. 243 std::vector<Value *> PointerAllocaValues; 244 245 /// For each alloca, we keep track of the dbg.declare intrinsic that 246 /// describes it, if any, so that we can convert it to a dbg.value 247 /// intrinsic if the alloca gets promoted. 248 SmallVector<DbgDeclareInst *, 8> AllocaDbgDeclares; 249 250 /// The set of basic blocks the renamer has already visited. 251 /// 252 SmallPtrSet<BasicBlock *, 16> Visited; 253 254 /// Contains a stable numbering of basic blocks to avoid non-determinstic 255 /// behavior. 256 DenseMap<BasicBlock *, unsigned> BBNumbers; 257 258 /// Lazily compute the number of predecessors a block has. 259 DenseMap<const BasicBlock *, unsigned> BBNumPreds; 260 261 public: 262 PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT, 263 AssumptionCache *AC) 264 : Allocas(Allocas.begin(), Allocas.end()), DT(DT), 265 DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false), 266 AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(), 267 nullptr, &DT, AC) {} 268 269 void run(); 270 271 private: 272 void RemoveFromAllocasList(unsigned &AllocaIdx) { 273 Allocas[AllocaIdx] = Allocas.back(); 274 Allocas.pop_back(); 275 --AllocaIdx; 276 } 277 278 unsigned getNumPreds(const BasicBlock *BB) { 279 unsigned &NP = BBNumPreds[BB]; 280 if (NP == 0) 281 NP = std::distance(pred_begin(BB), pred_end(BB)) + 1; 282 return NP - 1; 283 } 284 285 void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info, 286 const SmallPtrSetImpl<BasicBlock *> &DefBlocks, 287 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks); 288 void RenamePass(BasicBlock *BB, BasicBlock *Pred, 289 RenamePassData::ValVector &IncVals, 290 std::vector<RenamePassData> &Worklist); 291 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version); 292 }; 293 294 } // end of anonymous namespace 295 296 /// Given a LoadInst LI this adds assume(LI != null) after it. 297 static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) { 298 Function *AssumeIntrinsic = 299 Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume); 300 ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI, 301 Constant::getNullValue(LI->getType())); 302 LoadNotNull->insertAfter(LI); 303 CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull}); 304 CI->insertAfter(LoadNotNull); 305 AC->registerAssumption(CI); 306 } 307 308 static void removeLifetimeIntrinsicUsers(AllocaInst *AI) { 309 // Knowing that this alloca is promotable, we know that it's safe to kill all 310 // instructions except for load and store. 311 312 for (auto UI = AI->user_begin(), UE = AI->user_end(); UI != UE;) { 313 Instruction *I = cast<Instruction>(*UI); 314 ++UI; 315 if (isa<LoadInst>(I) || isa<StoreInst>(I)) 316 continue; 317 318 if (!I->getType()->isVoidTy()) { 319 // The only users of this bitcast/GEP instruction are lifetime intrinsics. 320 // Follow the use/def chain to erase them now instead of leaving it for 321 // dead code elimination later. 322 for (auto UUI = I->user_begin(), UUE = I->user_end(); UUI != UUE;) { 323 Instruction *Inst = cast<Instruction>(*UUI); 324 ++UUI; 325 Inst->eraseFromParent(); 326 } 327 } 328 I->eraseFromParent(); 329 } 330 } 331 332 /// \brief Rewrite as many loads as possible given a single store. 333 /// 334 /// When there is only a single store, we can use the domtree to trivially 335 /// replace all of the dominated loads with the stored value. Do so, and return 336 /// true if this has successfully promoted the alloca entirely. If this returns 337 /// false there were some loads which were not dominated by the single store 338 /// and thus must be phi-ed with undef. We fall back to the standard alloca 339 /// promotion algorithm in that case. 340 static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info, 341 LargeBlockInfo &LBI, DominatorTree &DT, 342 AssumptionCache *AC) { 343 StoreInst *OnlyStore = Info.OnlyStore; 344 bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0)); 345 BasicBlock *StoreBB = OnlyStore->getParent(); 346 int StoreIndex = -1; 347 348 // Clear out UsingBlocks. We will reconstruct it here if needed. 349 Info.UsingBlocks.clear(); 350 351 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) { 352 Instruction *UserInst = cast<Instruction>(*UI++); 353 if (!isa<LoadInst>(UserInst)) { 354 assert(UserInst == OnlyStore && "Should only have load/stores"); 355 continue; 356 } 357 LoadInst *LI = cast<LoadInst>(UserInst); 358 359 // Okay, if we have a load from the alloca, we want to replace it with the 360 // only value stored to the alloca. We can do this if the value is 361 // dominated by the store. If not, we use the rest of the mem2reg machinery 362 // to insert the phi nodes as needed. 363 if (!StoringGlobalVal) { // Non-instructions are always dominated. 364 if (LI->getParent() == StoreBB) { 365 // If we have a use that is in the same block as the store, compare the 366 // indices of the two instructions to see which one came first. If the 367 // load came before the store, we can't handle it. 368 if (StoreIndex == -1) 369 StoreIndex = LBI.getInstructionIndex(OnlyStore); 370 371 if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) { 372 // Can't handle this load, bail out. 373 Info.UsingBlocks.push_back(StoreBB); 374 continue; 375 } 376 377 } else if (LI->getParent() != StoreBB && 378 !DT.dominates(StoreBB, LI->getParent())) { 379 // If the load and store are in different blocks, use BB dominance to 380 // check their relationships. If the store doesn't dom the use, bail 381 // out. 382 Info.UsingBlocks.push_back(LI->getParent()); 383 continue; 384 } 385 } 386 387 // Otherwise, we *can* safely rewrite this load. 388 Value *ReplVal = OnlyStore->getOperand(0); 389 // If the replacement value is the load, this must occur in unreachable 390 // code. 391 if (ReplVal == LI) 392 ReplVal = UndefValue::get(LI->getType()); 393 394 // If the load was marked as nonnull we don't want to lose 395 // that information when we erase this Load. So we preserve 396 // it with an assume. 397 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) && 398 !llvm::isKnownNonNullAt(ReplVal, LI, &DT)) 399 addAssumeNonNull(AC, LI); 400 401 LI->replaceAllUsesWith(ReplVal); 402 LI->eraseFromParent(); 403 LBI.deleteValue(LI); 404 } 405 406 // Finally, after the scan, check to see if the store is all that is left. 407 if (!Info.UsingBlocks.empty()) 408 return false; // If not, we'll have to fall back for the remainder. 409 410 // Record debuginfo for the store and remove the declaration's 411 // debuginfo. 412 if (DbgDeclareInst *DDI = Info.DbgDeclare) { 413 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false); 414 ConvertDebugDeclareToDebugValue(DDI, Info.OnlyStore, DIB); 415 DDI->eraseFromParent(); 416 LBI.deleteValue(DDI); 417 } 418 // Remove the (now dead) store and alloca. 419 Info.OnlyStore->eraseFromParent(); 420 LBI.deleteValue(Info.OnlyStore); 421 422 AI->eraseFromParent(); 423 LBI.deleteValue(AI); 424 return true; 425 } 426 427 /// Many allocas are only used within a single basic block. If this is the 428 /// case, avoid traversing the CFG and inserting a lot of potentially useless 429 /// PHI nodes by just performing a single linear pass over the basic block 430 /// using the Alloca. 431 /// 432 /// If we cannot promote this alloca (because it is read before it is written), 433 /// return false. This is necessary in cases where, due to control flow, the 434 /// alloca is undefined only on some control flow paths. e.g. code like 435 /// this is correct in LLVM IR: 436 /// // A is an alloca with no stores so far 437 /// for (...) { 438 /// int t = *A; 439 /// if (!first_iteration) 440 /// use(t); 441 /// *A = 42; 442 /// } 443 static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info, 444 LargeBlockInfo &LBI, 445 DominatorTree &DT, 446 AssumptionCache *AC) { 447 // The trickiest case to handle is when we have large blocks. Because of this, 448 // this code is optimized assuming that large blocks happen. This does not 449 // significantly pessimize the small block case. This uses LargeBlockInfo to 450 // make it efficient to get the index of various operations in the block. 451 452 // Walk the use-def list of the alloca, getting the locations of all stores. 453 typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy; 454 StoresByIndexTy StoresByIndex; 455 456 for (User *U : AI->users()) 457 if (StoreInst *SI = dyn_cast<StoreInst>(U)) 458 StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI)); 459 460 // Sort the stores by their index, making it efficient to do a lookup with a 461 // binary search. 462 std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first()); 463 464 // Walk all of the loads from this alloca, replacing them with the nearest 465 // store above them, if any. 466 for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) { 467 LoadInst *LI = dyn_cast<LoadInst>(*UI++); 468 if (!LI) 469 continue; 470 471 unsigned LoadIdx = LBI.getInstructionIndex(LI); 472 473 // Find the nearest store that has a lower index than this load. 474 StoresByIndexTy::iterator I = 475 std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(), 476 std::make_pair(LoadIdx, 477 static_cast<StoreInst *>(nullptr)), 478 less_first()); 479 if (I == StoresByIndex.begin()) { 480 if (StoresByIndex.empty()) 481 // If there are no stores, the load takes the undef value. 482 LI->replaceAllUsesWith(UndefValue::get(LI->getType())); 483 else 484 // There is no store before this load, bail out (load may be affected 485 // by the following stores - see main comment). 486 return false; 487 } else { 488 // Otherwise, there was a store before this load, the load takes its value. 489 // Note, if the load was marked as nonnull we don't want to lose that 490 // information when we erase it. So we preserve it with an assume. 491 Value *ReplVal = std::prev(I)->second->getOperand(0); 492 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) && 493 !llvm::isKnownNonNullAt(ReplVal, LI, &DT)) 494 addAssumeNonNull(AC, LI); 495 496 LI->replaceAllUsesWith(ReplVal); 497 } 498 499 LI->eraseFromParent(); 500 LBI.deleteValue(LI); 501 } 502 503 // Remove the (now dead) stores and alloca. 504 while (!AI->use_empty()) { 505 StoreInst *SI = cast<StoreInst>(AI->user_back()); 506 // Record debuginfo for the store before removing it. 507 if (DbgDeclareInst *DDI = Info.DbgDeclare) { 508 DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false); 509 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 510 } 511 SI->eraseFromParent(); 512 LBI.deleteValue(SI); 513 } 514 515 AI->eraseFromParent(); 516 LBI.deleteValue(AI); 517 518 // The alloca's debuginfo can be removed as well. 519 if (DbgDeclareInst *DDI = Info.DbgDeclare) { 520 DDI->eraseFromParent(); 521 LBI.deleteValue(DDI); 522 } 523 524 ++NumLocalPromoted; 525 return true; 526 } 527 528 void PromoteMem2Reg::run() { 529 Function &F = *DT.getRoot()->getParent(); 530 531 AllocaDbgDeclares.resize(Allocas.size()); 532 533 AllocaInfo Info; 534 LargeBlockInfo LBI; 535 ForwardIDFCalculator IDF(DT); 536 537 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) { 538 AllocaInst *AI = Allocas[AllocaNum]; 539 540 assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!"); 541 assert(AI->getParent()->getParent() == &F && 542 "All allocas should be in the same function, which is same as DF!"); 543 544 removeLifetimeIntrinsicUsers(AI); 545 546 if (AI->use_empty()) { 547 // If there are no uses of the alloca, just delete it now. 548 AI->eraseFromParent(); 549 550 // Remove the alloca from the Allocas list, since it has been processed 551 RemoveFromAllocasList(AllocaNum); 552 ++NumDeadAlloca; 553 continue; 554 } 555 556 // Calculate the set of read and write-locations for each alloca. This is 557 // analogous to finding the 'uses' and 'definitions' of each variable. 558 Info.AnalyzeAlloca(AI); 559 560 // If there is only a single store to this value, replace any loads of 561 // it that are directly dominated by the definition with the value stored. 562 if (Info.DefiningBlocks.size() == 1) { 563 if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AC)) { 564 // The alloca has been processed, move on. 565 RemoveFromAllocasList(AllocaNum); 566 ++NumSingleStore; 567 continue; 568 } 569 } 570 571 // If the alloca is only read and written in one basic block, just perform a 572 // linear sweep over the block to eliminate it. 573 if (Info.OnlyUsedInOneBlock && 574 promoteSingleBlockAlloca(AI, Info, LBI, DT, AC)) { 575 // The alloca has been processed, move on. 576 RemoveFromAllocasList(AllocaNum); 577 continue; 578 } 579 580 // If we haven't computed a numbering for the BB's in the function, do so 581 // now. 582 if (BBNumbers.empty()) { 583 unsigned ID = 0; 584 for (auto &BB : F) 585 BBNumbers[&BB] = ID++; 586 } 587 588 // Remember the dbg.declare intrinsic describing this alloca, if any. 589 if (Info.DbgDeclare) 590 AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare; 591 592 // Keep the reverse mapping of the 'Allocas' array for the rename pass. 593 AllocaLookup[Allocas[AllocaNum]] = AllocaNum; 594 595 // At this point, we're committed to promoting the alloca using IDF's, and 596 // the standard SSA construction algorithm. Determine which blocks need PHI 597 // nodes and see if we can optimize out some work by avoiding insertion of 598 // dead phi nodes. 599 600 601 // Unique the set of defining blocks for efficient lookup. 602 SmallPtrSet<BasicBlock *, 32> DefBlocks; 603 DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end()); 604 605 // Determine which blocks the value is live in. These are blocks which lead 606 // to uses. 607 SmallPtrSet<BasicBlock *, 32> LiveInBlocks; 608 ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks); 609 610 // At this point, we're committed to promoting the alloca using IDF's, and 611 // the standard SSA construction algorithm. Determine which blocks need phi 612 // nodes and see if we can optimize out some work by avoiding insertion of 613 // dead phi nodes. 614 IDF.setLiveInBlocks(LiveInBlocks); 615 IDF.setDefiningBlocks(DefBlocks); 616 SmallVector<BasicBlock *, 32> PHIBlocks; 617 IDF.calculate(PHIBlocks); 618 if (PHIBlocks.size() > 1) 619 std::sort(PHIBlocks.begin(), PHIBlocks.end(), 620 [this](BasicBlock *A, BasicBlock *B) { 621 return BBNumbers.lookup(A) < BBNumbers.lookup(B); 622 }); 623 624 unsigned CurrentVersion = 0; 625 for (BasicBlock *BB : PHIBlocks) 626 QueuePhiNode(BB, AllocaNum, CurrentVersion); 627 } 628 629 if (Allocas.empty()) 630 return; // All of the allocas must have been trivial! 631 632 LBI.clear(); 633 634 // Set the incoming values for the basic block to be null values for all of 635 // the alloca's. We do this in case there is a load of a value that has not 636 // been stored yet. In this case, it will get this null value. 637 // 638 RenamePassData::ValVector Values(Allocas.size()); 639 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) 640 Values[i] = UndefValue::get(Allocas[i]->getAllocatedType()); 641 642 // Walks all basic blocks in the function performing the SSA rename algorithm 643 // and inserting the phi nodes we marked as necessary 644 // 645 std::vector<RenamePassData> RenamePassWorkList; 646 RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values)); 647 do { 648 RenamePassData RPD = std::move(RenamePassWorkList.back()); 649 RenamePassWorkList.pop_back(); 650 // RenamePass may add new worklist entries. 651 RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList); 652 } while (!RenamePassWorkList.empty()); 653 654 // The renamer uses the Visited set to avoid infinite loops. Clear it now. 655 Visited.clear(); 656 657 // Remove the allocas themselves from the function. 658 for (Instruction *A : Allocas) { 659 // If there are any uses of the alloca instructions left, they must be in 660 // unreachable basic blocks that were not processed by walking the dominator 661 // tree. Just delete the users now. 662 if (!A->use_empty()) 663 A->replaceAllUsesWith(UndefValue::get(A->getType())); 664 A->eraseFromParent(); 665 } 666 667 // Remove alloca's dbg.declare instrinsics from the function. 668 for (DbgDeclareInst *DDI : AllocaDbgDeclares) 669 if (DDI) 670 DDI->eraseFromParent(); 671 672 // Loop over all of the PHI nodes and see if there are any that we can get 673 // rid of because they merge all of the same incoming values. This can 674 // happen due to undef values coming into the PHI nodes. This process is 675 // iterative, because eliminating one PHI node can cause others to be removed. 676 bool EliminatedAPHI = true; 677 while (EliminatedAPHI) { 678 EliminatedAPHI = false; 679 680 // Iterating over NewPhiNodes is deterministic, so it is safe to try to 681 // simplify and RAUW them as we go. If it was not, we could add uses to 682 // the values we replace with in a non-deterministic order, thus creating 683 // non-deterministic def->use chains. 684 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator 685 I = NewPhiNodes.begin(), 686 E = NewPhiNodes.end(); 687 I != E;) { 688 PHINode *PN = I->second; 689 690 // If this PHI node merges one value and/or undefs, get the value. 691 if (Value *V = SimplifyInstruction(PN, SQ)) { 692 PN->replaceAllUsesWith(V); 693 PN->eraseFromParent(); 694 NewPhiNodes.erase(I++); 695 EliminatedAPHI = true; 696 continue; 697 } 698 ++I; 699 } 700 } 701 702 // At this point, the renamer has added entries to PHI nodes for all reachable 703 // code. Unfortunately, there may be unreachable blocks which the renamer 704 // hasn't traversed. If this is the case, the PHI nodes may not 705 // have incoming values for all predecessors. Loop over all PHI nodes we have 706 // created, inserting undef values if they are missing any incoming values. 707 // 708 for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator 709 I = NewPhiNodes.begin(), 710 E = NewPhiNodes.end(); 711 I != E; ++I) { 712 // We want to do this once per basic block. As such, only process a block 713 // when we find the PHI that is the first entry in the block. 714 PHINode *SomePHI = I->second; 715 BasicBlock *BB = SomePHI->getParent(); 716 if (&BB->front() != SomePHI) 717 continue; 718 719 // Only do work here if there the PHI nodes are missing incoming values. We 720 // know that all PHI nodes that were inserted in a block will have the same 721 // number of incoming values, so we can just check any of them. 722 if (SomePHI->getNumIncomingValues() == getNumPreds(BB)) 723 continue; 724 725 // Get the preds for BB. 726 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB)); 727 728 // Ok, now we know that all of the PHI nodes are missing entries for some 729 // basic blocks. Start by sorting the incoming predecessors for efficient 730 // access. 731 std::sort(Preds.begin(), Preds.end()); 732 733 // Now we loop through all BB's which have entries in SomePHI and remove 734 // them from the Preds list. 735 for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) { 736 // Do a log(n) search of the Preds list for the entry we want. 737 SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound( 738 Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i)); 739 assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) && 740 "PHI node has entry for a block which is not a predecessor!"); 741 742 // Remove the entry 743 Preds.erase(EntIt); 744 } 745 746 // At this point, the blocks left in the preds list must have dummy 747 // entries inserted into every PHI nodes for the block. Update all the phi 748 // nodes in this block that we are inserting (there could be phis before 749 // mem2reg runs). 750 unsigned NumBadPreds = SomePHI->getNumIncomingValues(); 751 BasicBlock::iterator BBI = BB->begin(); 752 while ((SomePHI = dyn_cast<PHINode>(BBI++)) && 753 SomePHI->getNumIncomingValues() == NumBadPreds) { 754 Value *UndefVal = UndefValue::get(SomePHI->getType()); 755 for (BasicBlock *Pred : Preds) 756 SomePHI->addIncoming(UndefVal, Pred); 757 } 758 } 759 760 NewPhiNodes.clear(); 761 } 762 763 /// \brief Determine which blocks the value is live in. 764 /// 765 /// These are blocks which lead to uses. Knowing this allows us to avoid 766 /// inserting PHI nodes into blocks which don't lead to uses (thus, the 767 /// inserted phi nodes would be dead). 768 void PromoteMem2Reg::ComputeLiveInBlocks( 769 AllocaInst *AI, AllocaInfo &Info, 770 const SmallPtrSetImpl<BasicBlock *> &DefBlocks, 771 SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) { 772 773 // To determine liveness, we must iterate through the predecessors of blocks 774 // where the def is live. Blocks are added to the worklist if we need to 775 // check their predecessors. Start with all the using blocks. 776 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(), 777 Info.UsingBlocks.end()); 778 779 // If any of the using blocks is also a definition block, check to see if the 780 // definition occurs before or after the use. If it happens before the use, 781 // the value isn't really live-in. 782 for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) { 783 BasicBlock *BB = LiveInBlockWorklist[i]; 784 if (!DefBlocks.count(BB)) 785 continue; 786 787 // Okay, this is a block that both uses and defines the value. If the first 788 // reference to the alloca is a def (store), then we know it isn't live-in. 789 for (BasicBlock::iterator I = BB->begin();; ++I) { 790 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 791 if (SI->getOperand(1) != AI) 792 continue; 793 794 // We found a store to the alloca before a load. The alloca is not 795 // actually live-in here. 796 LiveInBlockWorklist[i] = LiveInBlockWorklist.back(); 797 LiveInBlockWorklist.pop_back(); 798 --i; 799 --e; 800 break; 801 } 802 803 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 804 if (LI->getOperand(0) != AI) 805 continue; 806 807 // Okay, we found a load before a store to the alloca. It is actually 808 // live into this block. 809 break; 810 } 811 } 812 } 813 814 // Now that we have a set of blocks where the phi is live-in, recursively add 815 // their predecessors until we find the full region the value is live. 816 while (!LiveInBlockWorklist.empty()) { 817 BasicBlock *BB = LiveInBlockWorklist.pop_back_val(); 818 819 // The block really is live in here, insert it into the set. If already in 820 // the set, then it has already been processed. 821 if (!LiveInBlocks.insert(BB).second) 822 continue; 823 824 // Since the value is live into BB, it is either defined in a predecessor or 825 // live into it to. Add the preds to the worklist unless they are a 826 // defining block. 827 for (BasicBlock *P : predecessors(BB)) { 828 // The value is not live into a predecessor if it defines the value. 829 if (DefBlocks.count(P)) 830 continue; 831 832 // Otherwise it is, add to the worklist. 833 LiveInBlockWorklist.push_back(P); 834 } 835 } 836 } 837 838 /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca. 839 /// 840 /// Returns true if there wasn't already a phi-node for that variable 841 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo, 842 unsigned &Version) { 843 // Look up the basic-block in question. 844 PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)]; 845 846 // If the BB already has a phi node added for the i'th alloca then we're done! 847 if (PN) 848 return false; 849 850 // Create a PhiNode using the dereferenced type... and add the phi-node to the 851 // BasicBlock. 852 PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB), 853 Allocas[AllocaNo]->getName() + "." + Twine(Version++), 854 &BB->front()); 855 ++NumPHIInsert; 856 PhiToAllocaMap[PN] = AllocaNo; 857 return true; 858 } 859 860 /// \brief Recursively traverse the CFG of the function, renaming loads and 861 /// stores to the allocas which we are promoting. 862 /// 863 /// IncomingVals indicates what value each Alloca contains on exit from the 864 /// predecessor block Pred. 865 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred, 866 RenamePassData::ValVector &IncomingVals, 867 std::vector<RenamePassData> &Worklist) { 868 NextIteration: 869 // If we are inserting any phi nodes into this BB, they will already be in the 870 // block. 871 if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) { 872 // If we have PHI nodes to update, compute the number of edges from Pred to 873 // BB. 874 if (PhiToAllocaMap.count(APN)) { 875 // We want to be able to distinguish between PHI nodes being inserted by 876 // this invocation of mem2reg from those phi nodes that already existed in 877 // the IR before mem2reg was run. We determine that APN is being inserted 878 // because it is missing incoming edges. All other PHI nodes being 879 // inserted by this pass of mem2reg will have the same number of incoming 880 // operands so far. Remember this count. 881 unsigned NewPHINumOperands = APN->getNumOperands(); 882 883 unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB); 884 assert(NumEdges && "Must be at least one edge from Pred to BB!"); 885 886 // Add entries for all the phis. 887 BasicBlock::iterator PNI = BB->begin(); 888 do { 889 unsigned AllocaNo = PhiToAllocaMap[APN]; 890 891 // Add N incoming values to the PHI node. 892 for (unsigned i = 0; i != NumEdges; ++i) 893 APN->addIncoming(IncomingVals[AllocaNo], Pred); 894 895 // The currently active variable for this block is now the PHI. 896 IncomingVals[AllocaNo] = APN; 897 if (DbgDeclareInst *DDI = AllocaDbgDeclares[AllocaNo]) 898 ConvertDebugDeclareToDebugValue(DDI, APN, DIB); 899 900 // Get the next phi node. 901 ++PNI; 902 APN = dyn_cast<PHINode>(PNI); 903 if (!APN) 904 break; 905 906 // Verify that it is missing entries. If not, it is not being inserted 907 // by this mem2reg invocation so we want to ignore it. 908 } while (APN->getNumOperands() == NewPHINumOperands); 909 } 910 } 911 912 // Don't revisit blocks. 913 if (!Visited.insert(BB).second) 914 return; 915 916 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) { 917 Instruction *I = &*II++; // get the instruction, increment iterator 918 919 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 920 AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand()); 921 if (!Src) 922 continue; 923 924 DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src); 925 if (AI == AllocaLookup.end()) 926 continue; 927 928 Value *V = IncomingVals[AI->second]; 929 930 // If the load was marked as nonnull we don't want to lose 931 // that information when we erase this Load. So we preserve 932 // it with an assume. 933 if (AC && LI->getMetadata(LLVMContext::MD_nonnull) && 934 !llvm::isKnownNonNullAt(V, LI, &DT)) 935 addAssumeNonNull(AC, LI); 936 937 // Anything using the load now uses the current value. 938 LI->replaceAllUsesWith(V); 939 BB->getInstList().erase(LI); 940 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 941 // Delete this instruction and mark the name as the current holder of the 942 // value 943 AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand()); 944 if (!Dest) 945 continue; 946 947 DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest); 948 if (ai == AllocaLookup.end()) 949 continue; 950 951 // what value were we writing? 952 IncomingVals[ai->second] = SI->getOperand(0); 953 // Record debuginfo for the store before removing it. 954 if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second]) 955 ConvertDebugDeclareToDebugValue(DDI, SI, DIB); 956 BB->getInstList().erase(SI); 957 } 958 } 959 960 // 'Recurse' to our successors. 961 succ_iterator I = succ_begin(BB), E = succ_end(BB); 962 if (I == E) 963 return; 964 965 // Keep track of the successors so we don't visit the same successor twice 966 SmallPtrSet<BasicBlock *, 8> VisitedSuccs; 967 968 // Handle the first successor without using the worklist. 969 VisitedSuccs.insert(*I); 970 Pred = BB; 971 BB = *I; 972 ++I; 973 974 for (; I != E; ++I) 975 if (VisitedSuccs.insert(*I).second) 976 Worklist.emplace_back(*I, Pred, IncomingVals); 977 978 goto NextIteration; 979 } 980 981 void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT, 982 AssumptionCache *AC) { 983 // If there is nothing to do, bail out... 984 if (Allocas.empty()) 985 return; 986 987 PromoteMem2Reg(Allocas, DT, AC).run(); 988 } 989