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