LoopUnswitch.cpp revision b7427031372337e6d67f9573ec6c722ab5ea913e
1//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This pass transforms loops that contain branches on loop-invariant conditions 11// to have multiple loops. For example, it turns the left into the right code: 12// 13// for (...) if (lic) 14// A for (...) 15// if (lic) A; B; C 16// B else 17// C for (...) 18// A; C 19// 20// This can increase the size of the code exponentially (doubling it every time 21// a loop is unswitched) so we only unswitch if the resultant code will be 22// smaller than a threshold. 23// 24// This pass expects LICM to be run before it to hoist invariant conditions out 25// of the loop, to make the unswitching opportunity obvious. 26// 27//===----------------------------------------------------------------------===// 28 29#define DEBUG_TYPE "loop-unswitch" 30#include "llvm/Transforms/Scalar.h" 31#include "llvm/Constants.h" 32#include "llvm/Function.h" 33#include "llvm/Instructions.h" 34#include "llvm/Analysis/LoopInfo.h" 35#include "llvm/Transforms/Utils/Cloning.h" 36#include "llvm/Transforms/Utils/Local.h" 37#include "llvm/Transforms/Utils/BasicBlockUtils.h" 38#include "llvm/ADT/Statistic.h" 39#include "llvm/ADT/PostOrderIterator.h" 40#include "llvm/Support/Debug.h" 41#include "llvm/Support/CommandLine.h" 42#include <algorithm> 43#include <set> 44using namespace llvm; 45 46namespace { 47 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched"); 48 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched"); 49 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched"); 50 Statistic<> NumTrivial ("loop-unswitch", 51 "Number of unswitches that are trivial"); 52 Statistic<> NumSimplify("loop-unswitch", 53 "Number of simplifications of unswitched code"); 54 cl::opt<unsigned> 55 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), 56 cl::init(10), cl::Hidden); 57 58 class LoopUnswitch : public FunctionPass { 59 LoopInfo *LI; // Loop information 60 61 // LoopProcessWorklist - List of loops we need to process. 62 std::vector<Loop*> LoopProcessWorklist; 63 public: 64 virtual bool runOnFunction(Function &F); 65 bool visitLoop(Loop *L); 66 67 /// This transformation requires natural loop information & requires that 68 /// loop preheaders be inserted into the CFG... 69 /// 70 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 71 AU.addRequiredID(LoopSimplifyID); 72 AU.addPreservedID(LoopSimplifyID); 73 AU.addRequired<LoopInfo>(); 74 AU.addPreserved<LoopInfo>(); 75 AU.addRequiredID(LCSSAID); 76 AU.addPreservedID(LCSSAID); 77 } 78 79 private: 80 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist, 81 /// remove it. 82 void RemoveLoopFromWorklist(Loop *L) { 83 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(), 84 LoopProcessWorklist.end(), L); 85 if (I != LoopProcessWorklist.end()) 86 LoopProcessWorklist.erase(I); 87 } 88 89 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L); 90 unsigned getLoopUnswitchCost(Loop *L, Value *LIC); 91 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val, 92 BasicBlock *ExitBlock); 93 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L); 94 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To); 95 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt); 96 97 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, 98 Constant *Val, bool isEqual); 99 100 void SimplifyCode(std::vector<Instruction*> &Worklist); 101 void RemoveBlockIfDead(BasicBlock *BB, 102 std::vector<Instruction*> &Worklist); 103 void RemoveLoopFromHierarchy(Loop *L); 104 }; 105 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops"); 106} 107 108FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); } 109 110bool LoopUnswitch::runOnFunction(Function &F) { 111 bool Changed = false; 112 LI = &getAnalysis<LoopInfo>(); 113 114 // Populate the worklist of loops to process in post-order. 115 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 116 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI) 117 LoopProcessWorklist.push_back(*LI); 118 119 // Process the loops in worklist order, this is a post-order visitation of 120 // the loops. We use a worklist of loops so that loops can be removed at any 121 // time if they are deleted (e.g. the backedge of a loop is removed). 122 while (!LoopProcessWorklist.empty()) { 123 Loop *L = LoopProcessWorklist.back(); 124 LoopProcessWorklist.pop_back(); 125 Changed |= visitLoop(L); 126 } 127 128 return Changed; 129} 130 131/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is 132/// invariant in the loop, or has an invariant piece, return the invariant. 133/// Otherwise, return null. 134static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) { 135 // Constants should be folded, not unswitched on! 136 if (isa<Constant>(Cond)) return false; 137 138 // TODO: Handle: br (VARIANT|INVARIANT). 139 // TODO: Hoist simple expressions out of loops. 140 if (L->isLoopInvariant(Cond)) return Cond; 141 142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond)) 143 if (BO->getOpcode() == Instruction::And || 144 BO->getOpcode() == Instruction::Or) { 145 // If either the left or right side is invariant, we can unswitch on this, 146 // which will cause the branch to go away in one loop and the condition to 147 // simplify in the other one. 148 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed)) 149 return LHS; 150 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed)) 151 return RHS; 152 } 153 154 return 0; 155} 156 157bool LoopUnswitch::visitLoop(Loop *L) { 158 assert(L->isLCSSAForm()); 159 160 bool Changed = false; 161 162 // Loop over all of the basic blocks in the loop. If we find an interior 163 // block that is branching on a loop-invariant condition, we can unswitch this 164 // loop. 165 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 166 I != E; ++I) { 167 TerminatorInst *TI = (*I)->getTerminator(); 168 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 169 // If this isn't branching on an invariant condition, we can't unswitch 170 // it. 171 if (BI->isConditional()) { 172 // See if this, or some part of it, is loop invariant. If so, we can 173 // unswitch on it if we desire. 174 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed); 175 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::getTrue(), 176 L)) { 177 ++NumBranches; 178 return true; 179 } 180 } 181 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 182 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed); 183 if (LoopCond && SI->getNumCases() > 1) { 184 // Find a value to unswitch on: 185 // FIXME: this should chose the most expensive case! 186 Constant *UnswitchVal = SI->getCaseValue(1); 187 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) { 188 ++NumSwitches; 189 return true; 190 } 191 } 192 } 193 194 // Scan the instructions to check for unswitchable values. 195 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 196 BBI != E; ++BBI) 197 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) { 198 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed); 199 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::getTrue(), 200 L)) { 201 ++NumSelects; 202 return true; 203 } 204 } 205 } 206 207 assert(L->isLCSSAForm()); 208 209 return Changed; 210} 211 212/// isTrivialLoopExitBlock - Check to see if all paths from BB either: 213/// 1. Exit the loop with no side effects. 214/// 2. Branch to the latch block with no side-effects. 215/// 216/// If these conditions are true, we return true and set ExitBB to the block we 217/// exit through. 218/// 219static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, 220 BasicBlock *&ExitBB, 221 std::set<BasicBlock*> &Visited) { 222 if (!Visited.insert(BB).second) { 223 // Already visited and Ok, end of recursion. 224 return true; 225 } else if (!L->contains(BB)) { 226 // Otherwise, this is a loop exit, this is fine so long as this is the 227 // first exit. 228 if (ExitBB != 0) return false; 229 ExitBB = BB; 230 return true; 231 } 232 233 // Otherwise, this is an unvisited intra-loop node. Check all successors. 234 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) { 235 // Check to see if the successor is a trivial loop exit. 236 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited)) 237 return false; 238 } 239 240 // Okay, everything after this looks good, check to make sure that this block 241 // doesn't include any side effects. 242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 243 if (I->mayWriteToMemory()) 244 return false; 245 246 return true; 247} 248 249/// isTrivialLoopExitBlock - Return true if the specified block unconditionally 250/// leads to an exit from the specified loop, and has no side-effects in the 251/// process. If so, return the block that is exited to, otherwise return null. 252static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) { 253 std::set<BasicBlock*> Visited; 254 Visited.insert(L->getHeader()); // Branches to header are ok. 255 BasicBlock *ExitBB = 0; 256 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited)) 257 return ExitBB; 258 return 0; 259} 260 261/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is 262/// trivial: that is, that the condition controls whether or not the loop does 263/// anything at all. If this is a trivial condition, unswitching produces no 264/// code duplications (equivalently, it produces a simpler loop and a new empty 265/// loop, which gets deleted). 266/// 267/// If this is a trivial condition, return true, otherwise return false. When 268/// returning true, this sets Cond and Val to the condition that controls the 269/// trivial condition: when Cond dynamically equals Val, the loop is known to 270/// exit. Finally, this sets LoopExit to the BB that the loop exits to when 271/// Cond == Val. 272/// 273static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0, 274 BasicBlock **LoopExit = 0) { 275 BasicBlock *Header = L->getHeader(); 276 TerminatorInst *HeaderTerm = Header->getTerminator(); 277 278 BasicBlock *LoopExitBB = 0; 279 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) { 280 // If the header block doesn't end with a conditional branch on Cond, we 281 // can't handle it. 282 if (!BI->isConditional() || BI->getCondition() != Cond) 283 return false; 284 285 // Check to see if a successor of the branch is guaranteed to go to the 286 // latch block or exit through a one exit block without having any 287 // side-effects. If so, determine the value of Cond that causes it to do 288 // this. 289 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) { 290 if (Val) *Val = ConstantBool::getTrue(); 291 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) { 292 if (Val) *Val = ConstantBool::getFalse(); 293 } 294 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) { 295 // If this isn't a switch on Cond, we can't handle it. 296 if (SI->getCondition() != Cond) return false; 297 298 // Check to see if a successor of the switch is guaranteed to go to the 299 // latch block or exit through a one exit block without having any 300 // side-effects. If so, determine the value of Cond that causes it to do 301 // this. Note that we can't trivially unswitch on the default case. 302 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) 303 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) { 304 // Okay, we found a trivial case, remember the value that is trivial. 305 if (Val) *Val = SI->getCaseValue(i); 306 break; 307 } 308 } 309 310 // If we didn't find a single unique LoopExit block, or if the loop exit block 311 // contains phi nodes, this isn't trivial. 312 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin())) 313 return false; // Can't handle this. 314 315 if (LoopExit) *LoopExit = LoopExitBB; 316 317 // We already know that nothing uses any scalar values defined inside of this 318 // loop. As such, we just have to check to see if this loop will execute any 319 // side-effecting instructions (e.g. stores, calls, volatile loads) in the 320 // part of the loop that the code *would* execute. We already checked the 321 // tail, check the header now. 322 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I) 323 if (I->mayWriteToMemory()) 324 return false; 325 return true; 326} 327 328/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if 329/// we choose to unswitch the specified loop on the specified value. 330/// 331unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) { 332 // If the condition is trivial, always unswitch. There is no code growth for 333 // this case. 334 if (IsTrivialUnswitchCondition(L, LIC)) 335 return 0; 336 337 // FIXME: This is really overly conservative. However, more liberal 338 // estimations have thus far resulted in excessive unswitching, which is bad 339 // both in compile time and in code size. This should be replaced once 340 // someone figures out how a good estimation. 341 return L->getBlocks().size(); 342 343 unsigned Cost = 0; 344 // FIXME: this is brain dead. It should take into consideration code 345 // shrinkage. 346 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 347 I != E; ++I) { 348 BasicBlock *BB = *I; 349 // Do not include empty blocks in the cost calculation. This happen due to 350 // loop canonicalization and will be removed. 351 if (BB->begin() == BasicBlock::iterator(BB->getTerminator())) 352 continue; 353 354 // Count basic blocks. 355 ++Cost; 356 } 357 358 return Cost; 359} 360 361/// UnswitchIfProfitable - We have found that we can unswitch L when 362/// LoopCond == Val to simplify the loop. If we decide that this is profitable, 363/// unswitch the loop, reprocess the pieces, then return true. 364bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){ 365 // Check to see if it would be profitable to unswitch this loop. 366 unsigned Cost = getLoopUnswitchCost(L, LoopCond); 367 if (Cost > Threshold) { 368 // FIXME: this should estimate growth by the amount of code shared by the 369 // resultant unswitched loops. 370 // 371 DOUT << "NOT unswitching loop %" 372 << L->getHeader()->getName() << ", cost too high: " 373 << L->getBlocks().size() << "\n"; 374 return false; 375 } 376 377 // If this is a trivial condition to unswitch (which results in no code 378 // duplication), do it now. 379 Constant *CondVal; 380 BasicBlock *ExitBlock; 381 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) { 382 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock); 383 } else { 384 UnswitchNontrivialCondition(LoopCond, Val, L); 385 } 386 387 return true; 388} 389 390/// SplitBlock - Split the specified block at the specified instruction - every 391/// thing before SplitPt stays in Old and everything starting with SplitPt moves 392/// to a new block. The two blocks are joined by an unconditional branch and 393/// the loop info is updated. 394/// 395BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) { 396 BasicBlock::iterator SplitIt = SplitPt; 397 while (isa<PHINode>(SplitIt)) 398 ++SplitIt; 399 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split"); 400 401 // The new block lives in whichever loop the old one did. 402 if (Loop *L = LI->getLoopFor(Old)) 403 L->addBasicBlockToLoop(New, *LI); 404 405 return New; 406} 407 408 409BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) { 410 TerminatorInst *LatchTerm = BB->getTerminator(); 411 unsigned SuccNum = 0; 412 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) { 413 assert(i != e && "Didn't find edge?"); 414 if (LatchTerm->getSuccessor(i) == Succ) { 415 SuccNum = i; 416 break; 417 } 418 } 419 420 // If this is a critical edge, let SplitCriticalEdge do it. 421 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this)) 422 return LatchTerm->getSuccessor(SuccNum); 423 424 // If the edge isn't critical, then BB has a single successor or Succ has a 425 // single pred. Split the block. 426 BasicBlock::iterator SplitPoint; 427 if (BasicBlock *SP = Succ->getSinglePredecessor()) { 428 // If the successor only has a single pred, split the top of the successor 429 // block. 430 assert(SP == BB && "CFG broken"); 431 return SplitBlock(Succ, Succ->begin()); 432 } else { 433 // Otherwise, if BB has a single successor, split it at the bottom of the 434 // block. 435 assert(BB->getTerminator()->getNumSuccessors() == 1 && 436 "Should have a single succ!"); 437 return SplitBlock(BB, BB->getTerminator()); 438 } 439} 440 441 442 443// RemapInstruction - Convert the instruction operands from referencing the 444// current values into those specified by ValueMap. 445// 446static inline void RemapInstruction(Instruction *I, 447 std::map<const Value *, Value*> &ValueMap) { 448 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 449 Value *Op = I->getOperand(op); 450 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); 451 if (It != ValueMap.end()) Op = It->second; 452 I->setOperand(op, Op); 453 } 454} 455 456/// CloneLoop - Recursively clone the specified loop and all of its children, 457/// mapping the blocks with the specified map. 458static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM, 459 LoopInfo *LI) { 460 Loop *New = new Loop(); 461 462 if (PL) 463 PL->addChildLoop(New); 464 else 465 LI->addTopLevelLoop(New); 466 467 // Add all of the blocks in L to the new loop. 468 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 469 I != E; ++I) 470 if (LI->getLoopFor(*I) == L) 471 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); 472 473 // Add all of the subloops to the new loop. 474 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 475 CloneLoop(*I, New, VM, LI); 476 477 return New; 478} 479 480/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values 481/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the 482/// code immediately before InsertPt. 483static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val, 484 BasicBlock *TrueDest, 485 BasicBlock *FalseDest, 486 Instruction *InsertPt) { 487 // Insert a conditional branch on LIC to the two preheaders. The original 488 // code is the true version and the new code is the false version. 489 Value *BranchVal = LIC; 490 if (!isa<ConstantBool>(Val)) { 491 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt); 492 } else if (Val != ConstantBool::getTrue()) { 493 // We want to enter the new loop when the condition is true. 494 std::swap(TrueDest, FalseDest); 495 } 496 497 // Insert the new branch. 498 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt); 499} 500 501 502/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable 503/// condition in it (a cond branch from its header block to its latch block, 504/// where the path through the loop that doesn't execute its body has no 505/// side-effects), unswitch it. This doesn't involve any code duplication, just 506/// moving the conditional branch outside of the loop and updating loop info. 507void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 508 Constant *Val, 509 BasicBlock *ExitBlock) { 510 DOUT << "loop-unswitch: Trivial-Unswitch loop %" 511 << L->getHeader()->getName() << " [" << L->getBlocks().size() 512 << " blocks] in Function " << L->getHeader()->getParent()->getName() 513 << " on cond: " << *Val << " == " << *Cond << "\n"; 514 515 // First step, split the preheader, so that we know that there is a safe place 516 // to insert the conditional branch. We will change 'OrigPH' to have a 517 // conditional branch on Cond. 518 BasicBlock *OrigPH = L->getLoopPreheader(); 519 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader()); 520 521 // Now that we have a place to insert the conditional branch, create a place 522 // to branch to: this is the exit block out of the loop that we should 523 // short-circuit to. 524 525 // Split this block now, so that the loop maintains its exit block, and so 526 // that the jump from the preheader can execute the contents of the exit block 527 // without actually branching to it (the exit block should be dominated by the 528 // loop header, not the preheader). 529 assert(!L->contains(ExitBlock) && "Exit block is in the loop?"); 530 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin()); 531 532 // Okay, now we have a position to branch from and a position to branch to, 533 // insert the new conditional branch. 534 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 535 OrigPH->getTerminator()); 536 OrigPH->getTerminator()->eraseFromParent(); 537 538 // We need to reprocess this loop, it could be unswitched again. 539 LoopProcessWorklist.push_back(L); 540 541 // Now that we know that the loop is never entered when this condition is a 542 // particular value, rewrite the loop with this info. We know that this will 543 // at least eliminate the old branch. 544 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false); 545 ++NumTrivial; 546} 547 548 549/// VersionLoop - We determined that the loop is profitable to unswitch when LIC 550/// equal Val. Split it into loop versions and test the condition outside of 551/// either loop. Return the loops created as Out1/Out2. 552void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 553 Loop *L) { 554 Function *F = L->getHeader()->getParent(); 555 DOUT << "loop-unswitch: Unswitching loop %" 556 << L->getHeader()->getName() << " [" << L->getBlocks().size() 557 << " blocks] in Function " << F->getName() 558 << " when '" << *Val << "' == " << *LIC << "\n"; 559 560 // LoopBlocks contains all of the basic blocks of the loop, including the 561 // preheader of the loop, the body of the loop, and the exit blocks of the 562 // loop, in that order. 563 std::vector<BasicBlock*> LoopBlocks; 564 565 // First step, split the preheader and exit blocks, and add these blocks to 566 // the LoopBlocks list. 567 BasicBlock *OrigPreheader = L->getLoopPreheader(); 568 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader())); 569 570 // We want the loop to come after the preheader, but before the exit blocks. 571 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); 572 573 std::vector<BasicBlock*> ExitBlocks; 574 L->getUniqueExitBlocks(ExitBlocks); 575 576 // Split all of the edges from inside the loop to their exit blocks. Update 577 // the appropriate Phi nodes as we do so. 578 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 579 BasicBlock *ExitBlock = ExitBlocks[i]; 580 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock)); 581 582 for (unsigned j = 0, e = Preds.size(); j != e; ++j) { 583 assert(L->contains(Preds[j]) && 584 "All preds of loop exit blocks must be the same loop!"); 585 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock); 586 BasicBlock* StartBlock = Preds[j]; 587 BasicBlock* EndBlock; 588 if (MiddleBlock->getSinglePredecessor() == ExitBlock) { 589 EndBlock = MiddleBlock; 590 MiddleBlock = EndBlock->getSinglePredecessor();; 591 } else { 592 EndBlock = ExitBlock; 593 } 594 595 std::set<PHINode*> InsertedPHIs; 596 PHINode* OldLCSSA = 0; 597 for (BasicBlock::iterator I = EndBlock->begin(); 598 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) { 599 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock); 600 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(), 601 OldLCSSA->getName() + ".us-lcssa", 602 MiddleBlock->getTerminator()); 603 NewLCSSA->addIncoming(OldValue, StartBlock); 604 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock), 605 NewLCSSA); 606 InsertedPHIs.insert(NewLCSSA); 607 } 608 609 BasicBlock::iterator InsertPt = EndBlock->begin(); 610 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt; 611 for (BasicBlock::iterator I = MiddleBlock->begin(); 612 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0; 613 ++I) { 614 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(), 615 OldLCSSA->getName() + ".us-lcssa", 616 InsertPt); 617 OldLCSSA->replaceAllUsesWith(NewLCSSA); 618 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock); 619 } 620 } 621 } 622 623 // The exit blocks may have been changed due to edge splitting, recompute. 624 ExitBlocks.clear(); 625 L->getUniqueExitBlocks(ExitBlocks); 626 627 // Add exit blocks to the loop blocks. 628 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end()); 629 630 // Next step, clone all of the basic blocks that make up the loop (including 631 // the loop preheader and exit blocks), keeping track of the mapping between 632 // the instructions and blocks. 633 std::vector<BasicBlock*> NewBlocks; 634 NewBlocks.reserve(LoopBlocks.size()); 635 std::map<const Value*, Value*> ValueMap; 636 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { 637 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F); 638 NewBlocks.push_back(New); 639 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping. 640 } 641 642 // Splice the newly inserted blocks into the function right before the 643 // original preheader. 644 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(), 645 NewBlocks[0], F->end()); 646 647 // Now we create the new Loop object for the versioned loop. 648 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI); 649 Loop *ParentLoop = L->getParentLoop(); 650 if (ParentLoop) { 651 // Make sure to add the cloned preheader and exit blocks to the parent loop 652 // as well. 653 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI); 654 } 655 656 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 657 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]); 658 // The new exit block should be in the same loop as the old one. 659 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i])) 660 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI); 661 662 assert(NewExit->getTerminator()->getNumSuccessors() == 1 && 663 "Exit block should have been split to have one successor!"); 664 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0); 665 666 // If the successor of the exit block had PHI nodes, add an entry for 667 // NewExit. 668 PHINode *PN; 669 for (BasicBlock::iterator I = ExitSucc->begin(); 670 (PN = dyn_cast<PHINode>(I)); ++I) { 671 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]); 672 std::map<const Value *, Value*>::iterator It = ValueMap.find(V); 673 if (It != ValueMap.end()) V = It->second; 674 PN->addIncoming(V, NewExit); 675 } 676 } 677 678 // Rewrite the code to refer to itself. 679 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) 680 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 681 E = NewBlocks[i]->end(); I != E; ++I) 682 RemapInstruction(I, ValueMap); 683 684 // Rewrite the original preheader to select between versions of the loop. 685 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator()); 686 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] && 687 "Preheader splitting did not work correctly!"); 688 689 // Emit the new branch that selects between the two versions of this loop. 690 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR); 691 OldBR->eraseFromParent(); 692 693 LoopProcessWorklist.push_back(L); 694 LoopProcessWorklist.push_back(NewLoop); 695 696 // Now we rewrite the original code to know that the condition is true and the 697 // new code to know that the condition is false. 698 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false); 699 700 // It's possible that simplifying one loop could cause the other to be 701 // deleted. If so, don't simplify it. 702 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop) 703 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true); 704} 705 706/// RemoveFromWorklist - Remove all instances of I from the worklist vector 707/// specified. 708static void RemoveFromWorklist(Instruction *I, 709 std::vector<Instruction*> &Worklist) { 710 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(), 711 Worklist.end(), I); 712 while (WI != Worklist.end()) { 713 unsigned Offset = WI-Worklist.begin(); 714 Worklist.erase(WI); 715 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I); 716 } 717} 718 719/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the 720/// program, replacing all uses with V and update the worklist. 721static void ReplaceUsesOfWith(Instruction *I, Value *V, 722 std::vector<Instruction*> &Worklist) { 723 DOUT << "Replace with '" << *V << "': " << *I; 724 725 // Add uses to the worklist, which may be dead now. 726 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 727 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i))) 728 Worklist.push_back(Use); 729 730 // Add users to the worklist which may be simplified now. 731 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 732 UI != E; ++UI) 733 Worklist.push_back(cast<Instruction>(*UI)); 734 I->replaceAllUsesWith(V); 735 I->eraseFromParent(); 736 RemoveFromWorklist(I, Worklist); 737 ++NumSimplify; 738} 739 740/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop 741/// information, and remove any dead successors it has. 742/// 743void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB, 744 std::vector<Instruction*> &Worklist) { 745 if (pred_begin(BB) != pred_end(BB)) { 746 // This block isn't dead, since an edge to BB was just removed, see if there 747 // are any easy simplifications we can do now. 748 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 749 // If it has one pred, fold phi nodes in BB. 750 while (isa<PHINode>(BB->begin())) 751 ReplaceUsesOfWith(BB->begin(), 752 cast<PHINode>(BB->begin())->getIncomingValue(0), 753 Worklist); 754 755 // If this is the header of a loop and the only pred is the latch, we now 756 // have an unreachable loop. 757 if (Loop *L = LI->getLoopFor(BB)) 758 if (L->getHeader() == BB && L->contains(Pred)) { 759 // Remove the branch from the latch to the header block, this makes 760 // the header dead, which will make the latch dead (because the header 761 // dominates the latch). 762 Pred->getTerminator()->eraseFromParent(); 763 new UnreachableInst(Pred); 764 765 // The loop is now broken, remove it from LI. 766 RemoveLoopFromHierarchy(L); 767 768 // Reprocess the header, which now IS dead. 769 RemoveBlockIfDead(BB, Worklist); 770 return; 771 } 772 773 // If pred ends in a uncond branch, add uncond branch to worklist so that 774 // the two blocks will get merged. 775 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) 776 if (BI->isUnconditional()) 777 Worklist.push_back(BI); 778 } 779 return; 780 } 781 782 DOUT << "Nuking dead block: " << *BB; 783 784 // Remove the instructions in the basic block from the worklist. 785 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 786 RemoveFromWorklist(I, Worklist); 787 788 // Anything that uses the instructions in this basic block should have their 789 // uses replaced with undefs. 790 if (!I->use_empty()) 791 I->replaceAllUsesWith(UndefValue::get(I->getType())); 792 } 793 794 // If this is the edge to the header block for a loop, remove the loop and 795 // promote all subloops. 796 if (Loop *BBLoop = LI->getLoopFor(BB)) { 797 if (BBLoop->getLoopLatch() == BB) 798 RemoveLoopFromHierarchy(BBLoop); 799 } 800 801 // Remove the block from the loop info, which removes it from any loops it 802 // was in. 803 LI->removeBlock(BB); 804 805 806 // Remove phi node entries in successors for this block. 807 TerminatorInst *TI = BB->getTerminator(); 808 std::vector<BasicBlock*> Succs; 809 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 810 Succs.push_back(TI->getSuccessor(i)); 811 TI->getSuccessor(i)->removePredecessor(BB); 812 } 813 814 // Unique the successors, remove anything with multiple uses. 815 std::sort(Succs.begin(), Succs.end()); 816 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end()); 817 818 // Remove the basic block, including all of the instructions contained in it. 819 BB->eraseFromParent(); 820 821 // Remove successor blocks here that are not dead, so that we know we only 822 // have dead blocks in this list. Nondead blocks have a way of becoming dead, 823 // then getting removed before we revisit them, which is badness. 824 // 825 for (unsigned i = 0; i != Succs.size(); ++i) 826 if (pred_begin(Succs[i]) != pred_end(Succs[i])) { 827 // One exception is loop headers. If this block was the preheader for a 828 // loop, then we DO want to visit the loop so the loop gets deleted. 829 // We know that if the successor is a loop header, that this loop had to 830 // be the preheader: the case where this was the latch block was handled 831 // above and headers can only have two predecessors. 832 if (!LI->isLoopHeader(Succs[i])) { 833 Succs.erase(Succs.begin()+i); 834 --i; 835 } 836 } 837 838 for (unsigned i = 0, e = Succs.size(); i != e; ++i) 839 RemoveBlockIfDead(Succs[i], Worklist); 840} 841 842/// RemoveLoopFromHierarchy - We have discovered that the specified loop has 843/// become unwrapped, either because the backedge was deleted, or because the 844/// edge into the header was removed. If the edge into the header from the 845/// latch block was removed, the loop is unwrapped but subloops are still alive, 846/// so they just reparent loops. If the loops are actually dead, they will be 847/// removed later. 848void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) { 849 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop. 850 // Reparent all of the blocks in this loop. Since BBLoop had a parent, 851 // they are now all in it. 852 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 853 I != E; ++I) 854 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops. 855 LI->changeLoopFor(*I, ParentLoop); 856 857 // Remove the loop from its parent loop. 858 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();; 859 ++I) { 860 assert(I != E && "Couldn't find loop"); 861 if (*I == L) { 862 ParentLoop->removeChildLoop(I); 863 break; 864 } 865 } 866 867 // Move all subloops into the parent loop. 868 while (L->begin() != L->end()) 869 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1)); 870 } else { 871 // Reparent all of the blocks in this loop. Since BBLoop had no parent, 872 // they no longer in a loop at all. 873 874 for (unsigned i = 0; i != L->getBlocks().size(); ++i) { 875 // Don't change blocks in subloops. 876 if (LI->getLoopFor(L->getBlocks()[i]) == L) { 877 LI->removeBlock(L->getBlocks()[i]); 878 --i; 879 } 880 } 881 882 // Remove the loop from the top-level LoopInfo object. 883 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) { 884 assert(I != E && "Couldn't find loop"); 885 if (*I == L) { 886 LI->removeLoop(I); 887 break; 888 } 889 } 890 891 // Move all of the subloops to the top-level. 892 while (L->begin() != L->end()) 893 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1)); 894 } 895 896 delete L; 897 RemoveLoopFromWorklist(L); 898} 899 900 901 902// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has 903// the value specified by Val in the specified loop, or we know it does NOT have 904// that value. Rewrite any uses of LIC or of properties correlated to it. 905void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, 906 Constant *Val, 907 bool IsEqual) { 908 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); 909 910 // FIXME: Support correlated properties, like: 911 // for (...) 912 // if (li1 < li2) 913 // ... 914 // if (li1 > li2) 915 // ... 916 917 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches, 918 // selects, switches. 919 std::vector<User*> Users(LIC->use_begin(), LIC->use_end()); 920 std::vector<Instruction*> Worklist; 921 922 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC 923 // in the loop with the appropriate one directly. 924 if (IsEqual || isa<ConstantBool>(Val)) { 925 Value *Replacement; 926 if (IsEqual) 927 Replacement = Val; 928 else 929 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue()); 930 931 for (unsigned i = 0, e = Users.size(); i != e; ++i) 932 if (Instruction *U = cast<Instruction>(Users[i])) { 933 if (!L->contains(U->getParent())) 934 continue; 935 U->replaceUsesOfWith(LIC, Replacement); 936 Worklist.push_back(U); 937 } 938 } else { 939 // Otherwise, we don't know the precise value of LIC, but we do know that it 940 // is certainly NOT "Val". As such, simplify any uses in the loop that we 941 // can. This case occurs when we unswitch switch statements. 942 for (unsigned i = 0, e = Users.size(); i != e; ++i) 943 if (Instruction *U = cast<Instruction>(Users[i])) { 944 if (!L->contains(U->getParent())) 945 continue; 946 947 Worklist.push_back(U); 948 949 // If we know that LIC is not Val, use this info to simplify code. 950 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) { 951 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) { 952 if (SI->getCaseValue(i) == Val) { 953 // Found a dead case value. Don't remove PHI nodes in the 954 // successor if they become single-entry, those PHI nodes may 955 // be in the Users list. 956 957 // FIXME: This is a hack. We need to keep the successor around 958 // and hooked up so as to preserve the loop structure, because 959 // trying to update it is complicated. So instead we preserve the 960 // loop structure and put the block on an dead code path. 961 962 BasicBlock* Old = SI->getParent(); 963 BasicBlock* Split = SplitBlock(Old, SI); 964 965 Instruction* OldTerm = Old->getTerminator(); 966 new BranchInst(Split, SI->getSuccessor(i), 967 ConstantBool::getTrue(), OldTerm); 968 969 Old->getTerminator()->eraseFromParent(); 970 971 972 PHINode *PN; 973 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin(); 974 (PN = dyn_cast<PHINode>(II)); ++II) { 975 Value *InVal = PN->removeIncomingValue(Split, false); 976 PN->addIncoming(InVal, Old); 977 } 978 979 SI->removeCase(i); 980 break; 981 } 982 } 983 } 984 985 // TODO: We could do other simplifications, for example, turning 986 // LIC == Val -> false. 987 } 988 } 989 990 SimplifyCode(Worklist); 991} 992 993/// SimplifyCode - Okay, now that we have simplified some instructions in the 994/// loop, walk over it and constant prop, dce, and fold control flow where 995/// possible. Note that this is effectively a very simple loop-structure-aware 996/// optimizer. During processing of this loop, L could very well be deleted, so 997/// it must not be used. 998/// 999/// FIXME: When the loop optimizer is more mature, separate this out to a new 1000/// pass. 1001/// 1002void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) { 1003 while (!Worklist.empty()) { 1004 Instruction *I = Worklist.back(); 1005 Worklist.pop_back(); 1006 1007 // Simple constant folding. 1008 if (Constant *C = ConstantFoldInstruction(I)) { 1009 ReplaceUsesOfWith(I, C, Worklist); 1010 continue; 1011 } 1012 1013 // Simple DCE. 1014 if (isInstructionTriviallyDead(I)) { 1015 DOUT << "Remove dead instruction '" << *I; 1016 1017 // Add uses to the worklist, which may be dead now. 1018 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1019 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i))) 1020 Worklist.push_back(Use); 1021 I->eraseFromParent(); 1022 RemoveFromWorklist(I, Worklist); 1023 ++NumSimplify; 1024 continue; 1025 } 1026 1027 // Special case hacks that appear commonly in unswitched code. 1028 switch (I->getOpcode()) { 1029 case Instruction::Select: 1030 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) { 1031 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist); 1032 continue; 1033 } 1034 break; 1035 case Instruction::And: 1036 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS 1037 cast<BinaryOperator>(I)->swapOperands(); 1038 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) { 1039 if (CB->getValue()) // X & 1 -> X 1040 ReplaceUsesOfWith(I, I->getOperand(0), Worklist); 1041 else // X & 0 -> 0 1042 ReplaceUsesOfWith(I, I->getOperand(1), Worklist); 1043 continue; 1044 } 1045 break; 1046 case Instruction::Or: 1047 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS 1048 cast<BinaryOperator>(I)->swapOperands(); 1049 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) { 1050 if (CB->getValue()) // X | 1 -> 1 1051 ReplaceUsesOfWith(I, I->getOperand(1), Worklist); 1052 else // X | 0 -> X 1053 ReplaceUsesOfWith(I, I->getOperand(0), Worklist); 1054 continue; 1055 } 1056 break; 1057 case Instruction::Br: { 1058 BranchInst *BI = cast<BranchInst>(I); 1059 if (BI->isUnconditional()) { 1060 // If BI's parent is the only pred of the successor, fold the two blocks 1061 // together. 1062 BasicBlock *Pred = BI->getParent(); 1063 BasicBlock *Succ = BI->getSuccessor(0); 1064 BasicBlock *SinglePred = Succ->getSinglePredecessor(); 1065 if (!SinglePred) continue; // Nothing to do. 1066 assert(SinglePred == Pred && "CFG broken"); 1067 1068 DOUT << "Merging blocks: " << Pred->getName() << " <- " 1069 << Succ->getName() << "\n"; 1070 1071 // Resolve any single entry PHI nodes in Succ. 1072 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin())) 1073 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist); 1074 1075 // Move all of the successor contents from Succ to Pred. 1076 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(), 1077 Succ->end()); 1078 BI->eraseFromParent(); 1079 RemoveFromWorklist(BI, Worklist); 1080 1081 // If Succ has any successors with PHI nodes, update them to have 1082 // entries coming from Pred instead of Succ. 1083 Succ->replaceAllUsesWith(Pred); 1084 1085 // Remove Succ from the loop tree. 1086 LI->removeBlock(Succ); 1087 Succ->eraseFromParent(); 1088 ++NumSimplify; 1089 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){ 1090 // Conditional branch. Turn it into an unconditional branch, then 1091 // remove dead blocks. 1092 break; // FIXME: Enable. 1093 1094 DOUT << "Folded branch: " << *BI; 1095 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue()); 1096 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue()); 1097 DeadSucc->removePredecessor(BI->getParent(), true); 1098 Worklist.push_back(new BranchInst(LiveSucc, BI)); 1099 BI->eraseFromParent(); 1100 RemoveFromWorklist(BI, Worklist); 1101 ++NumSimplify; 1102 1103 RemoveBlockIfDead(DeadSucc, Worklist); 1104 } 1105 break; 1106 } 1107 } 1108 } 1109} 1110