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