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