Changes For Bug 352
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnswitch.cpp
1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops.  For example, it turns the left into the right code:
12 //
13 //  for (...)                  if (lic)
14 //    A                          for (...)
15 //    if (lic)                     A; B; C
16 //      B                      else
17 //    C                          for (...)
18 //                                 A; C
19 //
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
23 //
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/Analysis/Dominators.h"
35 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/Transforms/Utils/Cloning.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/ADT/Statistic.h"
40 using namespace llvm;
41
42 namespace {
43   Statistic<> NumUnswitched("loop-unswitch", "Number of loops unswitched");
44
45   class LoopUnswitch : public FunctionPass {
46     LoopInfo *LI;  // Loop information
47     DominatorSet *DS;
48   public:
49     virtual bool runOnFunction(Function &F);
50     bool visitLoop(Loop *L);
51
52     /// This transformation requires natural loop information & requires that
53     /// loop preheaders be inserted into the CFG...
54     ///
55     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56       AU.addRequiredID(LoopSimplifyID);
57       //AU.addRequired<DominatorSet>();
58       AU.addRequired<LoopInfo>();
59       AU.addPreserved<LoopInfo>();
60     }
61
62   private:
63     void VersionLoop(Value *LIC, Loop *L);
64     BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop);
65     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val);
66   };
67   RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
68 }
69
70 FunctionPass *createLoopUnswitchPass() { return new LoopUnswitch(); }
71
72 bool LoopUnswitch::runOnFunction(Function &F) {
73   bool Changed = false;
74   LI = &getAnalysis<LoopInfo>();
75   DS = 0; //&getAnalysis<DominatorSet>();
76
77   // Transform all the top-level loops.  Copy the loop list so that the child
78   // can update the loop tree if it needs to delete the loop.
79   std::vector<Loop*> SubLoops(LI->begin(), LI->end());
80   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
81     Changed |= visitLoop(SubLoops[i]);
82
83   return Changed;
84 }
85
86 bool LoopUnswitch::visitLoop(Loop *L) {
87   bool Changed = false;
88
89   // Recurse through all subloops before we process this loop.  Copy the loop
90   // list so that the child can update the loop tree if it needs to delete the
91   // loop.
92   std::vector<Loop*> SubLoops(L->begin(), L->end());
93   for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
94     Changed |= visitLoop(SubLoops[i]);
95
96   // Loop over all of the basic blocks in the loop.  If we find an interior
97   // block that is branching on a loop-invariant condition, we can unswitch this
98   // loop.
99   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
100        I != E; ++I) {
101     TerminatorInst *TI = (*I)->getTerminator();
102     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
103       if (!isa<Constant>(SI) && L->isLoopInvariant(SI->getCondition()))
104         DEBUG(std::cerr << "Can't unswitching 'switch' loop %"
105               << L->getHeader()->getName() << ", cost = "
106               << L->getBlocks().size() << "\n" << **I);
107     } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
108       if (BI->isConditional() && !isa<Constant>(BI->getCondition()) &&
109           L->isLoopInvariant(BI->getCondition())) {
110         // Check to see if it would be profitable to unswitch this loop.
111         if (L->getBlocks().size() > 10) {
112           DEBUG(std::cerr << "NOT unswitching loop %"
113                 << L->getHeader()->getName() << ", cost too high: "
114                 << L->getBlocks().size() << "\n");
115         } else {
116           // FIXME: check for profitability.
117           //std::cerr << "BEFORE:\n"; LI->dump();
118           
119           VersionLoop(BI->getCondition(), L);
120           
121           //std::cerr << "AFTER:\n"; LI->dump();
122           return true;
123         }
124       }
125   }
126   
127   return Changed;
128 }
129
130 /// SplitBlock - Split the specified basic block into two pieces.  If SplitAtTop
131 /// is false, this splits the block so the second half only has an unconditional
132 /// branch.  If SplitAtTop is true, it makes it so the first half of the block
133 /// only has an unconditional branch in it.
134 ///
135 /// This method updates the LoopInfo for this function to correctly reflect the
136 /// CFG changes made.
137 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) {
138   BasicBlock::iterator SplitPoint;
139   if (!SplitAtTop)
140     SplitPoint = BB->getTerminator();
141   else {
142     SplitPoint = BB->begin();
143     while (isa<PHINode>(SplitPoint)) ++SplitPoint;
144   }
145
146   BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+".tail");
147   // New now lives in whichever loop that BB used to.
148   if (Loop *L = LI->getLoopFor(BB))
149     L->addBasicBlockToLoop(New, *LI);
150   return SplitAtTop ? BB : New;
151 }
152
153
154 // RemapInstruction - Convert the instruction operands from referencing the 
155 // current values into those specified by ValueMap.
156 //
157 static inline void RemapInstruction(Instruction *I, 
158                                     std::map<const Value *, Value*> &ValueMap) {
159   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
160     Value *Op = I->getOperand(op);
161     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
162     if (It != ValueMap.end()) Op = It->second;
163     I->setOperand(op, Op);
164   }
165 }
166
167 /// CloneLoop - Recursively clone the specified loop and all of its children,
168 /// mapping the blocks with the specified map.
169 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
170                        LoopInfo *LI) {
171   Loop *New = new Loop();
172
173   if (PL)
174     PL->addChildLoop(New);
175   else
176     LI->addTopLevelLoop(New);
177
178   // Add all of the blocks in L to the new loop.
179   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
180        I != E; ++I)
181     if (LI->getLoopFor(*I) == L)
182       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
183
184   // Add all of the subloops to the new loop.
185   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
186     CloneLoop(*I, New, VM, LI);
187   
188   return New;
189 }
190
191
192 /// InsertPHINodesForUsesOutsideLoop - If this instruction is used outside of
193 /// the specified loop, insert a PHI node in the appropriate exit block to merge
194 /// the values in the two different loop versions.
195 ///
196 /// Most values are not used outside of the loop they are defined in, so be
197 /// efficient for this case.
198 ///
199 static AllocaInst *
200 InsertPHINodesForUsesOutsideLoop(Instruction *OI, Instruction *NI,
201                                  DominatorSet &DS, Loop *OL, Loop *NL,
202                                  std::vector<BasicBlock*> &OldExitBlocks,
203                                  std::map<const Value*, Value*> &ValueMap) {
204   assert(OI->getType() == NI->getType() && OI->getOpcode() == NI->getOpcode() &&
205          "Hrm, should be mapping between identical instructions!");
206   for (Value::use_iterator UI = OI->use_begin(), E = OI->use_end(); UI != E;
207        ++UI)
208     if (!OL->contains(cast<Instruction>(*UI)->getParent()) &&
209         !NL->contains(cast<Instruction>(*UI)->getParent()))
210       goto UsedOutsideOfLoop;
211   return 0;
212   
213 UsedOutsideOfLoop:
214   // Okay, this instruction is used outside of the current loop.  Insert a PHI
215   // nodes for the instruction merging the values together.
216
217   // FIXME: For now we just spill the object to the stack, assuming that a
218   // subsequent mem2reg pass will clean up after us.  This should be improved in
219   // two ways:
220   //  1. If there is only one exit block, trivially insert the PHI nodes
221   //  2. Once we update domfrontier, we should do the promotion after everything
222   //     is stable again.
223   AllocaInst *Result = DemoteRegToStack(*OI);
224
225   // Store to the stack location right after the new instruction.
226   BasicBlock::iterator InsertPoint = NI;
227   if (InvokeInst *II = dyn_cast<InvokeInst>(NI))
228     InsertPoint = II->getNormalDest()->begin();
229   else
230     ++InsertPoint;
231   while (isa<PHINode>(InsertPoint)) ++InsertPoint;
232   new StoreInst(NI, Result, InsertPoint);
233   return Result;
234 }
235
236
237
238 /// VersionLoop - We determined that the loop is profitable to unswitch and
239 /// contains a branch on a loop invariant condition.  Split it into loop
240 /// versions and test the condition outside of either loop.
241 void LoopUnswitch::VersionLoop(Value *LIC, Loop *L) {
242   Function *F = L->getHeader()->getParent();
243
244   DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
245         << L->getHeader()->getName() << " [" << L->getBlocks().size()
246         << " blocks] in Function " << F->getName()
247         << " on cond:" << *LIC << "\n");
248
249   std::vector<BasicBlock*> LoopBlocks;
250
251   // First step, split the preheader and exit blocks, and add these blocks to
252   // the LoopBlocks list.
253   BasicBlock *OrigPreheader = L->getLoopPreheader();
254   LoopBlocks.push_back(SplitBlock(OrigPreheader, false));
255
256   // We want the loop to come after the preheader, but before the exit blocks.
257   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
258
259   std::vector<BasicBlock*> ExitBlocks;
260   L->getExitBlocks(ExitBlocks);
261   std::sort(ExitBlocks.begin(), ExitBlocks.end());
262   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
263                    ExitBlocks.end());
264   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
265     LoopBlocks.push_back(ExitBlocks[i] = SplitBlock(ExitBlocks[i], true));
266
267   // Next step, clone all of the basic blocks that make up the loop (including
268   // the loop preheader and exit blocks), keeping track of the mapping between
269   // the instructions and blocks.
270   std::vector<BasicBlock*> NewBlocks;
271   NewBlocks.reserve(LoopBlocks.size());
272   std::map<const Value*, Value*> ValueMap;
273   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
274     NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F));
275     ValueMap[LoopBlocks[i]] = NewBlocks.back();  // Keep the BB mapping.
276   }
277
278   // Splice the newly inserted blocks into the function right before the
279   // original preheader.
280   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
281                                 NewBlocks[0], F->end());
282
283   // Now we create the new Loop object for the versioned loop.
284   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
285   if (Loop *Parent = L->getParentLoop()) {
286     // Make sure to add the cloned preheader and exit blocks to the parent loop
287     // as well.
288     Parent->addBasicBlockToLoop(NewBlocks[0], *LI);
289     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
290       Parent->addBasicBlockToLoop(cast<BasicBlock>(ValueMap[ExitBlocks[i]]),
291                                   *LI);
292   }
293
294   // Rewrite the code to refer to itself.
295   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
296     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
297            E = NewBlocks[i]->end(); I != E; ++I)
298       RemapInstruction(I, ValueMap);
299
300   // If the instructions are used outside of the loop, insert a PHI node in any
301   // exit blocks dominated by the instruction.
302   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
303     for (BasicBlock::iterator OI = LoopBlocks[i]->begin(),
304            E = LoopBlocks[i]->end(); OI != E; ++OI)
305       if (!OI->use_empty()) {
306         std::map<const Value*,Value*>::iterator OII = ValueMap.find(OI);
307         // The PHINode rewriting stuff can insert stores that are not in the
308         // mapping.  Don't mess around with them.
309         if (OII != ValueMap.end()) {
310           Instruction *NI = cast<Instruction>(OII->second);
311           InsertPHINodesForUsesOutsideLoop(OI, NI, *DS, L, NewLoop,
312                                            ExitBlocks, ValueMap);
313         }
314       }
315
316   // Rewrite the original preheader to select between versions of the loop.
317   assert(isa<BranchInst>(OrigPreheader->getTerminator()) &&
318          cast<BranchInst>(OrigPreheader->getTerminator())->isUnconditional() &&
319          OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&
320          "Preheader splitting did not work correctly!");
321   // Remove the unconditional branch to LoopBlocks[0].
322   OrigPreheader->getInstList().pop_back();
323
324   // Insert a conditional branch on LIC to the two preheaders.  The original
325   // code is the true version and the new code is the false version.
326   new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader);
327
328   // Now we rewrite the original code to know that the condition is true and the
329   // new code to know that the condition is false.
330   RewriteLoopBodyWithConditionConstant(L, LIC, true);
331   RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false);
332   ++NumUnswitched;
333
334   // Try to unswitch each of our new loops now!
335   visitLoop(L);
336   visitLoop(NewLoop);
337 }
338
339 // RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has
340 // the value specified by Val in the specified loop.  Rewrite any uses of LIC or
341 // of properties correlated to it.
342 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
343                                                         bool Val) {
344   // FIXME: Support correlated properties, like:
345   //  for (...)
346   //    if (li1 < li2)
347   //      ...
348   //    if (li1 > li2)
349   //      ...
350   ConstantBool *BoolVal = ConstantBool::get(Val);
351
352   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
353   for (unsigned i = 0, e = Users.size(); i != e; ++i)
354     if (Instruction *U = dyn_cast<Instruction>(Users[i]))
355       if (L->contains(U->getParent()))
356         U->replaceUsesOfWith(LIC, BoolVal);
357 }