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