blob: 95217254bd434e57356491ce8ae6ac78173e4ec1 [file] [log] [blame]
Chris Lattner18f16092004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner18f16092004-04-19 18:07:02 +00003// 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 Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner18f16092004-04-19 18:07:02 +00008//===----------------------------------------------------------------------===//
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 Lattner18f16092004-04-19 18:07:02 +000034#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/Transforms/Utils/Cloning.h"
36#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81be2e92006-02-10 19:08:15 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000038#include "llvm/ADT/Statistic.h"
Chris Lattnera6fc94b2006-02-18 07:57:38 +000039#include "llvm/ADT/PostOrderIterator.h"
Chris Lattnere487abb2006-02-09 20:15:48 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/CommandLine.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000042#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000043#include <iostream>
Chris Lattner2f4b8982006-02-09 19:14:52 +000044#include <set>
Chris Lattner18f16092004-04-19 18:07:02 +000045using namespace llvm;
46
47namespace {
Chris Lattner3dd4c402006-02-14 01:01:41 +000048 Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
49 Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
50 Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
51 Statistic<> NumTrivial ("loop-unswitch",
52 "Number of unswitches that are trivial");
Chris Lattner52221f72006-02-17 00:31:07 +000053 Statistic<> NumSimplify("loop-unswitch",
54 "Number of simplifications of unswitched code");
Chris Lattnere487abb2006-02-09 20:15:48 +000055 cl::opt<unsigned>
56 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
57 cl::init(10), cl::Hidden);
58
Chris Lattner18f16092004-04-19 18:07:02 +000059 class LoopUnswitch : public FunctionPass {
60 LoopInfo *LI; // Loop information
Chris Lattnera6fc94b2006-02-18 07:57:38 +000061
62 // LoopProcessWorklist - List of loops we need to process.
63 std::vector<Loop*> LoopProcessWorklist;
Chris Lattner18f16092004-04-19 18:07:02 +000064 public:
65 virtual bool runOnFunction(Function &F);
66 bool visitLoop(Loop *L);
67
68 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
70 ///
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf4f5f4e2006-02-09 22:15:42 +000073 AU.addPreservedID(LoopSimplifyID);
Chris Lattner18f16092004-04-19 18:07:02 +000074 AU.addRequired<LoopInfo>();
75 AU.addPreserved<LoopInfo>();
Owen Anderson6edf3992006-06-12 21:49:21 +000076 AU.addRequiredID(LCSSAID);
77 AU.addPreservedID(LCSSAID);
Chris Lattner18f16092004-04-19 18:07:02 +000078 }
79
80 private:
Chris Lattnera6fc94b2006-02-18 07:57:38 +000081 /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
82 /// remove it.
83 void RemoveLoopFromWorklist(Loop *L) {
84 std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
85 LoopProcessWorklist.end(), L);
86 if (I != LoopProcessWorklist.end())
87 LoopProcessWorklist.erase(I);
88 }
89
Chris Lattnerc2358092006-02-11 00:43:37 +000090 bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
Chris Lattner4c41d492006-02-10 01:24:09 +000091 unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
Chris Lattnerf4412d82006-02-18 01:27:45 +000092 void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +000093 BasicBlock *ExitBlock);
Chris Lattnera6fc94b2006-02-18 07:57:38 +000094 void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
Chris Lattnerb2bc3152006-02-10 23:16:39 +000095 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
Chris Lattner4e132392006-02-15 22:03:36 +000096 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
Chris Lattnera6fc94b2006-02-18 07:57:38 +000097
98 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
99 Constant *Val, bool isEqual);
100
101 void SimplifyCode(std::vector<Instruction*> &Worklist);
Chris Lattnerdb410242006-02-18 02:42:34 +0000102 void RemoveBlockIfDead(BasicBlock *BB,
103 std::vector<Instruction*> &Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000104 void RemoveLoopFromHierarchy(Loop *L);
Chris Lattner18f16092004-04-19 18:07:02 +0000105 };
Chris Lattner7f8897f2006-08-27 22:42:52 +0000106 RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
Chris Lattner18f16092004-04-19 18:07:02 +0000107}
108
Jeff Cohenf5e58f82005-01-06 05:47:18 +0000109FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattner18f16092004-04-19 18:07:02 +0000110
111bool LoopUnswitch::runOnFunction(Function &F) {
112 bool Changed = false;
113 LI = &getAnalysis<LoopInfo>();
Chris Lattner18f16092004-04-19 18:07:02 +0000114
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000115 // Populate the worklist of loops to process in post-order.
116 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
117 for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
118 LoopProcessWorklist.push_back(*LI);
Chris Lattner18f16092004-04-19 18:07:02 +0000119
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000120 // Process the loops in worklist order, this is a post-order visitation of
121 // the loops. We use a worklist of loops so that loops can be removed at any
122 // time if they are deleted (e.g. the backedge of a loop is removed).
123 while (!LoopProcessWorklist.empty()) {
124 Loop *L = LoopProcessWorklist.back();
125 LoopProcessWorklist.pop_back();
126 Changed |= visitLoop(L);
127 }
128
129 return Changed;
130}
131
132/// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
133/// invariant in the loop, or has an invariant piece, return the invariant.
134/// Otherwise, return null.
135static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
136 // Constants should be folded, not unswitched on!
137 if (isa<Constant>(Cond)) return false;
138
139 // TODO: Handle: br (VARIANT|INVARIANT).
140 // TODO: Hoist simple expressions out of loops.
141 if (L->isLoopInvariant(Cond)) return Cond;
142
143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
144 if (BO->getOpcode() == Instruction::And ||
145 BO->getOpcode() == Instruction::Or) {
146 // If either the left or right side is invariant, we can unswitch on this,
147 // which will cause the branch to go away in one loop and the condition to
148 // simplify in the other one.
149 if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
150 return LHS;
151 if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
152 return RHS;
153 }
154
155 return 0;
156}
157
158bool LoopUnswitch::visitLoop(Loop *L) {
Owen Anderson6edf3992006-06-12 21:49:21 +0000159 assert(L->isLCSSAForm());
160
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000161 bool Changed = false;
162
163 // Loop over all of the basic blocks in the loop. If we find an interior
164 // block that is branching on a loop-invariant condition, we can unswitch this
165 // loop.
166 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
167 I != E; ++I) {
168 TerminatorInst *TI = (*I)->getTerminator();
169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
170 // If this isn't branching on an invariant condition, we can't unswitch
171 // it.
172 if (BI->isConditional()) {
173 // See if this, or some part of it, is loop invariant. If so, we can
174 // unswitch on it if we desire.
175 Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
Chris Lattner47811b72006-09-28 23:35:22 +0000176 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::getTrue(),
177 L)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000178 ++NumBranches;
179 return true;
180 }
181 }
182 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
183 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
184 if (LoopCond && SI->getNumCases() > 1) {
185 // Find a value to unswitch on:
186 // FIXME: this should chose the most expensive case!
187 Constant *UnswitchVal = SI->getCaseValue(1);
188 if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
189 ++NumSwitches;
190 return true;
191 }
192 }
193 }
194
195 // Scan the instructions to check for unswitchable values.
196 for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
197 BBI != E; ++BBI)
198 if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
199 Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
Chris Lattner47811b72006-09-28 23:35:22 +0000200 if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::getTrue(),
201 L)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000202 ++NumSelects;
203 return true;
204 }
205 }
206 }
Owen Anderson6edf3992006-06-12 21:49:21 +0000207
208 assert(L->isLCSSAForm());
209
Chris Lattner18f16092004-04-19 18:07:02 +0000210 return Changed;
211}
212
Chris Lattner4e132392006-02-15 22:03:36 +0000213/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
214/// 1. Exit the loop with no side effects.
215/// 2. Branch to the latch block with no side-effects.
216///
217/// If these conditions are true, we return true and set ExitBB to the block we
218/// exit through.
219///
220static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
221 BasicBlock *&ExitBB,
222 std::set<BasicBlock*> &Visited) {
Chris Lattner0017d482006-02-17 06:39:56 +0000223 if (!Visited.insert(BB).second) {
224 // Already visited and Ok, end of recursion.
225 return true;
226 } else if (!L->contains(BB)) {
227 // Otherwise, this is a loop exit, this is fine so long as this is the
228 // first exit.
229 if (ExitBB != 0) return false;
230 ExitBB = BB;
231 return true;
232 }
233
234 // Otherwise, this is an unvisited intra-loop node. Check all successors.
Chris Lattner4e132392006-02-15 22:03:36 +0000235 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
Chris Lattner0017d482006-02-17 06:39:56 +0000236 // Check to see if the successor is a trivial loop exit.
237 if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
238 return false;
Chris Lattner708e1a52006-02-10 02:30:37 +0000239 }
Chris Lattner4e132392006-02-15 22:03:36 +0000240
241 // Okay, everything after this looks good, check to make sure that this block
242 // doesn't include any side effects.
Chris Lattnera48654e2006-02-15 22:52:05 +0000243 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner4e132392006-02-15 22:03:36 +0000244 if (I->mayWriteToMemory())
245 return false;
246
247 return true;
Chris Lattner708e1a52006-02-10 02:30:37 +0000248}
249
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000250/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
251/// leads to an exit from the specified loop, and has no side-effects in the
252/// process. If so, return the block that is exited to, otherwise return null.
Chris Lattner4e132392006-02-15 22:03:36 +0000253static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
254 std::set<BasicBlock*> Visited;
255 Visited.insert(L->getHeader()); // Branches to header are ok.
Chris Lattner4e132392006-02-15 22:03:36 +0000256 BasicBlock *ExitBB = 0;
257 if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
258 return ExitBB;
259 return 0;
260}
Chris Lattner708e1a52006-02-10 02:30:37 +0000261
Chris Lattner4c41d492006-02-10 01:24:09 +0000262/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
263/// trivial: that is, that the condition controls whether or not the loop does
264/// anything at all. If this is a trivial condition, unswitching produces no
265/// code duplications (equivalently, it produces a simpler loop and a new empty
266/// loop, which gets deleted).
267///
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000268/// If this is a trivial condition, return true, otherwise return false. When
269/// returning true, this sets Cond and Val to the condition that controls the
270/// trivial condition: when Cond dynamically equals Val, the loop is known to
271/// exit. Finally, this sets LoopExit to the BB that the loop exits to when
272/// Cond == Val.
273///
274static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000275 BasicBlock **LoopExit = 0) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000276 BasicBlock *Header = L->getHeader();
Chris Lattnera48654e2006-02-15 22:52:05 +0000277 TerminatorInst *HeaderTerm = Header->getTerminator();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000278
Chris Lattnera48654e2006-02-15 22:52:05 +0000279 BasicBlock *LoopExitBB = 0;
280 if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
281 // If the header block doesn't end with a conditional branch on Cond, we
282 // can't handle it.
283 if (!BI->isConditional() || BI->getCondition() != Cond)
284 return false;
Chris Lattner4c41d492006-02-10 01:24:09 +0000285
Chris Lattnera48654e2006-02-15 22:52:05 +0000286 // Check to see if a successor of the branch is guaranteed to go to the
287 // latch block or exit through a one exit block without having any
288 // side-effects. If so, determine the value of Cond that causes it to do
289 // this.
290 if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
Chris Lattner47811b72006-09-28 23:35:22 +0000291 if (Val) *Val = ConstantBool::getTrue();
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000292 } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
Chris Lattner47811b72006-09-28 23:35:22 +0000293 if (Val) *Val = ConstantBool::getFalse();
Chris Lattnera48654e2006-02-15 22:52:05 +0000294 }
295 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
296 // If this isn't a switch on Cond, we can't handle it.
297 if (SI->getCondition() != Cond) return false;
298
299 // Check to see if a successor of the switch is guaranteed to go to the
300 // latch block or exit through a one exit block without having any
301 // side-effects. If so, determine the value of Cond that causes it to do
302 // this. Note that we can't trivially unswitch on the default case.
303 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
304 if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
305 // Okay, we found a trivial case, remember the value that is trivial.
306 if (Val) *Val = SI->getCaseValue(i);
Chris Lattnera48654e2006-02-15 22:52:05 +0000307 break;
308 }
Chris Lattner4e132392006-02-15 22:03:36 +0000309 }
310
Chris Lattnerf8bf1162006-02-22 23:55:00 +0000311 // If we didn't find a single unique LoopExit block, or if the loop exit block
312 // contains phi nodes, this isn't trivial.
313 if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
Chris Lattner4e132392006-02-15 22:03:36 +0000314 return false; // Can't handle this.
Chris Lattner4c41d492006-02-10 01:24:09 +0000315
Chris Lattnera48654e2006-02-15 22:52:05 +0000316 if (LoopExit) *LoopExit = LoopExitBB;
Chris Lattner4c41d492006-02-10 01:24:09 +0000317
318 // We already know that nothing uses any scalar values defined inside of this
319 // loop. As such, we just have to check to see if this loop will execute any
320 // side-effecting instructions (e.g. stores, calls, volatile loads) in the
Chris Lattner4e132392006-02-15 22:03:36 +0000321 // part of the loop that the code *would* execute. We already checked the
322 // tail, check the header now.
Chris Lattner4c41d492006-02-10 01:24:09 +0000323 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
324 if (I->mayWriteToMemory())
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000325 return false;
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000326 return true;
Chris Lattner4c41d492006-02-10 01:24:09 +0000327}
328
329/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
330/// we choose to unswitch the specified loop on the specified value.
331///
332unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
333 // If the condition is trivial, always unswitch. There is no code growth for
334 // this case.
335 if (IsTrivialUnswitchCondition(L, LIC))
336 return 0;
337
Owen Anderson372994b2006-06-28 17:47:50 +0000338 // FIXME: This is really overly conservative. However, more liberal
339 // estimations have thus far resulted in excessive unswitching, which is bad
340 // both in compile time and in code size. This should be replaced once
341 // someone figures out how a good estimation.
342 return L->getBlocks().size();
Chris Lattnerdaa2bf92006-06-28 16:38:55 +0000343
Chris Lattner4c41d492006-02-10 01:24:09 +0000344 unsigned Cost = 0;
345 // FIXME: this is brain dead. It should take into consideration code
346 // shrinkage.
347 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
348 I != E; ++I) {
349 BasicBlock *BB = *I;
350 // Do not include empty blocks in the cost calculation. This happen due to
351 // loop canonicalization and will be removed.
352 if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
353 continue;
354
355 // Count basic blocks.
356 ++Cost;
357 }
358
359 return Cost;
360}
361
Chris Lattnerc2358092006-02-11 00:43:37 +0000362/// UnswitchIfProfitable - We have found that we can unswitch L when
363/// LoopCond == Val to simplify the loop. If we decide that this is profitable,
364/// unswitch the loop, reprocess the pieces, then return true.
365bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
366 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner0f862e52006-03-24 07:14:00 +0000367 unsigned Cost = getLoopUnswitchCost(L, LoopCond);
368 if (Cost > Threshold) {
Chris Lattnerc2358092006-02-11 00:43:37 +0000369 // FIXME: this should estimate growth by the amount of code shared by the
370 // resultant unswitched loops.
371 //
372 DEBUG(std::cerr << "NOT unswitching loop %"
373 << L->getHeader()->getName() << ", cost too high: "
374 << L->getBlocks().size() << "\n");
375 return false;
376 }
Owen Anderson2b67f072006-06-26 07:44:36 +0000377
Chris Lattnerc2358092006-02-11 00:43:37 +0000378 // If this is a trivial condition to unswitch (which results in no code
379 // duplication), do it now.
Chris Lattner6d9d13d2006-02-15 01:44:42 +0000380 Constant *CondVal;
Chris Lattnerc2358092006-02-11 00:43:37 +0000381 BasicBlock *ExitBlock;
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000382 if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
383 UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
Chris Lattnerc2358092006-02-11 00:43:37 +0000384 } else {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000385 UnswitchNontrivialCondition(LoopCond, Val, L);
Chris Lattnerc2358092006-02-11 00:43:37 +0000386 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000387
Chris Lattnerc2358092006-02-11 00:43:37 +0000388 return true;
389}
390
Chris Lattner4e132392006-02-15 22:03:36 +0000391/// SplitBlock - Split the specified block at the specified instruction - every
392/// thing before SplitPt stays in Old and everything starting with SplitPt moves
393/// to a new block. The two blocks are joined by an unconditional branch and
394/// the loop info is updated.
395///
396BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000397 BasicBlock::iterator SplitIt = SplitPt;
398 while (isa<PHINode>(SplitIt))
399 ++SplitIt;
400 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
Chris Lattner4e132392006-02-15 22:03:36 +0000401
402 // The new block lives in whichever loop the old one did.
403 if (Loop *L = LI->getLoopFor(Old))
404 L->addBasicBlockToLoop(New, *LI);
405
406 return New;
407}
408
409
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000410BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
411 TerminatorInst *LatchTerm = BB->getTerminator();
412 unsigned SuccNum = 0;
413 for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
414 assert(i != e && "Didn't find edge?");
415 if (LatchTerm->getSuccessor(i) == Succ) {
416 SuccNum = i;
417 break;
418 }
Chris Lattner18f16092004-04-19 18:07:02 +0000419 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000420
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000421 // If this is a critical edge, let SplitCriticalEdge do it.
422 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
423 return LatchTerm->getSuccessor(SuccNum);
424
425 // If the edge isn't critical, then BB has a single successor or Succ has a
426 // single pred. Split the block.
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000427 BasicBlock::iterator SplitPoint;
428 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
429 // If the successor only has a single pred, split the top of the successor
430 // block.
431 assert(SP == BB && "CFG broken");
Chris Lattner4e132392006-02-15 22:03:36 +0000432 return SplitBlock(Succ, Succ->begin());
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000433 } else {
434 // Otherwise, if BB has a single successor, split it at the bottom of the
435 // block.
436 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
437 "Should have a single succ!");
Chris Lattner4e132392006-02-15 22:03:36 +0000438 return SplitBlock(BB, BB->getTerminator());
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000439 }
Chris Lattner18f16092004-04-19 18:07:02 +0000440}
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000441
Chris Lattner18f16092004-04-19 18:07:02 +0000442
443
Misha Brukmanfd939082005-04-21 23:48:37 +0000444// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattner18f16092004-04-19 18:07:02 +0000445// current values into those specified by ValueMap.
446//
Misha Brukmanfd939082005-04-21 23:48:37 +0000447static inline void RemapInstruction(Instruction *I,
Chris Lattner18f16092004-04-19 18:07:02 +0000448 std::map<const Value *, Value*> &ValueMap) {
449 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
450 Value *Op = I->getOperand(op);
451 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
452 if (It != ValueMap.end()) Op = It->second;
453 I->setOperand(op, Op);
454 }
455}
456
457/// CloneLoop - Recursively clone the specified loop and all of its children,
458/// mapping the blocks with the specified map.
459static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
460 LoopInfo *LI) {
461 Loop *New = new Loop();
462
463 if (PL)
464 PL->addChildLoop(New);
465 else
466 LI->addTopLevelLoop(New);
467
468 // Add all of the blocks in L to the new loop.
469 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
470 I != E; ++I)
471 if (LI->getLoopFor(*I) == L)
472 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
473
474 // Add all of the subloops to the new loop.
475 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
476 CloneLoop(*I, New, VM, LI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000477
Chris Lattner18f16092004-04-19 18:07:02 +0000478 return New;
479}
480
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000481/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
482/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
483/// code immediately before InsertPt.
484static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
485 BasicBlock *TrueDest,
486 BasicBlock *FalseDest,
487 Instruction *InsertPt) {
488 // Insert a conditional branch on LIC to the two preheaders. The original
489 // code is the true version and the new code is the false version.
490 Value *BranchVal = LIC;
Chris Lattner3fdde112006-02-15 19:05:52 +0000491 if (!isa<ConstantBool>(Val)) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000492 BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
Chris Lattner47811b72006-09-28 23:35:22 +0000493 } else if (Val != ConstantBool::getTrue()) {
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000494 // We want to enter the new loop when the condition is true.
495 std::swap(TrueDest, FalseDest);
496 }
497
498 // Insert the new branch.
499 new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
500}
501
502
Chris Lattner4c41d492006-02-10 01:24:09 +0000503/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
504/// condition in it (a cond branch from its header block to its latch block,
505/// where the path through the loop that doesn't execute its body has no
506/// side-effects), unswitch it. This doesn't involve any code duplication, just
507/// moving the conditional branch outside of the loop and updating loop info.
508void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000509 Constant *Val,
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000510 BasicBlock *ExitBlock) {
Chris Lattner4d1ca942006-02-10 01:36:35 +0000511 DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
512 << L->getHeader()->getName() << " [" << L->getBlocks().size()
513 << " blocks] in Function " << L->getHeader()->getParent()->getName()
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000514 << " on cond: " << *Val << " == " << *Cond << "\n");
Chris Lattner4d1ca942006-02-10 01:36:35 +0000515
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000516 // First step, split the preheader, so that we know that there is a safe place
Chris Lattner4c41d492006-02-10 01:24:09 +0000517 // to insert the conditional branch. We will change 'OrigPH' to have a
518 // conditional branch on Cond.
519 BasicBlock *OrigPH = L->getLoopPreheader();
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000520 BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
Chris Lattner4c41d492006-02-10 01:24:09 +0000521
522 // Now that we have a place to insert the conditional branch, create a place
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000523 // to branch to: this is the exit block out of the loop that we should
524 // short-circuit to.
Chris Lattner4c41d492006-02-10 01:24:09 +0000525
Chris Lattner4e132392006-02-15 22:03:36 +0000526 // Split this block now, so that the loop maintains its exit block, and so
527 // that the jump from the preheader can execute the contents of the exit block
528 // without actually branching to it (the exit block should be dominated by the
529 // loop header, not the preheader).
Chris Lattnerdd3ee6d2006-02-10 02:01:22 +0000530 assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
Chris Lattner4e132392006-02-15 22:03:36 +0000531 BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000532
Chris Lattner4c41d492006-02-10 01:24:09 +0000533 // Okay, now we have a position to branch from and a position to branch to,
534 // insert the new conditional branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000535 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
536 OrigPH->getTerminator());
Chris Lattner4c41d492006-02-10 01:24:09 +0000537 OrigPH->getTerminator()->eraseFromParent();
538
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000539 // We need to reprocess this loop, it could be unswitched again.
540 LoopProcessWorklist.push_back(L);
541
Chris Lattner4c41d492006-02-10 01:24:09 +0000542 // Now that we know that the loop is never entered when this condition is a
543 // particular value, rewrite the loop with this info. We know that this will
544 // at least eliminate the old branch.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000545 RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
Chris Lattner3dd4c402006-02-14 01:01:41 +0000546 ++NumTrivial;
Chris Lattner4c41d492006-02-10 01:24:09 +0000547}
548
Chris Lattner18f16092004-04-19 18:07:02 +0000549
Chris Lattnerc2358092006-02-11 00:43:37 +0000550/// VersionLoop - We determined that the loop is profitable to unswitch when LIC
551/// equal Val. Split it into loop versions and test the condition outside of
552/// either loop. Return the loops created as Out1/Out2.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000553void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
554 Loop *L) {
Chris Lattner18f16092004-04-19 18:07:02 +0000555 Function *F = L->getHeader()->getParent();
Chris Lattner18f16092004-04-19 18:07:02 +0000556 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
Chris Lattnerc2358092006-02-11 00:43:37 +0000557 << L->getHeader()->getName() << " [" << L->getBlocks().size()
558 << " blocks] in Function " << F->getName()
559 << " when '" << *Val << "' == " << *LIC << "\n");
Chris Lattner18f16092004-04-19 18:07:02 +0000560
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000561 // LoopBlocks contains all of the basic blocks of the loop, including the
562 // preheader of the loop, the body of the loop, and the exit blocks of the
563 // loop, in that order.
Chris Lattner18f16092004-04-19 18:07:02 +0000564 std::vector<BasicBlock*> LoopBlocks;
565
566 // First step, split the preheader and exit blocks, and add these blocks to
567 // the LoopBlocks list.
568 BasicBlock *OrigPreheader = L->getLoopPreheader();
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000569 LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
Chris Lattner18f16092004-04-19 18:07:02 +0000570
571 // We want the loop to come after the preheader, but before the exit blocks.
572 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
573
574 std::vector<BasicBlock*> ExitBlocks;
Devang Patel4b8f36f2006-08-29 22:29:16 +0000575 L->getUniqueExitBlocks(ExitBlocks);
576
Owen Anderson2b67f072006-06-26 07:44:36 +0000577 // Split all of the edges from inside the loop to their exit blocks. Update
578 // the appropriate Phi nodes as we do so.
Chris Lattner3dd4c402006-02-14 01:01:41 +0000579 unsigned NumBlocks = L->getBlocks().size();
Chris Lattner25cae0f2006-02-18 00:55:32 +0000580
Chris Lattner4c41d492006-02-10 01:24:09 +0000581 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000582 BasicBlock *ExitBlock = ExitBlocks[i];
583 std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
584
585 for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
586 assert(L->contains(Preds[j]) &&
587 "All preds of loop exit blocks must be the same loop!");
Owen Anderson2b67f072006-06-26 07:44:36 +0000588 BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
589 BasicBlock* StartBlock = Preds[j];
590 BasicBlock* EndBlock;
591 if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
592 EndBlock = MiddleBlock;
593 MiddleBlock = EndBlock->getSinglePredecessor();;
594 } else {
595 EndBlock = ExitBlock;
596 }
597
598 std::set<PHINode*> InsertedPHIs;
599 PHINode* OldLCSSA = 0;
600 for (BasicBlock::iterator I = EndBlock->begin();
601 (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
602 Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
603 PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
604 OldLCSSA->getName() + ".us-lcssa",
605 MiddleBlock->getTerminator());
606 NewLCSSA->addIncoming(OldValue, StartBlock);
607 OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
608 NewLCSSA);
609 InsertedPHIs.insert(NewLCSSA);
610 }
611
Owen Andersondb5b9cf2006-07-19 03:51:48 +0000612 BasicBlock::iterator InsertPt = EndBlock->begin();
Owen Anderson2b67f072006-06-26 07:44:36 +0000613 while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
614 for (BasicBlock::iterator I = MiddleBlock->begin();
615 (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
616 ++I) {
617 PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
618 OldLCSSA->getName() + ".us-lcssa",
619 InsertPt);
620 OldLCSSA->replaceAllUsesWith(NewLCSSA);
621 NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
622 }
623 }
Chris Lattner4c41d492006-02-10 01:24:09 +0000624 }
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000625
626 // The exit blocks may have been changed due to edge splitting, recompute.
627 ExitBlocks.clear();
Devang Patel4b8f36f2006-08-29 22:29:16 +0000628 L->getUniqueExitBlocks(ExitBlocks);
629
Chris Lattnerb2bc3152006-02-10 23:16:39 +0000630 // Add exit blocks to the loop blocks.
631 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
Chris Lattner18f16092004-04-19 18:07:02 +0000632
633 // Next step, clone all of the basic blocks that make up the loop (including
634 // the loop preheader and exit blocks), keeping track of the mapping between
635 // the instructions and blocks.
636 std::vector<BasicBlock*> NewBlocks;
637 NewBlocks.reserve(LoopBlocks.size());
638 std::map<const Value*, Value*> ValueMap;
639 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
Chris Lattner3dd4c402006-02-14 01:01:41 +0000640 BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
641 NewBlocks.push_back(New);
642 ValueMap[LoopBlocks[i]] = New; // Keep the BB mapping.
Chris Lattner18f16092004-04-19 18:07:02 +0000643 }
644
645 // Splice the newly inserted blocks into the function right before the
646 // original preheader.
647 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
648 NewBlocks[0], F->end());
649
650 // Now we create the new Loop object for the versioned loop.
651 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
Chris Lattnere8255932006-02-10 23:26:14 +0000652 Loop *ParentLoop = L->getParentLoop();
653 if (ParentLoop) {
Chris Lattner18f16092004-04-19 18:07:02 +0000654 // Make sure to add the cloned preheader and exit blocks to the parent loop
655 // as well.
Chris Lattnere8255932006-02-10 23:26:14 +0000656 ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
657 }
658
659 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
660 BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
Chris Lattner25cae0f2006-02-18 00:55:32 +0000661 // The new exit block should be in the same loop as the old one.
662 if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
663 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
Chris Lattnere8255932006-02-10 23:26:14 +0000664
665 assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
666 "Exit block should have been split to have one successor!");
667 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
668
669 // If the successor of the exit block had PHI nodes, add an entry for
670 // NewExit.
671 PHINode *PN;
672 for (BasicBlock::iterator I = ExitSucc->begin();
673 (PN = dyn_cast<PHINode>(I)); ++I) {
674 Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
675 std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
676 if (It != ValueMap.end()) V = It->second;
677 PN->addIncoming(V, NewExit);
678 }
Chris Lattner18f16092004-04-19 18:07:02 +0000679 }
680
681 // Rewrite the code to refer to itself.
682 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
683 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
684 E = NewBlocks[i]->end(); I != E; ++I)
685 RemapInstruction(I, ValueMap);
Chris Lattner2f4b8982006-02-09 19:14:52 +0000686
Chris Lattner18f16092004-04-19 18:07:02 +0000687 // Rewrite the original preheader to select between versions of the loop.
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000688 BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
689 assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
Chris Lattner18f16092004-04-19 18:07:02 +0000690 "Preheader splitting did not work correctly!");
Chris Lattner18f16092004-04-19 18:07:02 +0000691
Chris Lattnerfed5d9d2006-02-15 00:07:43 +0000692 // Emit the new branch that selects between the two versions of this loop.
693 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
694 OldBR->eraseFromParent();
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000695
696 LoopProcessWorklist.push_back(L);
697 LoopProcessWorklist.push_back(NewLoop);
Chris Lattner18f16092004-04-19 18:07:02 +0000698
699 // Now we rewrite the original code to know that the condition is true and the
700 // new code to know that the condition is false.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000701 RewriteLoopBodyWithConditionConstant(L , LIC, Val, false);
702
703 // It's possible that simplifying one loop could cause the other to be
704 // deleted. If so, don't simplify it.
705 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
706 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
Chris Lattner18f16092004-04-19 18:07:02 +0000707}
708
Chris Lattner52221f72006-02-17 00:31:07 +0000709/// RemoveFromWorklist - Remove all instances of I from the worklist vector
710/// specified.
711static void RemoveFromWorklist(Instruction *I,
712 std::vector<Instruction*> &Worklist) {
713 std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
714 Worklist.end(), I);
715 while (WI != Worklist.end()) {
716 unsigned Offset = WI-Worklist.begin();
717 Worklist.erase(WI);
718 WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
719 }
720}
721
722/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
723/// program, replacing all uses with V and update the worklist.
724static void ReplaceUsesOfWith(Instruction *I, Value *V,
725 std::vector<Instruction*> &Worklist) {
726 DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
727
728 // Add uses to the worklist, which may be dead now.
729 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
730 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
731 Worklist.push_back(Use);
732
733 // Add users to the worklist which may be simplified now.
734 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
735 UI != E; ++UI)
736 Worklist.push_back(cast<Instruction>(*UI));
737 I->replaceAllUsesWith(V);
738 I->eraseFromParent();
739 RemoveFromWorklist(I, Worklist);
740 ++NumSimplify;
741}
742
Chris Lattnerdb410242006-02-18 02:42:34 +0000743/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
744/// information, and remove any dead successors it has.
745///
746void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
747 std::vector<Instruction*> &Worklist) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000748 if (pred_begin(BB) != pred_end(BB)) {
749 // This block isn't dead, since an edge to BB was just removed, see if there
750 // are any easy simplifications we can do now.
751 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
752 // If it has one pred, fold phi nodes in BB.
753 while (isa<PHINode>(BB->begin()))
754 ReplaceUsesOfWith(BB->begin(),
755 cast<PHINode>(BB->begin())->getIncomingValue(0),
756 Worklist);
757
758 // If this is the header of a loop and the only pred is the latch, we now
759 // have an unreachable loop.
760 if (Loop *L = LI->getLoopFor(BB))
761 if (L->getHeader() == BB && L->contains(Pred)) {
762 // Remove the branch from the latch to the header block, this makes
763 // the header dead, which will make the latch dead (because the header
764 // dominates the latch).
765 Pred->getTerminator()->eraseFromParent();
766 new UnreachableInst(Pred);
767
768 // The loop is now broken, remove it from LI.
769 RemoveLoopFromHierarchy(L);
770
771 // Reprocess the header, which now IS dead.
772 RemoveBlockIfDead(BB, Worklist);
773 return;
774 }
775
776 // If pred ends in a uncond branch, add uncond branch to worklist so that
777 // the two blocks will get merged.
778 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
779 if (BI->isUnconditional())
780 Worklist.push_back(BI);
781 }
782 return;
783 }
Chris Lattner52221f72006-02-17 00:31:07 +0000784
Chris Lattnerdb410242006-02-18 02:42:34 +0000785 DEBUG(std::cerr << "Nuking dead block: " << *BB);
786
787 // Remove the instructions in the basic block from the worklist.
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000788 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Chris Lattnerdb410242006-02-18 02:42:34 +0000789 RemoveFromWorklist(I, Worklist);
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000790
791 // Anything that uses the instructions in this basic block should have their
792 // uses replaced with undefs.
793 if (!I->use_empty())
794 I->replaceAllUsesWith(UndefValue::get(I->getType()));
795 }
Chris Lattnerdb410242006-02-18 02:42:34 +0000796
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000797 // If this is the edge to the header block for a loop, remove the loop and
798 // promote all subloops.
Chris Lattnerdb410242006-02-18 02:42:34 +0000799 if (Loop *BBLoop = LI->getLoopFor(BB)) {
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000800 if (BBLoop->getLoopLatch() == BB)
801 RemoveLoopFromHierarchy(BBLoop);
Chris Lattnerdb410242006-02-18 02:42:34 +0000802 }
803
804 // Remove the block from the loop info, which removes it from any loops it
805 // was in.
806 LI->removeBlock(BB);
807
808
809 // Remove phi node entries in successors for this block.
810 TerminatorInst *TI = BB->getTerminator();
811 std::vector<BasicBlock*> Succs;
812 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
813 Succs.push_back(TI->getSuccessor(i));
814 TI->getSuccessor(i)->removePredecessor(BB);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000815 }
816
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000817 // Unique the successors, remove anything with multiple uses.
Chris Lattnerdb410242006-02-18 02:42:34 +0000818 std::sort(Succs.begin(), Succs.end());
819 Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
820
821 // Remove the basic block, including all of the instructions contained in it.
822 BB->eraseFromParent();
823
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000824 // Remove successor blocks here that are not dead, so that we know we only
825 // have dead blocks in this list. Nondead blocks have a way of becoming dead,
826 // then getting removed before we revisit them, which is badness.
827 //
828 for (unsigned i = 0; i != Succs.size(); ++i)
829 if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
830 // One exception is loop headers. If this block was the preheader for a
831 // loop, then we DO want to visit the loop so the loop gets deleted.
832 // We know that if the successor is a loop header, that this loop had to
833 // be the preheader: the case where this was the latch block was handled
834 // above and headers can only have two predecessors.
835 if (!LI->isLoopHeader(Succs[i])) {
836 Succs.erase(Succs.begin()+i);
837 --i;
838 }
839 }
840
Chris Lattnerdb410242006-02-18 02:42:34 +0000841 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
842 RemoveBlockIfDead(Succs[i], Worklist);
Chris Lattnerf4412d82006-02-18 01:27:45 +0000843}
Chris Lattner52221f72006-02-17 00:31:07 +0000844
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000845/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
846/// become unwrapped, either because the backedge was deleted, or because the
847/// edge into the header was removed. If the edge into the header from the
848/// latch block was removed, the loop is unwrapped but subloops are still alive,
849/// so they just reparent loops. If the loops are actually dead, they will be
850/// removed later.
851void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
852 if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
853 // Reparent all of the blocks in this loop. Since BBLoop had a parent,
854 // they are now all in it.
855 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
856 I != E; ++I)
857 if (LI->getLoopFor(*I) == L) // Don't change blocks in subloops.
858 LI->changeLoopFor(*I, ParentLoop);
859
860 // Remove the loop from its parent loop.
861 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
862 ++I) {
863 assert(I != E && "Couldn't find loop");
864 if (*I == L) {
865 ParentLoop->removeChildLoop(I);
866 break;
867 }
868 }
869
870 // Move all subloops into the parent loop.
871 while (L->begin() != L->end())
872 ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
873 } else {
874 // Reparent all of the blocks in this loop. Since BBLoop had no parent,
875 // they no longer in a loop at all.
876
877 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
878 // Don't change blocks in subloops.
879 if (LI->getLoopFor(L->getBlocks()[i]) == L) {
880 LI->removeBlock(L->getBlocks()[i]);
881 --i;
882 }
883 }
884
885 // Remove the loop from the top-level LoopInfo object.
886 for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
887 assert(I != E && "Couldn't find loop");
888 if (*I == L) {
889 LI->removeLoop(I);
890 break;
891 }
892 }
893
894 // Move all of the subloops to the top-level.
895 while (L->begin() != L->end())
896 LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
897 }
898
899 delete L;
900 RemoveLoopFromWorklist(L);
901}
902
903
904
Chris Lattnerc2358092006-02-11 00:43:37 +0000905// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
906// the value specified by Val in the specified loop, or we know it does NOT have
907// that value. Rewrite any uses of LIC or of properties correlated to it.
Chris Lattner18f16092004-04-19 18:07:02 +0000908void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
Chris Lattnerc2358092006-02-11 00:43:37 +0000909 Constant *Val,
910 bool IsEqual) {
Chris Lattner4c41d492006-02-10 01:24:09 +0000911 assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
Chris Lattnerc2358092006-02-11 00:43:37 +0000912
Chris Lattner18f16092004-04-19 18:07:02 +0000913 // FIXME: Support correlated properties, like:
914 // for (...)
915 // if (li1 < li2)
916 // ...
917 // if (li1 > li2)
918 // ...
Chris Lattnerc2358092006-02-11 00:43:37 +0000919
Chris Lattner708e1a52006-02-10 02:30:37 +0000920 // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
921 // selects, switches.
Chris Lattner18f16092004-04-19 18:07:02 +0000922 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
Chris Lattner52221f72006-02-17 00:31:07 +0000923 std::vector<Instruction*> Worklist;
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000924
Chris Lattner52221f72006-02-17 00:31:07 +0000925 // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
926 // in the loop with the appropriate one directly.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +0000927 if (IsEqual || isa<ConstantBool>(Val)) {
928 Value *Replacement;
929 if (IsEqual)
930 Replacement = Val;
931 else
932 Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
Chris Lattner52221f72006-02-17 00:31:07 +0000933
934 for (unsigned i = 0, e = Users.size(); i != e; ++i)
935 if (Instruction *U = cast<Instruction>(Users[i])) {
936 if (!L->contains(U->getParent()))
937 continue;
938 U->replaceUsesOfWith(LIC, Replacement);
939 Worklist.push_back(U);
940 }
941 } else {
942 // Otherwise, we don't know the precise value of LIC, but we do know that it
943 // is certainly NOT "Val". As such, simplify any uses in the loop that we
944 // can. This case occurs when we unswitch switch statements.
945 for (unsigned i = 0, e = Users.size(); i != e; ++i)
946 if (Instruction *U = cast<Instruction>(Users[i])) {
947 if (!L->contains(U->getParent()))
948 continue;
949
950 Worklist.push_back(U);
951
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000952 // If we know that LIC is not Val, use this info to simplify code.
953 if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
954 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
955 if (SI->getCaseValue(i) == Val) {
956 // Found a dead case value. Don't remove PHI nodes in the
957 // successor if they become single-entry, those PHI nodes may
958 // be in the Users list.
Owen Anderson2b67f072006-06-26 07:44:36 +0000959
960 // FIXME: This is a hack. We need to keep the successor around
961 // and hooked up so as to preserve the loop structure, because
962 // trying to update it is complicated. So instead we preserve the
963 // loop structure and put the block on an dead code path.
964
965 BasicBlock* Old = SI->getParent();
966 BasicBlock* Split = SplitBlock(Old, SI);
967
968 Instruction* OldTerm = Old->getTerminator();
Chris Lattner47811b72006-09-28 23:35:22 +0000969 BranchInst* Branch = new BranchInst(Split, SI->getSuccessor(i),
970 ConstantBool::getTrue(),
971 OldTerm);
Owen Anderson2b67f072006-06-26 07:44:36 +0000972
973 Old->getTerminator()->eraseFromParent();
974
Owen Andersonbef85082006-06-27 22:26:09 +0000975
976 PHINode *PN;
977 for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
978 (PN = dyn_cast<PHINode>(II)); ++II) {
979 Value *InVal = PN->removeIncomingValue(Split, false);
980 PN->addIncoming(InVal, Old);
Owen Anderson2b67f072006-06-26 07:44:36 +0000981 }
982
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000983 SI->removeCase(i);
984 break;
Chris Lattnerc2358092006-02-11 00:43:37 +0000985 }
986 }
Chris Lattnerc2358092006-02-11 00:43:37 +0000987 }
Chris Lattner52221f72006-02-17 00:31:07 +0000988
989 // TODO: We could do other simplifications, for example, turning
990 // LIC == Val -> false.
Chris Lattner10cd9bb2006-02-16 19:36:22 +0000991 }
Chris Lattner52221f72006-02-17 00:31:07 +0000992 }
Chris Lattnera6fc94b2006-02-18 07:57:38 +0000993
994 SimplifyCode(Worklist);
995}
996
997/// SimplifyCode - Okay, now that we have simplified some instructions in the
998/// loop, walk over it and constant prop, dce, and fold control flow where
999/// possible. Note that this is effectively a very simple loop-structure-aware
1000/// optimizer. During processing of this loop, L could very well be deleted, so
1001/// it must not be used.
1002///
1003/// FIXME: When the loop optimizer is more mature, separate this out to a new
1004/// pass.
1005///
1006void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
Chris Lattner52221f72006-02-17 00:31:07 +00001007 while (!Worklist.empty()) {
1008 Instruction *I = Worklist.back();
1009 Worklist.pop_back();
1010
1011 // Simple constant folding.
1012 if (Constant *C = ConstantFoldInstruction(I)) {
1013 ReplaceUsesOfWith(I, C, Worklist);
1014 continue;
Chris Lattner10cd9bb2006-02-16 19:36:22 +00001015 }
Chris Lattner52221f72006-02-17 00:31:07 +00001016
1017 // Simple DCE.
1018 if (isInstructionTriviallyDead(I)) {
1019 DEBUG(std::cerr << "Remove dead instruction '" << *I);
1020
1021 // Add uses to the worklist, which may be dead now.
1022 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1023 if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1024 Worklist.push_back(Use);
1025 I->eraseFromParent();
1026 RemoveFromWorklist(I, Worklist);
1027 ++NumSimplify;
1028 continue;
1029 }
1030
1031 // Special case hacks that appear commonly in unswitched code.
1032 switch (I->getOpcode()) {
1033 case Instruction::Select:
1034 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
1035 ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
1036 continue;
1037 }
1038 break;
1039 case Instruction::And:
1040 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1041 cast<BinaryOperator>(I)->swapOperands();
1042 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1043 if (CB->getValue()) // X & 1 -> X
1044 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1045 else // X & 0 -> 0
1046 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1047 continue;
1048 }
1049 break;
1050 case Instruction::Or:
1051 if (isa<ConstantBool>(I->getOperand(0))) // constant -> RHS
1052 cast<BinaryOperator>(I)->swapOperands();
1053 if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
1054 if (CB->getValue()) // X | 1 -> 1
1055 ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1056 else // X | 0 -> X
1057 ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1058 continue;
1059 }
1060 break;
1061 case Instruction::Br: {
1062 BranchInst *BI = cast<BranchInst>(I);
1063 if (BI->isUnconditional()) {
1064 // If BI's parent is the only pred of the successor, fold the two blocks
1065 // together.
1066 BasicBlock *Pred = BI->getParent();
1067 BasicBlock *Succ = BI->getSuccessor(0);
1068 BasicBlock *SinglePred = Succ->getSinglePredecessor();
1069 if (!SinglePred) continue; // Nothing to do.
1070 assert(SinglePred == Pred && "CFG broken");
1071
1072 DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- "
1073 << Succ->getName() << "\n");
1074
1075 // Resolve any single entry PHI nodes in Succ.
1076 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1077 ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1078
1079 // Move all of the successor contents from Succ to Pred.
1080 Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1081 Succ->end());
1082 BI->eraseFromParent();
1083 RemoveFromWorklist(BI, Worklist);
1084
1085 // If Succ has any successors with PHI nodes, update them to have
1086 // entries coming from Pred instead of Succ.
1087 Succ->replaceAllUsesWith(Pred);
1088
1089 // Remove Succ from the loop tree.
1090 LI->removeBlock(Succ);
1091 Succ->eraseFromParent();
Chris Lattnerf4412d82006-02-18 01:27:45 +00001092 ++NumSimplify;
Chris Lattnerf4412d82006-02-18 01:27:45 +00001093 } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
Chris Lattnerdb410242006-02-18 02:42:34 +00001094 // Conditional branch. Turn it into an unconditional branch, then
1095 // remove dead blocks.
Chris Lattnerbd28e3f2006-02-22 06:37:14 +00001096 break; // FIXME: Enable.
1097
Chris Lattnerdb410242006-02-18 02:42:34 +00001098 DEBUG(std::cerr << "Folded branch: " << *BI);
1099 BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
1100 BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
1101 DeadSucc->removePredecessor(BI->getParent(), true);
1102 Worklist.push_back(new BranchInst(LiveSucc, BI));
1103 BI->eraseFromParent();
1104 RemoveFromWorklist(BI, Worklist);
1105 ++NumSimplify;
1106
1107 RemoveBlockIfDead(DeadSucc, Worklist);
Chris Lattner52221f72006-02-17 00:31:07 +00001108 }
1109 break;
1110 }
1111 }
1112 }
Chris Lattner18f16092004-04-19 18:07:02 +00001113}