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