blob: fd75c90d9a482fe0c023988953535b1f40badcd4 [file] [log] [blame]
Chris Lattneree99d152008-04-20 20:35:01 +00001//===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner6c2a5502008-04-20 21:13:06 +000010// This file implements the Jump Threading pass.
Chris Lattneree99d152008-04-20 20:35:01 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
Chris Lattner6c2a5502008-04-20 21:13:06 +000016#include "llvm/IntrinsicInst.h"
Chris Lattneree99d152008-04-20 20:35:01 +000017#include "llvm/Pass.h"
Chris Lattneree23b832008-04-20 22:39:42 +000018#include "llvm/ADT/DenseMap.h"
Chris Lattneree99d152008-04-20 20:35:01 +000019#include "llvm/ADT/Statistic.h"
Chris Lattnerd980e342008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattneree23b832008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattneree99d152008-04-20 20:35:01 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Compiler.h"
Chris Lattner6c2a5502008-04-20 21:13:06 +000024#include "llvm/Support/Debug.h"
Chris Lattneree99d152008-04-20 20:35:01 +000025using namespace llvm;
26
Chris Lattneree23b832008-04-20 22:39:42 +000027STATISTIC(NumThreads, "Number of jumps threaded");
28STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattneree99d152008-04-20 20:35:01 +000029
Chris Lattner6c2a5502008-04-20 21:13:06 +000030static cl::opt<unsigned>
31Threshold("jump-threading-threshold",
32 cl::desc("Max block size to duplicate for jump threading"),
33 cl::init(6), cl::Hidden);
34
Chris Lattneree99d152008-04-20 20:35:01 +000035namespace {
Chris Lattner6c2a5502008-04-20 21:13:06 +000036 /// This pass performs 'jump threading', which looks at blocks that have
37 /// multiple predecessors and multiple successors. If one or more of the
38 /// predecessors of the block can be proven to always jump to one of the
39 /// successors, we forward the edge from the predecessor to the successor by
40 /// duplicating the contents of this block.
41 ///
42 /// An example of when this can occur is code like this:
43 ///
44 /// if () { ...
45 /// X = 4;
46 /// }
47 /// if (X < 3) {
48 ///
49 /// In this case, the unconditional branch at the end of the first if can be
50 /// revectored to the false side of the second if.
51 ///
Chris Lattneree99d152008-04-20 20:35:01 +000052 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
53 public:
54 static char ID; // Pass identification
55 JumpThreading() : FunctionPass((intptr_t)&ID) {}
56
57 bool runOnFunction(Function &F);
Chris Lattneree23b832008-04-20 22:39:42 +000058 bool ThreadBlock(BasicBlock *BB);
59 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattnercbc3a3e2008-04-22 06:36:15 +000060
61 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattneree99d152008-04-20 20:35:01 +000062 };
63 char JumpThreading::ID = 0;
64 RegisterPass<JumpThreading> X("jump-threading", "Jump Threading");
65}
66
67// Public interface to the Jump Threading pass
68FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
69
70/// runOnFunction - Top level algorithm.
71///
72bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner6c2a5502008-04-20 21:13:06 +000073 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattneree23b832008-04-20 22:39:42 +000074
75 bool AnotherIteration = true, EverChanged = false;
76 while (AnotherIteration) {
77 AnotherIteration = false;
78 bool Changed = false;
79 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
80 while (ThreadBlock(I))
81 Changed = true;
82 AnotherIteration = Changed;
83 EverChanged |= Changed;
84 }
85 return EverChanged;
Chris Lattneree99d152008-04-20 20:35:01 +000086}
Chris Lattner6c2a5502008-04-20 21:13:06 +000087
88/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
89/// thread across it.
Chris Lattneree23b832008-04-20 22:39:42 +000090static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
91 BasicBlock::const_iterator I = BB->begin();
Chris Lattner6c2a5502008-04-20 21:13:06 +000092 /// Ignore PHI nodes, these will be flattened when duplication happens.
93 while (isa<PHINode>(*I)) ++I;
94
95 // Sum up the cost of each instruction until we get to the terminator. Don't
96 // include the terminator because the copy won't include it.
97 unsigned Size = 0;
98 for (; !isa<TerminatorInst>(I); ++I) {
99 // Debugger intrinsics don't incur code size.
100 if (isa<DbgInfoIntrinsic>(I)) continue;
101
102 // If this is a pointer->pointer bitcast, it is free.
103 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
104 continue;
105
106 // All other instructions count for at least one unit.
107 ++Size;
108
109 // Calls are more expensive. If they are non-intrinsic calls, we model them
110 // as having cost of 4. If they are a non-vector intrinsic, we model them
111 // as having cost of 2 total, and if they are a vector intrinsic, we model
112 // them as having cost 1.
113 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
114 if (!isa<IntrinsicInst>(CI))
115 Size += 3;
116 else if (isa<VectorType>(CI->getType()))
117 Size += 1;
118 }
119 }
120
121 // Threading through a switch statement is particularly profitable. If this
122 // block ends in a switch, decrease its cost to make it more likely to happen.
123 if (isa<SwitchInst>(I))
124 Size = Size > 6 ? Size-6 : 0;
125
126 return Size;
127}
128
129
130/// ThreadBlock - If there are any predecessors whose control can be threaded
131/// through to a successor, transform them now.
Chris Lattneree23b832008-04-20 22:39:42 +0000132bool JumpThreading::ThreadBlock(BasicBlock *BB) {
Chris Lattner6c2a5502008-04-20 21:13:06 +0000133 // See if this block ends with a branch of switch. If so, see if the
134 // condition is a phi node. If so, and if an entry of the phi node is a
135 // constant, we can thread the block.
136 Value *Condition;
Chris Lattneree23b832008-04-20 22:39:42 +0000137 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
138 // Can't thread an unconditional jump.
139 if (BI->isUnconditional()) return false;
Chris Lattner6c2a5502008-04-20 21:13:06 +0000140 Condition = BI->getCondition();
Chris Lattneree23b832008-04-20 22:39:42 +0000141 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner6c2a5502008-04-20 21:13:06 +0000142 Condition = SI->getCondition();
143 else
144 return false; // Must be an invoke.
Chris Lattneree23b832008-04-20 22:39:42 +0000145
146 // If the terminator of this block is branching on a constant, simplify the
Chris Lattnerb192cc82008-04-21 18:25:01 +0000147 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattneree23b832008-04-20 22:39:42 +0000148 // other blocks.
149 if (isa<ConstantInt>(Condition)) {
150 DOUT << " In block '" << BB->getNameStart()
151 << "' folding terminator: " << *BB->getTerminator();
152 ++NumFolds;
153 ConstantFoldTerminator(BB);
154 return true;
155 }
156
157 // If there is only a single predecessor of this block, nothing to fold.
158 if (BB->getSinglePredecessor())
159 return false;
Chris Lattner6c2a5502008-04-20 21:13:06 +0000160
161 // See if this is a phi node in the current block.
162 PHINode *PN = dyn_cast<PHINode>(Condition);
Chris Lattnercbc3a3e2008-04-22 06:36:15 +0000163 if (PN && PN->getParent() == BB)
164 return ProcessJumpOnPHI(PN);
Chris Lattner6c2a5502008-04-20 21:13:06 +0000165
Chris Lattnercbc3a3e2008-04-22 06:36:15 +0000166 return false;
167}
168
169/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
170/// the current block. See if there are any simplifications we can do based on
171/// inputs to the phi node.
172///
173bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattner0add3212008-04-20 21:18:09 +0000174 // See if the phi node has any constant values. If so, we can determine where
175 // the corresponding predecessor will branch.
176 unsigned PredNo = ~0U;
Chris Lattneree23b832008-04-20 22:39:42 +0000177 ConstantInt *PredCst = 0;
Chris Lattner0add3212008-04-20 21:18:09 +0000178 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattneree23b832008-04-20 22:39:42 +0000179 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i)))) {
Chris Lattner0add3212008-04-20 21:18:09 +0000180 PredNo = i;
181 break;
182 }
183 }
184
185 // If no incoming value has a constant, we don't know the destination of any
186 // predecessors.
187 if (PredNo == ~0U)
188 return false;
189
Chris Lattner6c2a5502008-04-20 21:13:06 +0000190 // See if the cost of duplicating this block is low enough.
Chris Lattnercbc3a3e2008-04-22 06:36:15 +0000191 BasicBlock *BB = PN->getParent();
Chris Lattner6c2a5502008-04-20 21:13:06 +0000192 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
193 if (JumpThreadCost > Threshold) {
Chris Lattneree23b832008-04-20 22:39:42 +0000194 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattner0add3212008-04-20 21:18:09 +0000195 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner6c2a5502008-04-20 21:13:06 +0000196 return false;
197 }
Chris Lattner6c2a5502008-04-20 21:13:06 +0000198
Chris Lattneree23b832008-04-20 22:39:42 +0000199 // If so, we can actually do this threading. Figure out which predecessor and
200 // which successor we are threading for.
201 BasicBlock *PredBB = PN->getIncomingBlock(PredNo);
202 BasicBlock *SuccBB;
203 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
204 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
205 else {
206 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
207 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
208 }
209
Chris Lattnerd980e342008-04-21 02:57:57 +0000210 // If there are multiple preds with the same incoming value for the PHI,
211 // factor them together so we get one block to thread for the whole group.
212 // This is important for things like "phi i1 [true, true, false, true, x]"
213 // where we only need to clone the block for the true blocks once.
214 SmallVector<BasicBlock*, 16> CommonPreds;
215 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
216 if (PN->getIncomingValue(i) == PredCst)
217 CommonPreds.push_back(PN->getIncomingBlock(i));
218 if (CommonPreds.size() != 1) {
219 DOUT << " Factoring out " << CommonPreds.size()
220 << " common predecessors.\n";
221 PredBB = SplitBlockPredecessors(BB, &CommonPreds[0], CommonPreds.size(),
222 ".thr_comm", this);
223 }
224
Chris Lattneree23b832008-04-20 22:39:42 +0000225 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
226 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
227 << ", across block:\n "
228 << *BB;
229
230 ThreadEdge(BB, PredBB, SuccBB);
231 ++NumThreads;
232 return true;
233}
234
235/// ThreadEdge - We have decided that it is safe and profitable to thread an
236/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
237/// change.
238void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
239 BasicBlock *SuccBB) {
240
241 // Jump Threading can not update SSA properties correctly if the values
242 // defined in the duplicated block are used outside of the block itself. For
243 // this reason, we spill all values that are used outside of BB to the stack.
244 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
245 if (I->isUsedOutsideOfBlock(BB)) {
246 // We found a use of I outside of BB. Create a new stack slot to
247 // break this inter-block usage pattern.
248 DemoteRegToStack(*I);
249 }
250
251 // We are going to have to map operands from the original BB block to the new
252 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
253 // account for entry from PredBB.
254 DenseMap<Instruction*, Value*> ValueMapping;
255
256 BasicBlock *NewBB =
257 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
258 NewBB->moveAfter(PredBB);
259
260 BasicBlock::iterator BI = BB->begin();
261 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
262 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
263
264 // Clone the non-phi instructions of BB into NewBB, keeping track of the
265 // mapping and using it to remap operands in the cloned instructions.
266 for (; !isa<TerminatorInst>(BI); ++BI) {
267 Instruction *New = BI->clone();
268 New->setName(BI->getNameStart());
269 NewBB->getInstList().push_back(New);
270 ValueMapping[BI] = New;
271
272 // Remap operands to patch up intra-block references.
273 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
274 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
275 if (Value *Remapped = ValueMapping[Inst])
276 New->setOperand(i, Remapped);
277 }
278
279 // We didn't copy the terminator from BB over to NewBB, because there is now
280 // an unconditional jump to SuccBB. Insert the unconditional jump.
281 BranchInst::Create(SuccBB, NewBB);
282
283 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
284 // PHI nodes for NewBB now.
285 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
286 PHINode *PN = cast<PHINode>(PNI);
287 // Ok, we have a PHI node. Figure out what the incoming value was for the
288 // DestBlock.
289 Value *IV = PN->getIncomingValueForBlock(BB);
290
291 // Remap the value if necessary.
292 if (Instruction *Inst = dyn_cast<Instruction>(IV))
293 if (Value *MappedIV = ValueMapping[Inst])
294 IV = MappedIV;
295 PN->addIncoming(IV, NewBB);
296 }
297
298 // Finally, NewBB is good to go. Update the terminator of PredBB to jump to
299 // NewBB instead of BB. This eliminates predecessors from BB, which requires
300 // us to simplify any PHI nodes in BB.
301 TerminatorInst *PredTerm = PredBB->getTerminator();
302 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
303 if (PredTerm->getSuccessor(i) == BB) {
304 BB->removePredecessor(PredBB);
305 PredTerm->setSuccessor(i, NewBB);
306 }
Chris Lattner6c2a5502008-04-20 21:13:06 +0000307}