Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 1 | //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 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. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 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" |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 34 | #include "llvm/Analysis/LoopInfo.h" |
| 35 | #include "llvm/Transforms/Utils/Cloning.h" |
| 36 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | ec6b40a | 2006-02-10 19:08:15 +0000 | [diff] [blame] | 37 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 38 | #include "llvm/ADT/Statistic.h" |
Chris Lattner | 8976219 | 2006-02-09 20:15:48 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
| 40 | #include "llvm/Support/CommandLine.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 41 | #include <algorithm> |
Chris Lattner | c597b8a | 2006-01-22 23:32:06 +0000 | [diff] [blame] | 42 | #include <iostream> |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 43 | #include <set> |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 44 | using namespace llvm; |
| 45 | |
| 46 | namespace { |
| 47 | Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched"); |
Chris Lattner | 8976219 | 2006-02-09 20:15:48 +0000 | [diff] [blame] | 48 | cl::opt<unsigned> |
| 49 | Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), |
| 50 | cl::init(10), cl::Hidden); |
| 51 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 52 | class LoopUnswitch : public FunctionPass { |
| 53 | LoopInfo *LI; // Loop information |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 54 | public: |
| 55 | virtual bool runOnFunction(Function &F); |
| 56 | bool visitLoop(Loop *L); |
| 57 | |
| 58 | /// This transformation requires natural loop information & requires that |
| 59 | /// loop preheaders be inserted into the CFG... |
| 60 | /// |
| 61 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 62 | AU.addRequiredID(LoopSimplifyID); |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 63 | AU.addPreservedID(LoopSimplifyID); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 64 | AU.addRequired<LoopInfo>(); |
| 65 | AU.addPreserved<LoopInfo>(); |
| 66 | } |
| 67 | |
| 68 | private: |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 69 | unsigned getLoopUnswitchCost(Loop *L, Value *LIC); |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 70 | void VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 71 | BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 72 | void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val); |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 73 | void UnswitchTrivialCondition(Loop *L, Value *Cond, bool EntersLoopOnCond, |
| 74 | BasicBlock *ExitBlock); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 75 | }; |
| 76 | RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops"); |
| 77 | } |
| 78 | |
Jeff Cohen | eca0d0f | 2005-01-06 05:47:18 +0000 | [diff] [blame] | 79 | FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 80 | |
| 81 | bool LoopUnswitch::runOnFunction(Function &F) { |
| 82 | bool Changed = false; |
| 83 | LI = &getAnalysis<LoopInfo>(); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 84 | |
| 85 | // Transform all the top-level loops. Copy the loop list so that the child |
| 86 | // can update the loop tree if it needs to delete the loop. |
| 87 | std::vector<Loop*> SubLoops(LI->begin(), LI->end()); |
| 88 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 89 | Changed |= visitLoop(SubLoops[i]); |
| 90 | |
| 91 | return Changed; |
| 92 | } |
| 93 | |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 94 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 95 | /// LoopValuesUsedOutsideLoop - Return true if there are any values defined in |
| 96 | /// the loop that are used by instructions outside of it. |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 97 | static bool LoopValuesUsedOutsideLoop(Loop *L) { |
| 98 | // We will be doing lots of "loop contains block" queries. Loop::contains is |
| 99 | // linear time, use a set to speed this up. |
| 100 | std::set<BasicBlock*> LoopBlocks; |
| 101 | |
| 102 | for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); |
| 103 | BB != E; ++BB) |
| 104 | LoopBlocks.insert(*BB); |
| 105 | |
| 106 | for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); |
| 107 | BB != E; ++BB) { |
| 108 | for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I) |
| 109 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; |
| 110 | ++UI) { |
| 111 | BasicBlock *UserBB = cast<Instruction>(*UI)->getParent(); |
| 112 | if (!LoopBlocks.count(UserBB)) |
| 113 | return true; |
| 114 | } |
| 115 | } |
| 116 | return false; |
| 117 | } |
| 118 | |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 119 | /// FindTrivialLoopExitBlock - We know that we have a branch from the loop |
| 120 | /// header to the specified latch block. See if one of the successors of the |
| 121 | /// latch block is an exit, and if so what block it is. |
| 122 | static BasicBlock *FindTrivialLoopExitBlock(Loop *L, BasicBlock *Latch) { |
| 123 | BasicBlock *Header = L->getHeader(); |
| 124 | BranchInst *LatchBranch = dyn_cast<BranchInst>(Latch->getTerminator()); |
| 125 | if (!LatchBranch || !LatchBranch->isConditional()) return 0; |
| 126 | |
| 127 | // Simple case, the latch block is a conditional branch. The target that |
| 128 | // doesn't go to the loop header is our block if it is not in the loop. |
| 129 | if (LatchBranch->getSuccessor(0) == Header) { |
| 130 | if (L->contains(LatchBranch->getSuccessor(1))) return false; |
| 131 | return LatchBranch->getSuccessor(1); |
| 132 | } else { |
| 133 | assert(LatchBranch->getSuccessor(1) == Header); |
| 134 | if (L->contains(LatchBranch->getSuccessor(0))) return false; |
| 135 | return LatchBranch->getSuccessor(0); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 140 | /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is |
| 141 | /// trivial: that is, that the condition controls whether or not the loop does |
| 142 | /// anything at all. If this is a trivial condition, unswitching produces no |
| 143 | /// code duplications (equivalently, it produces a simpler loop and a new empty |
| 144 | /// loop, which gets deleted). |
| 145 | /// |
| 146 | /// If this is a trivial condition, return ConstantBool::True if the loop body |
| 147 | /// runs when the condition is true, False if the loop body executes when the |
| 148 | /// condition is false. Otherwise, return null to indicate a complex condition. |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 149 | static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, |
| 150 | bool *CondEntersLoop = 0, |
| 151 | BasicBlock **LoopExit = 0) { |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 152 | BasicBlock *Header = L->getHeader(); |
| 153 | BranchInst *HeaderTerm = dyn_cast<BranchInst>(Header->getTerminator()); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 154 | |
| 155 | // If the header block doesn't end with a conditional branch on Cond, we can't |
| 156 | // handle it. |
| 157 | if (!HeaderTerm || !HeaderTerm->isConditional() || |
| 158 | HeaderTerm->getCondition() != Cond) |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 159 | return false; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 160 | |
| 161 | // Check to see if the conditional branch goes to the latch block. If not, |
| 162 | // it's not trivial. This also determines the value of Cond that will execute |
| 163 | // the loop. |
| 164 | BasicBlock *Latch = L->getLoopLatch(); |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 165 | if (HeaderTerm->getSuccessor(1) == Latch) { |
| 166 | if (CondEntersLoop) *CondEntersLoop = true; |
| 167 | } else if (HeaderTerm->getSuccessor(0) == Latch) |
| 168 | if (CondEntersLoop) *CondEntersLoop = false; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 169 | else |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 170 | return false; // Doesn't branch to latch block. |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 171 | |
| 172 | // The latch block must end with a conditional branch where one edge goes to |
| 173 | // the header (this much we know) and one edge goes OUT of the loop. |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 174 | BasicBlock *LoopExitBlock = FindTrivialLoopExitBlock(L, Latch); |
| 175 | if (!LoopExitBlock) return 0; |
| 176 | if (LoopExit) *LoopExit = LoopExitBlock; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 177 | |
| 178 | // We already know that nothing uses any scalar values defined inside of this |
| 179 | // loop. As such, we just have to check to see if this loop will execute any |
| 180 | // side-effecting instructions (e.g. stores, calls, volatile loads) in the |
| 181 | // part of the loop that the code *would* execute. |
| 182 | for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I) |
| 183 | if (I->mayWriteToMemory()) |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 184 | return false; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 185 | for (BasicBlock::iterator I = Latch->begin(), E = Latch->end(); I != E; ++I) |
| 186 | if (I->mayWriteToMemory()) |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 187 | return false; |
| 188 | return true; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 189 | } |
| 190 | |
| 191 | /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if |
| 192 | /// we choose to unswitch the specified loop on the specified value. |
| 193 | /// |
| 194 | unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) { |
| 195 | // If the condition is trivial, always unswitch. There is no code growth for |
| 196 | // this case. |
| 197 | if (IsTrivialUnswitchCondition(L, LIC)) |
| 198 | return 0; |
| 199 | |
| 200 | unsigned Cost = 0; |
| 201 | // FIXME: this is brain dead. It should take into consideration code |
| 202 | // shrinkage. |
| 203 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 204 | I != E; ++I) { |
| 205 | BasicBlock *BB = *I; |
| 206 | // Do not include empty blocks in the cost calculation. This happen due to |
| 207 | // loop canonicalization and will be removed. |
| 208 | if (BB->begin() == BasicBlock::iterator(BB->getTerminator())) |
| 209 | continue; |
| 210 | |
| 211 | // Count basic blocks. |
| 212 | ++Cost; |
| 213 | } |
| 214 | |
| 215 | return Cost; |
| 216 | } |
| 217 | |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 218 | /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is |
| 219 | /// invariant in the loop, or has an invariant piece, return the invariant. |
| 220 | /// Otherwise, return null. |
| 221 | static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) { |
| 222 | // Constants should be folded, not unswitched on! |
| 223 | if (isa<Constant>(Cond)) return false; |
| 224 | |
| 225 | // TODO: Handle: br (VARIANT|INVARIANT). |
| 226 | // TODO: Hoist simple expressions out of loops. |
| 227 | if (L->isLoopInvariant(Cond)) return Cond; |
| 228 | |
| 229 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond)) |
| 230 | if (BO->getOpcode() == Instruction::And || |
| 231 | BO->getOpcode() == Instruction::Or) { |
| 232 | // If either the left or right side is invariant, we can unswitch on this, |
| 233 | // which will cause the branch to go away in one loop and the condition to |
| 234 | // simplify in the other one. |
| 235 | if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed)) |
| 236 | return LHS; |
| 237 | if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed)) |
| 238 | return RHS; |
| 239 | } |
| 240 | |
| 241 | return 0; |
| 242 | } |
| 243 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 244 | bool LoopUnswitch::visitLoop(Loop *L) { |
| 245 | bool Changed = false; |
| 246 | |
| 247 | // Recurse through all subloops before we process this loop. Copy the loop |
| 248 | // list so that the child can update the loop tree if it needs to delete the |
| 249 | // loop. |
| 250 | std::vector<Loop*> SubLoops(L->begin(), L->end()); |
| 251 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 252 | Changed |= visitLoop(SubLoops[i]); |
| 253 | |
| 254 | // Loop over all of the basic blocks in the loop. If we find an interior |
| 255 | // block that is branching on a loop-invariant condition, we can unswitch this |
| 256 | // loop. |
| 257 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 258 | I != E; ++I) { |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame^] | 259 | for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); |
| 260 | BBI != E; ++BBI) |
| 261 | if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) { |
| 262 | Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed); |
| 263 | if (LoopCond == 0) continue; |
| 264 | |
| 265 | //if (UnswitchIfProfitable(LoopCond, |
| 266 | std::cerr << "LOOP INVARIANT SELECT: " << *SI; |
| 267 | } |
| 268 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 269 | TerminatorInst *TI = (*I)->getTerminator(); |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 270 | // FIXME: Handle invariant select instructions. |
| 271 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 272 | if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 273 | if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition())) |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 274 | DEBUG(std::cerr << "TODO: Implement unswitching 'switch' loop %" |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 275 | << L->getHeader()->getName() << ", cost = " |
| 276 | << L->getBlocks().size() << "\n" << **I); |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 277 | continue; |
| 278 | } |
| 279 | |
| 280 | BranchInst *BI = dyn_cast<BranchInst>(TI); |
| 281 | if (!BI) continue; |
| 282 | |
| 283 | // If this isn't branching on an invariant condition, we can't unswitch it. |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 284 | if (!BI->isConditional()) |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 285 | continue; |
| 286 | |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 287 | // See if this, or some part of it, is loop invariant. If so, we can |
| 288 | // unswitch on it if we desire. |
| 289 | Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed); |
| 290 | if (LoopCond == 0) continue; |
| 291 | |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 292 | // Check to see if it would be profitable to unswitch this loop. |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 293 | if (getLoopUnswitchCost(L, LoopCond) > Threshold) { |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 294 | // FIXME: this should estimate growth by the amount of code shared by the |
| 295 | // resultant unswitched loops. This should have no code growth: |
| 296 | // for () { if (iv) {...} } |
| 297 | // as one copy of the loop will be empty. |
| 298 | // |
| 299 | DEBUG(std::cerr << "NOT unswitching loop %" |
| 300 | << L->getHeader()->getName() << ", cost too high: " |
| 301 | << L->getBlocks().size() << "\n"); |
| 302 | continue; |
| 303 | } |
| 304 | |
| 305 | // If this loop has live-out values, we can't unswitch it. We need something |
| 306 | // like loop-closed SSA form in order to know how to insert PHI nodes for |
| 307 | // these values. |
| 308 | if (LoopValuesUsedOutsideLoop(L)) { |
| 309 | DEBUG(std::cerr << "NOT unswitching loop %" |
| 310 | << L->getHeader()->getName() |
| 311 | << ", a loop value is used outside loop!\n"); |
| 312 | continue; |
| 313 | } |
| 314 | |
| 315 | //std::cerr << "BEFORE:\n"; LI->dump(); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 316 | Loop *NewLoop1 = 0, *NewLoop2 = 0; |
| 317 | |
| 318 | // If this is a trivial condition to unswitch (which results in no code |
| 319 | // duplication), do it now. |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 320 | bool EntersLoopOnCond; |
| 321 | BasicBlock *ExitBlock; |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 322 | if (IsTrivialUnswitchCondition(L, LoopCond, &EntersLoopOnCond, &ExitBlock)){ |
| 323 | UnswitchTrivialCondition(L, LoopCond, EntersLoopOnCond, ExitBlock); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 324 | NewLoop1 = L; |
| 325 | } else { |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 326 | VersionLoop(LoopCond, L, NewLoop1, NewLoop2); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 327 | } |
| 328 | |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 329 | //std::cerr << "AFTER:\n"; LI->dump(); |
| 330 | |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 331 | // Try to unswitch each of our new loops now! |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 332 | if (NewLoop1) visitLoop(NewLoop1); |
| 333 | if (NewLoop2) visitLoop(NewLoop2); |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 334 | return true; |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 335 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 336 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 337 | return Changed; |
| 338 | } |
| 339 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 340 | BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) { |
| 341 | TerminatorInst *LatchTerm = BB->getTerminator(); |
| 342 | unsigned SuccNum = 0; |
| 343 | for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) { |
| 344 | assert(i != e && "Didn't find edge?"); |
| 345 | if (LatchTerm->getSuccessor(i) == Succ) { |
| 346 | SuccNum = i; |
| 347 | break; |
| 348 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 349 | } |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 350 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 351 | // If this is a critical edge, let SplitCriticalEdge do it. |
| 352 | if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this)) |
| 353 | return LatchTerm->getSuccessor(SuccNum); |
| 354 | |
| 355 | // If the edge isn't critical, then BB has a single successor or Succ has a |
| 356 | // single pred. Split the block. |
| 357 | BasicBlock *BlockToSplit; |
| 358 | BasicBlock::iterator SplitPoint; |
| 359 | if (BasicBlock *SP = Succ->getSinglePredecessor()) { |
| 360 | // If the successor only has a single pred, split the top of the successor |
| 361 | // block. |
| 362 | assert(SP == BB && "CFG broken"); |
| 363 | BlockToSplit = Succ; |
| 364 | SplitPoint = Succ->begin(); |
| 365 | } else { |
| 366 | // Otherwise, if BB has a single successor, split it at the bottom of the |
| 367 | // block. |
| 368 | assert(BB->getTerminator()->getNumSuccessors() == 1 && |
| 369 | "Should have a single succ!"); |
| 370 | BlockToSplit = BB; |
| 371 | SplitPoint = BB->getTerminator(); |
| 372 | } |
| 373 | |
| 374 | BasicBlock *New = |
| 375 | BlockToSplit->splitBasicBlock(SplitPoint, |
| 376 | BlockToSplit->getName()+".tail"); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 377 | // New now lives in whichever loop that BB used to. |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 378 | if (Loop *L = LI->getLoopFor(BlockToSplit)) |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 379 | L->addBasicBlockToLoop(New, *LI); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 380 | return New; |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 381 | } |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 382 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 383 | |
| 384 | |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 385 | // RemapInstruction - Convert the instruction operands from referencing the |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 386 | // current values into those specified by ValueMap. |
| 387 | // |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 388 | static inline void RemapInstruction(Instruction *I, |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 389 | std::map<const Value *, Value*> &ValueMap) { |
| 390 | for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { |
| 391 | Value *Op = I->getOperand(op); |
| 392 | std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); |
| 393 | if (It != ValueMap.end()) Op = It->second; |
| 394 | I->setOperand(op, Op); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | /// CloneLoop - Recursively clone the specified loop and all of its children, |
| 399 | /// mapping the blocks with the specified map. |
| 400 | static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM, |
| 401 | LoopInfo *LI) { |
| 402 | Loop *New = new Loop(); |
| 403 | |
| 404 | if (PL) |
| 405 | PL->addChildLoop(New); |
| 406 | else |
| 407 | LI->addTopLevelLoop(New); |
| 408 | |
| 409 | // Add all of the blocks in L to the new loop. |
| 410 | for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); |
| 411 | I != E; ++I) |
| 412 | if (LI->getLoopFor(*I) == L) |
| 413 | New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI); |
| 414 | |
| 415 | // Add all of the subloops to the new loop. |
| 416 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 417 | CloneLoop(*I, New, VM, LI); |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 418 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 419 | return New; |
| 420 | } |
| 421 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 422 | /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable |
| 423 | /// condition in it (a cond branch from its header block to its latch block, |
| 424 | /// where the path through the loop that doesn't execute its body has no |
| 425 | /// side-effects), unswitch it. This doesn't involve any code duplication, just |
| 426 | /// moving the conditional branch outside of the loop and updating loop info. |
| 427 | void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 428 | bool EnterOnCond, |
| 429 | BasicBlock *ExitBlock) { |
Chris Lattner | 3fc3148 | 2006-02-10 01:36:35 +0000 | [diff] [blame] | 430 | DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %" |
| 431 | << L->getHeader()->getName() << " [" << L->getBlocks().size() |
| 432 | << " blocks] in Function " << L->getHeader()->getParent()->getName() |
| 433 | << " on cond:" << *Cond << "\n"); |
| 434 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 435 | // First step, split the preheader, so that we know that there is a safe place |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 436 | // to insert the conditional branch. We will change 'OrigPH' to have a |
| 437 | // conditional branch on Cond. |
| 438 | BasicBlock *OrigPH = L->getLoopPreheader(); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 439 | BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader()); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 440 | |
| 441 | // Now that we have a place to insert the conditional branch, create a place |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 442 | // to branch to: this is the exit block out of the loop that we should |
| 443 | // short-circuit to. |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 444 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 445 | // Split this edge now, so that the loop maintains its exit block. |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 446 | assert(!L->contains(ExitBlock) && "Exit block is in the loop?"); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 447 | BasicBlock *NewExit = SplitEdge(L->getLoopLatch(), ExitBlock); |
| 448 | assert(NewExit != ExitBlock && "Edge not split!"); |
| 449 | |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 450 | // Okay, now we have a position to branch from and a position to branch to, |
| 451 | // insert the new conditional branch. |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 452 | new BranchInst(EnterOnCond ? NewPH : NewExit, EnterOnCond ? NewExit : NewPH, |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 453 | Cond, OrigPH->getTerminator()); |
| 454 | OrigPH->getTerminator()->eraseFromParent(); |
| 455 | |
| 456 | // Now that we know that the loop is never entered when this condition is a |
| 457 | // particular value, rewrite the loop with this info. We know that this will |
| 458 | // at least eliminate the old branch. |
Chris Lattner | 4935417 | 2006-02-10 02:01:22 +0000 | [diff] [blame] | 459 | RewriteLoopBodyWithConditionConstant(L, Cond, EnterOnCond); |
Chris Lattner | 3fc3148 | 2006-02-10 01:36:35 +0000 | [diff] [blame] | 460 | |
| 461 | ++NumUnswitched; |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 462 | } |
| 463 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 464 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 465 | /// VersionLoop - We determined that the loop is profitable to unswitch and |
| 466 | /// contains a branch on a loop invariant condition. Split it into loop |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 467 | /// versions and test the condition outside of either loop. Return the loops |
| 468 | /// created as Out1/Out2. |
| 469 | void LoopUnswitch::VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2) { |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 470 | Function *F = L->getHeader()->getParent(); |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 471 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 472 | DEBUG(std::cerr << "loop-unswitch: Unswitching loop %" |
| 473 | << L->getHeader()->getName() << " [" << L->getBlocks().size() |
| 474 | << " blocks] in Function " << F->getName() |
| 475 | << " on cond:" << *LIC << "\n"); |
| 476 | |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 477 | // LoopBlocks contains all of the basic blocks of the loop, including the |
| 478 | // preheader of the loop, the body of the loop, and the exit blocks of the |
| 479 | // loop, in that order. |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 480 | std::vector<BasicBlock*> LoopBlocks; |
| 481 | |
| 482 | // First step, split the preheader and exit blocks, and add these blocks to |
| 483 | // the LoopBlocks list. |
| 484 | BasicBlock *OrigPreheader = L->getLoopPreheader(); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 485 | LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader())); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 486 | |
| 487 | // We want the loop to come after the preheader, but before the exit blocks. |
| 488 | LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end()); |
| 489 | |
| 490 | std::vector<BasicBlock*> ExitBlocks; |
| 491 | L->getExitBlocks(ExitBlocks); |
| 492 | std::sort(ExitBlocks.begin(), ExitBlocks.end()); |
| 493 | ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()), |
| 494 | ExitBlocks.end()); |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 495 | // Split all of the edges from inside the loop to their exit blocks. This |
| 496 | // unswitching trivial: no phi nodes to update. |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 497 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 498 | BasicBlock *ExitBlock = ExitBlocks[i]; |
| 499 | std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock)); |
| 500 | |
| 501 | for (unsigned j = 0, e = Preds.size(); j != e; ++j) { |
| 502 | assert(L->contains(Preds[j]) && |
| 503 | "All preds of loop exit blocks must be the same loop!"); |
| 504 | SplitEdge(Preds[j], ExitBlock); |
| 505 | } |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 506 | } |
Chris Lattner | fe4151e | 2006-02-10 23:16:39 +0000 | [diff] [blame] | 507 | |
| 508 | // The exit blocks may have been changed due to edge splitting, recompute. |
| 509 | ExitBlocks.clear(); |
| 510 | L->getExitBlocks(ExitBlocks); |
| 511 | std::sort(ExitBlocks.begin(), ExitBlocks.end()); |
| 512 | ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()), |
| 513 | ExitBlocks.end()); |
| 514 | |
| 515 | // Add exit blocks to the loop blocks. |
| 516 | LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end()); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 517 | |
| 518 | // Next step, clone all of the basic blocks that make up the loop (including |
| 519 | // the loop preheader and exit blocks), keeping track of the mapping between |
| 520 | // the instructions and blocks. |
| 521 | std::vector<BasicBlock*> NewBlocks; |
| 522 | NewBlocks.reserve(LoopBlocks.size()); |
| 523 | std::map<const Value*, Value*> ValueMap; |
| 524 | for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) { |
| 525 | NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F)); |
| 526 | ValueMap[LoopBlocks[i]] = NewBlocks.back(); // Keep the BB mapping. |
| 527 | } |
| 528 | |
| 529 | // Splice the newly inserted blocks into the function right before the |
| 530 | // original preheader. |
| 531 | F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(), |
| 532 | NewBlocks[0], F->end()); |
| 533 | |
| 534 | // Now we create the new Loop object for the versioned loop. |
| 535 | Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI); |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame^] | 536 | Loop *ParentLoop = L->getParentLoop(); |
| 537 | if (ParentLoop) { |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 538 | // Make sure to add the cloned preheader and exit blocks to the parent loop |
| 539 | // as well. |
Chris Lattner | f1b1516 | 2006-02-10 23:26:14 +0000 | [diff] [blame^] | 540 | ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI); |
| 541 | } |
| 542 | |
| 543 | for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { |
| 544 | BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]); |
| 545 | if (ParentLoop) |
| 546 | ParentLoop->addBasicBlockToLoop(cast<BasicBlock>(NewExit), *LI); |
| 547 | |
| 548 | assert(NewExit->getTerminator()->getNumSuccessors() == 1 && |
| 549 | "Exit block should have been split to have one successor!"); |
| 550 | BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0); |
| 551 | |
| 552 | // If the successor of the exit block had PHI nodes, add an entry for |
| 553 | // NewExit. |
| 554 | PHINode *PN; |
| 555 | for (BasicBlock::iterator I = ExitSucc->begin(); |
| 556 | (PN = dyn_cast<PHINode>(I)); ++I) { |
| 557 | Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]); |
| 558 | std::map<const Value *, Value*>::iterator It = ValueMap.find(V); |
| 559 | if (It != ValueMap.end()) V = It->second; |
| 560 | PN->addIncoming(V, NewExit); |
| 561 | } |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 562 | } |
| 563 | |
| 564 | // Rewrite the code to refer to itself. |
| 565 | for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) |
| 566 | for (BasicBlock::iterator I = NewBlocks[i]->begin(), |
| 567 | E = NewBlocks[i]->end(); I != E; ++I) |
| 568 | RemapInstruction(I, ValueMap); |
Chris Lattner | 2826e05 | 2006-02-09 19:14:52 +0000 | [diff] [blame] | 569 | |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 570 | // Rewrite the original preheader to select between versions of the loop. |
| 571 | assert(isa<BranchInst>(OrigPreheader->getTerminator()) && |
| 572 | cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() && |
| 573 | OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] && |
| 574 | "Preheader splitting did not work correctly!"); |
| 575 | // Remove the unconditional branch to LoopBlocks[0]. |
| 576 | OrigPreheader->getInstList().pop_back(); |
| 577 | |
| 578 | // Insert a conditional branch on LIC to the two preheaders. The original |
| 579 | // code is the true version and the new code is the false version. |
| 580 | new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader); |
| 581 | |
| 582 | // Now we rewrite the original code to know that the condition is true and the |
| 583 | // new code to know that the condition is false. |
| 584 | RewriteLoopBodyWithConditionConstant(L, LIC, true); |
| 585 | RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false); |
| 586 | ++NumUnswitched; |
Chris Lattner | 4f0e66d | 2006-02-09 22:15:42 +0000 | [diff] [blame] | 587 | Out1 = L; |
| 588 | Out2 = NewLoop; |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 589 | } |
| 590 | |
| 591 | // RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has |
| 592 | // the value specified by Val in the specified loop. Rewrite any uses of LIC or |
| 593 | // of properties correlated to it. |
| 594 | void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, |
| 595 | bool Val) { |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 596 | assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 597 | // FIXME: Support correlated properties, like: |
| 598 | // for (...) |
| 599 | // if (li1 < li2) |
| 600 | // ... |
| 601 | // if (li1 > li2) |
| 602 | // ... |
| 603 | ConstantBool *BoolVal = ConstantBool::get(Val); |
| 604 | |
Chris Lattner | 6e26315 | 2006-02-10 02:30:37 +0000 | [diff] [blame] | 605 | // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches, |
| 606 | // selects, switches. |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 607 | std::vector<User*> Users(LIC->use_begin(), LIC->use_end()); |
| 608 | for (unsigned i = 0, e = Users.size(); i != e; ++i) |
Chris Lattner | ed7a67b | 2006-02-10 01:24:09 +0000 | [diff] [blame] | 609 | if (Instruction *U = cast<Instruction>(Users[i])) |
Chris Lattner | f48f777 | 2004-04-19 18:07:02 +0000 | [diff] [blame] | 610 | if (L->contains(U->getParent())) |
| 611 | U->replaceUsesOfWith(LIC, BoolVal); |
| 612 | } |