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