blob: 273291910b37759db90a932b771bfdec6139fa0f [file] [log] [blame]
Chris Lattnerf48f7772004-04-19 18:07:02 +00001//===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf48f7772004-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf48f7772004-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 Lattnerf48f7772004-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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000037#include "llvm/ADT/Statistic.h"
Chris Lattner89762192006-02-09 20:15:48 +000038#include "llvm/Support/Debug.h"
39#include "llvm/Support/CommandLine.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000040#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000041#include <iostream>
Chris Lattner2826e052006-02-09 19:14:52 +000042#include <set>
Chris Lattnerf48f7772004-04-19 18:07:02 +000043using namespace llvm;
44
45namespace {
46 Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched");
Chris Lattner89762192006-02-09 20:15:48 +000047 cl::opt<unsigned>
48 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
49 cl::init(10), cl::Hidden);
50
Chris Lattnerf48f7772004-04-19 18:07:02 +000051 class LoopUnswitch : public FunctionPass {
52 LoopInfo *LI; // Loop information
Chris Lattnerf48f7772004-04-19 18:07:02 +000053 public:
54 virtual bool runOnFunction(Function &F);
55 bool visitLoop(Loop *L);
56
57 /// This transformation requires natural loop information & requires that
58 /// loop preheaders be inserted into the CFG...
59 ///
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequiredID(LoopSimplifyID);
Chris Lattner4f0e66d2006-02-09 22:15:42 +000062 AU.addPreservedID(LoopSimplifyID);
Chris Lattnerf48f7772004-04-19 18:07:02 +000063 AU.addRequired<LoopInfo>();
64 AU.addPreserved<LoopInfo>();
65 }
66
67 private:
Chris Lattner4f0e66d2006-02-09 22:15:42 +000068 void VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2);
Chris Lattnerf48f7772004-04-19 18:07:02 +000069 BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop);
70 void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val);
71 };
72 RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
73}
74
Jeff Coheneca0d0f2005-01-06 05:47:18 +000075FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
Chris Lattnerf48f7772004-04-19 18:07:02 +000076
77bool LoopUnswitch::runOnFunction(Function &F) {
78 bool Changed = false;
79 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf48f7772004-04-19 18:07:02 +000080
81 // Transform all the top-level loops. Copy the loop list so that the child
82 // can update the loop tree if it needs to delete the loop.
83 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
84 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
85 Changed |= visitLoop(SubLoops[i]);
86
87 return Changed;
88}
89
Chris Lattner2826e052006-02-09 19:14:52 +000090
91/// InsertPHINodesForUsesOutsideLoop - If this instruction is used outside of
92/// the specified loop, insert a PHI node in the appropriate exit block to merge
93/// the values in the two different loop versions.
94///
95/// Most values are not used outside of the loop they are defined in, so be
96/// efficient for this case.
97///
98static bool LoopValuesUsedOutsideLoop(Loop *L) {
99 // We will be doing lots of "loop contains block" queries. Loop::contains is
100 // linear time, use a set to speed this up.
101 std::set<BasicBlock*> LoopBlocks;
102
103 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
104 BB != E; ++BB)
105 LoopBlocks.insert(*BB);
106
107 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
108 BB != E; ++BB) {
109 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
110 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
111 ++UI) {
112 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
113 if (!LoopBlocks.count(UserBB))
114 return true;
115 }
116 }
117 return false;
118}
119
Chris Lattnerf48f7772004-04-19 18:07:02 +0000120bool LoopUnswitch::visitLoop(Loop *L) {
121 bool Changed = false;
122
123 // Recurse through all subloops before we process this loop. Copy the loop
124 // list so that the child can update the loop tree if it needs to delete the
125 // loop.
126 std::vector<Loop*> SubLoops(L->begin(), L->end());
127 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
128 Changed |= visitLoop(SubLoops[i]);
129
130 // Loop over all of the basic blocks in the loop. If we find an interior
131 // block that is branching on a loop-invariant condition, we can unswitch this
132 // loop.
133 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
134 I != E; ++I) {
135 TerminatorInst *TI = (*I)->getTerminator();
136 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
137 if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition()))
Chris Lattner2826e052006-02-09 19:14:52 +0000138 DEBUG(std::cerr << "TODO: Implement unswitching 'switch' loop %"
Chris Lattnerf48f7772004-04-19 18:07:02 +0000139 << L->getHeader()->getName() << ", cost = "
140 << L->getBlocks().size() << "\n" << **I);
Chris Lattner2826e052006-02-09 19:14:52 +0000141 continue;
142 }
143
144 BranchInst *BI = dyn_cast<BranchInst>(TI);
145 if (!BI) continue;
146
147 // If this isn't branching on an invariant condition, we can't unswitch it.
148 if (!BI->isConditional() || isa<Constant>(BI->getCondition()) ||
149 !L->isLoopInvariant(BI->getCondition()))
150 continue;
151
152 // Check to see if it would be profitable to unswitch this loop.
Chris Lattner89762192006-02-09 20:15:48 +0000153 if (L->getBlocks().size() > Threshold) {
Chris Lattner2826e052006-02-09 19:14:52 +0000154 // FIXME: this should estimate growth by the amount of code shared by the
155 // resultant unswitched loops. This should have no code growth:
156 // for () { if (iv) {...} }
157 // as one copy of the loop will be empty.
158 //
159 DEBUG(std::cerr << "NOT unswitching loop %"
160 << L->getHeader()->getName() << ", cost too high: "
161 << L->getBlocks().size() << "\n");
162 continue;
163 }
164
165 // If this loop has live-out values, we can't unswitch it. We need something
166 // like loop-closed SSA form in order to know how to insert PHI nodes for
167 // these values.
168 if (LoopValuesUsedOutsideLoop(L)) {
169 DEBUG(std::cerr << "NOT unswitching loop %"
170 << L->getHeader()->getName()
171 << ", a loop value is used outside loop!\n");
172 continue;
173 }
174
175 //std::cerr << "BEFORE:\n"; LI->dump();
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000176 Loop *First = 0, *Second = 0;
177 VersionLoop(BI->getCondition(), L, First, Second);
Chris Lattner2826e052006-02-09 19:14:52 +0000178 //std::cerr << "AFTER:\n"; LI->dump();
179
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000180 // Try to unswitch each of our new loops now!
181 if (First) visitLoop(First);
182 if (Second) visitLoop(Second);
Chris Lattner2826e052006-02-09 19:14:52 +0000183 return true;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000184 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000185
Chris Lattnerf48f7772004-04-19 18:07:02 +0000186 return Changed;
187}
188
189/// SplitBlock - Split the specified basic block into two pieces. If SplitAtTop
190/// is false, this splits the block so the second half only has an unconditional
191/// branch. If SplitAtTop is true, it makes it so the first half of the block
192/// only has an unconditional branch in it.
193///
194/// This method updates the LoopInfo for this function to correctly reflect the
195/// CFG changes made.
196BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) {
197 BasicBlock::iterator SplitPoint;
198 if (!SplitAtTop)
199 SplitPoint = BB->getTerminator();
200 else {
201 SplitPoint = BB->begin();
202 while (isa<PHINode>(SplitPoint)) ++SplitPoint;
203 }
204
205 BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+".tail");
206 // New now lives in whichever loop that BB used to.
207 if (Loop *L = LI->getLoopFor(BB))
208 L->addBasicBlockToLoop(New, *LI);
209 return SplitAtTop ? BB : New;
210}
211
212
Misha Brukmanb1c93172005-04-21 23:48:37 +0000213// RemapInstruction - Convert the instruction operands from referencing the
Chris Lattnerf48f7772004-04-19 18:07:02 +0000214// current values into those specified by ValueMap.
215//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000216static inline void RemapInstruction(Instruction *I,
Chris Lattnerf48f7772004-04-19 18:07:02 +0000217 std::map<const Value *, Value*> &ValueMap) {
218 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
219 Value *Op = I->getOperand(op);
220 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
221 if (It != ValueMap.end()) Op = It->second;
222 I->setOperand(op, Op);
223 }
224}
225
226/// CloneLoop - Recursively clone the specified loop and all of its children,
227/// mapping the blocks with the specified map.
228static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
229 LoopInfo *LI) {
230 Loop *New = new Loop();
231
232 if (PL)
233 PL->addChildLoop(New);
234 else
235 LI->addTopLevelLoop(New);
236
237 // Add all of the blocks in L to the new loop.
238 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
239 I != E; ++I)
240 if (LI->getLoopFor(*I) == L)
241 New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
242
243 // Add all of the subloops to the new loop.
244 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
245 CloneLoop(*I, New, VM, LI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000246
Chris Lattnerf48f7772004-04-19 18:07:02 +0000247 return New;
248}
249
250
Chris Lattnerf48f7772004-04-19 18:07:02 +0000251/// VersionLoop - We determined that the loop is profitable to unswitch and
252/// contains a branch on a loop invariant condition. Split it into loop
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000253/// versions and test the condition outside of either loop. Return the loops
254/// created as Out1/Out2.
255void LoopUnswitch::VersionLoop(Value *LIC, Loop *L, Loop *&Out1, Loop *&Out2) {
Chris Lattnerf48f7772004-04-19 18:07:02 +0000256 Function *F = L->getHeader()->getParent();
257
258 DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
259 << L->getHeader()->getName() << " [" << L->getBlocks().size()
260 << " blocks] in Function " << F->getName()
261 << " on cond:" << *LIC << "\n");
262
263 std::vector<BasicBlock*> LoopBlocks;
264
265 // First step, split the preheader and exit blocks, and add these blocks to
266 // the LoopBlocks list.
267 BasicBlock *OrigPreheader = L->getLoopPreheader();
268 LoopBlocks.push_back(SplitBlock(OrigPreheader, false));
269
270 // We want the loop to come after the preheader, but before the exit blocks.
271 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
272
273 std::vector<BasicBlock*> ExitBlocks;
274 L->getExitBlocks(ExitBlocks);
275 std::sort(ExitBlocks.begin(), ExitBlocks.end());
276 ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
277 ExitBlocks.end());
278 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
279 LoopBlocks.push_back(ExitBlocks[i] = SplitBlock(ExitBlocks[i], true));
280
281 // Next step, clone all of the basic blocks that make up the loop (including
282 // the loop preheader and exit blocks), keeping track of the mapping between
283 // the instructions and blocks.
284 std::vector<BasicBlock*> NewBlocks;
285 NewBlocks.reserve(LoopBlocks.size());
286 std::map<const Value*, Value*> ValueMap;
287 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
288 NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F));
289 ValueMap[LoopBlocks[i]] = NewBlocks.back(); // Keep the BB mapping.
290 }
291
292 // Splice the newly inserted blocks into the function right before the
293 // original preheader.
294 F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
295 NewBlocks[0], F->end());
296
297 // Now we create the new Loop object for the versioned loop.
298 Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
299 if (Loop *Parent = L->getParentLoop()) {
300 // Make sure to add the cloned preheader and exit blocks to the parent loop
301 // as well.
302 Parent->addBasicBlockToLoop(NewBlocks[0], *LI);
303 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
304 Parent->addBasicBlockToLoop(cast<BasicBlock>(ValueMap[ExitBlocks[i]]),
305 *LI);
306 }
307
308 // Rewrite the code to refer to itself.
309 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
310 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
311 E = NewBlocks[i]->end(); I != E; ++I)
312 RemapInstruction(I, ValueMap);
Chris Lattner2826e052006-02-09 19:14:52 +0000313
Chris Lattnerf48f7772004-04-19 18:07:02 +0000314 // Rewrite the original preheader to select between versions of the loop.
315 assert(isa<BranchInst>(OrigPreheader->getTerminator()) &&
316 cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() &&
317 OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&
318 "Preheader splitting did not work correctly!");
319 // Remove the unconditional branch to LoopBlocks[0].
320 OrigPreheader->getInstList().pop_back();
321
322 // Insert a conditional branch on LIC to the two preheaders. The original
323 // code is the true version and the new code is the false version.
324 new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader);
325
326 // Now we rewrite the original code to know that the condition is true and the
327 // new code to know that the condition is false.
328 RewriteLoopBodyWithConditionConstant(L, LIC, true);
329 RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false);
330 ++NumUnswitched;
Chris Lattner4f0e66d2006-02-09 22:15:42 +0000331 Out1 = L;
332 Out2 = NewLoop;
Chris Lattnerf48f7772004-04-19 18:07:02 +0000333}
334
335// RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has
336// the value specified by Val in the specified loop. Rewrite any uses of LIC or
337// of properties correlated to it.
338void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
339 bool Val) {
340 // FIXME: Support correlated properties, like:
341 // for (...)
342 // if (li1 < li2)
343 // ...
344 // if (li1 > li2)
345 // ...
346 ConstantBool *BoolVal = ConstantBool::get(Val);
347
348 std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
349 for (unsigned i = 0, e = Users.size(); i != e; ++i)
350 if (Instruction *U = dyn_cast<Instruction>(Users[i]))
351 if (L->contains(U->getParent()))
352 U->replaceUsesOfWith(LIC, BoolVal);
353}