blob: 991b11110b41eec883c6c2b550bf0437f1fa456d [file] [log] [blame]
Chris Lattner8383a7b2008-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 Lattner177480b2008-04-20 21:13:06 +000010// This file implements the Jump Threading pass.
Chris Lattner8383a7b2008-04-20 20:35:01 +000011//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "jump-threading"
15#include "llvm/Transforms/Scalar.h"
Chris Lattner177480b2008-04-20 21:13:06 +000016#include "llvm/IntrinsicInst.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000017#include "llvm/Pass.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000018#include "llvm/ADT/DenseMap.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000019#include "llvm/ADT/Statistic.h"
Chris Lattner2cc67512008-04-21 02:57:57 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerbd3401f2008-04-20 22:39:42 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Compiler.h"
Chris Lattner177480b2008-04-20 21:13:06 +000024#include "llvm/Support/Debug.h"
Chris Lattner8383a7b2008-04-20 20:35:01 +000025using namespace llvm;
26
Chris Lattnerbd3401f2008-04-20 22:39:42 +000027STATISTIC(NumThreads, "Number of jumps threaded");
28STATISTIC(NumFolds, "Number of terminators folded");
Chris Lattner8383a7b2008-04-20 20:35:01 +000029
Chris Lattner177480b2008-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 Lattner8383a7b2008-04-20 20:35:01 +000035namespace {
Chris Lattner177480b2008-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 Lattner8383a7b2008-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 Lattnerbd3401f2008-04-20 22:39:42 +000058 bool ThreadBlock(BasicBlock *BB);
59 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
Chris Lattner6bf77502008-04-22 07:05:46 +000060 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
61
Chris Lattnerd38c14e2008-04-22 06:36:15 +000062 bool ProcessJumpOnPHI(PHINode *PN);
Chris Lattnerae65b3c2008-04-22 20:46:09 +000063 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
Chris Lattnera5ddb592008-04-22 21:40:39 +000064 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
Chris Lattner8383a7b2008-04-20 20:35:01 +000065 };
66 char JumpThreading::ID = 0;
67 RegisterPass<JumpThreading> X("jump-threading", "Jump Threading");
68}
69
70// Public interface to the Jump Threading pass
71FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
72
73/// runOnFunction - Top level algorithm.
74///
75bool JumpThreading::runOnFunction(Function &F) {
Chris Lattner177480b2008-04-20 21:13:06 +000076 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +000077
78 bool AnotherIteration = true, EverChanged = false;
79 while (AnotherIteration) {
80 AnotherIteration = false;
81 bool Changed = false;
82 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
83 while (ThreadBlock(I))
84 Changed = true;
85 AnotherIteration = Changed;
86 EverChanged |= Changed;
87 }
88 return EverChanged;
Chris Lattner8383a7b2008-04-20 20:35:01 +000089}
Chris Lattner177480b2008-04-20 21:13:06 +000090
Chris Lattner6bf77502008-04-22 07:05:46 +000091/// FactorCommonPHIPreds - If there are multiple preds with the same incoming
92/// value for the PHI, factor them together so we get one block to thread for
93/// the whole group.
94/// This is important for things like "phi i1 [true, true, false, true, x]"
95/// where we only need to clone the block for the true blocks once.
96///
97BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
98 SmallVector<BasicBlock*, 16> CommonPreds;
99 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
100 if (PN->getIncomingValue(i) == CstVal)
101 CommonPreds.push_back(PN->getIncomingBlock(i));
102
103 if (CommonPreds.size() == 1)
104 return CommonPreds[0];
105
106 DOUT << " Factoring out " << CommonPreds.size()
107 << " common predecessors.\n";
108 return SplitBlockPredecessors(PN->getParent(),
109 &CommonPreds[0], CommonPreds.size(),
110 ".thr_comm", this);
111}
112
113
Chris Lattner177480b2008-04-20 21:13:06 +0000114/// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
115/// thread across it.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000116static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
117 BasicBlock::const_iterator I = BB->begin();
Chris Lattner177480b2008-04-20 21:13:06 +0000118 /// Ignore PHI nodes, these will be flattened when duplication happens.
119 while (isa<PHINode>(*I)) ++I;
120
121 // Sum up the cost of each instruction until we get to the terminator. Don't
122 // include the terminator because the copy won't include it.
123 unsigned Size = 0;
124 for (; !isa<TerminatorInst>(I); ++I) {
125 // Debugger intrinsics don't incur code size.
126 if (isa<DbgInfoIntrinsic>(I)) continue;
127
128 // If this is a pointer->pointer bitcast, it is free.
129 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
130 continue;
131
132 // All other instructions count for at least one unit.
133 ++Size;
134
135 // Calls are more expensive. If they are non-intrinsic calls, we model them
136 // as having cost of 4. If they are a non-vector intrinsic, we model them
137 // as having cost of 2 total, and if they are a vector intrinsic, we model
138 // them as having cost 1.
139 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
140 if (!isa<IntrinsicInst>(CI))
141 Size += 3;
142 else if (isa<VectorType>(CI->getType()))
143 Size += 1;
144 }
145 }
146
147 // Threading through a switch statement is particularly profitable. If this
148 // block ends in a switch, decrease its cost to make it more likely to happen.
149 if (isa<SwitchInst>(I))
150 Size = Size > 6 ? Size-6 : 0;
151
152 return Size;
153}
154
155
156/// ThreadBlock - If there are any predecessors whose control can be threaded
157/// through to a successor, transform them now.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000158bool JumpThreading::ThreadBlock(BasicBlock *BB) {
Chris Lattner177480b2008-04-20 21:13:06 +0000159 // See if this block ends with a branch of switch. If so, see if the
160 // condition is a phi node. If so, and if an entry of the phi node is a
161 // constant, we can thread the block.
162 Value *Condition;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000163 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
164 // Can't thread an unconditional jump.
165 if (BI->isUnconditional()) return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000166 Condition = BI->getCondition();
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000167 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
Chris Lattner177480b2008-04-20 21:13:06 +0000168 Condition = SI->getCondition();
169 else
170 return false; // Must be an invoke.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000171
172 // If the terminator of this block is branching on a constant, simplify the
Chris Lattner037c7812008-04-21 18:25:01 +0000173 // terminator to an unconditional branch. This can occur due to threading in
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000174 // other blocks.
175 if (isa<ConstantInt>(Condition)) {
176 DOUT << " In block '" << BB->getNameStart()
177 << "' folding terminator: " << *BB->getTerminator();
178 ++NumFolds;
179 ConstantFoldTerminator(BB);
180 return true;
181 }
182
183 // If there is only a single predecessor of this block, nothing to fold.
184 if (BB->getSinglePredecessor())
185 return false;
Chris Lattner177480b2008-04-20 21:13:06 +0000186
187 // See if this is a phi node in the current block.
188 PHINode *PN = dyn_cast<PHINode>(Condition);
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000189 if (PN && PN->getParent() == BB)
190 return ProcessJumpOnPHI(PN);
Chris Lattner177480b2008-04-20 21:13:06 +0000191
Chris Lattner6bf77502008-04-22 07:05:46 +0000192 // If this is a conditional branch whose condition is and/or of a phi, try to
193 // simplify it.
194 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
195 if ((CondI->getOpcode() == Instruction::And ||
196 CondI->getOpcode() == Instruction::Or) &&
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000197 isa<BranchInst>(BB->getTerminator()) &&
198 ProcessBranchOnLogical(CondI, BB,
199 CondI->getOpcode() == Instruction::And))
200 return true;
Chris Lattner6bf77502008-04-22 07:05:46 +0000201 }
202
Chris Lattnera5ddb592008-04-22 21:40:39 +0000203 // If we have "br (phi != 42)" and the phi node has any constant values as
204 // operands, we can thread through this block.
205 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
206 if (isa<PHINode>(CondCmp->getOperand(0)) &&
207 isa<Constant>(CondCmp->getOperand(1)) &&
208 ProcessBranchOnCompare(CondCmp, BB))
209 return true;
210
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000211 return false;
212}
213
214/// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
215/// the current block. See if there are any simplifications we can do based on
216/// inputs to the phi node.
217///
218bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
Chris Lattnerf9065a92008-04-20 21:18:09 +0000219 // See if the phi node has any constant values. If so, we can determine where
220 // the corresponding predecessor will branch.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000221 ConstantInt *PredCst = 0;
Chris Lattnera5ddb592008-04-22 21:40:39 +0000222 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
223 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
Chris Lattnerf9065a92008-04-20 21:18:09 +0000224 break;
Chris Lattnerf9065a92008-04-20 21:18:09 +0000225
226 // If no incoming value has a constant, we don't know the destination of any
227 // predecessors.
Chris Lattnera5ddb592008-04-22 21:40:39 +0000228 if (PredCst == 0)
Chris Lattnerf9065a92008-04-20 21:18:09 +0000229 return false;
230
Chris Lattner177480b2008-04-20 21:13:06 +0000231 // See if the cost of duplicating this block is low enough.
Chris Lattnerd38c14e2008-04-22 06:36:15 +0000232 BasicBlock *BB = PN->getParent();
Chris Lattner177480b2008-04-20 21:13:06 +0000233 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
234 if (JumpThreadCost > Threshold) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000235 DOUT << " Not threading BB '" << BB->getNameStart()
Chris Lattnerf9065a92008-04-20 21:18:09 +0000236 << "' - Cost is too high: " << JumpThreadCost << "\n";
Chris Lattner177480b2008-04-20 21:13:06 +0000237 return false;
238 }
Chris Lattner177480b2008-04-20 21:13:06 +0000239
Chris Lattner6bf77502008-04-22 07:05:46 +0000240 // If so, we can actually do this threading. Merge any common predecessors
241 // that will act the same.
242 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
243
244 // Next, figure out which successor we are threading to.
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000245 BasicBlock *SuccBB;
246 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
247 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
248 else {
249 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
250 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
251 }
252
Chris Lattnereede65c2008-04-25 04:12:29 +0000253 // If threading to the same block as we come from, we would infinite loop.
254 if (SuccBB == BB) {
255 DOUT << " Not threading BB '" << BB->getNameStart()
256 << "' - would thread to self!\n";
257 return false;
258 }
259
Chris Lattner6bf77502008-04-22 07:05:46 +0000260 // And finally, do it!
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000261 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
262 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
263 << ", across block:\n "
Chris Lattner6bf77502008-04-22 07:05:46 +0000264 << *BB << "\n";
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000265
266 ThreadEdge(BB, PredBB, SuccBB);
267 ++NumThreads;
268 return true;
269}
270
Chris Lattner6bf77502008-04-22 07:05:46 +0000271/// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
272/// whose condition is an AND/OR where one side is PN. If PN has constant
273/// operands that permit us to evaluate the condition for some operand, thread
274/// through the block. For example with:
275/// br (and X, phi(Y, Z, false))
276/// the predecessor corresponding to the 'false' will always jump to the false
277/// destination of the branch.
278///
Chris Lattnerae65b3c2008-04-22 20:46:09 +0000279bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
280 bool isAnd) {
281 // If this is a binary operator tree of the same AND/OR opcode, check the
282 // LHS/RHS.
283 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
284 if (isAnd && BO->getOpcode() == Instruction::And ||
285 !isAnd && BO->getOpcode() == Instruction::Or) {
286 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
287 return true;
288 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
289 return true;
290 }
291
292 // If this isn't a PHI node, we can't handle it.
293 PHINode *PN = dyn_cast<PHINode>(V);
294 if (!PN || PN->getParent() != BB) return false;
295
Chris Lattner6bf77502008-04-22 07:05:46 +0000296 // We can only do the simplification for phi nodes of 'false' with AND or
297 // 'true' with OR. See if we have any entries in the phi for this.
298 unsigned PredNo = ~0U;
299 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
300 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
301 if (PN->getIncomingValue(i) == PredCst) {
302 PredNo = i;
303 break;
304 }
305 }
306
307 // If no match, bail out.
308 if (PredNo == ~0U)
309 return false;
310
311 // See if the cost of duplicating this block is low enough.
Chris Lattner6bf77502008-04-22 07:05:46 +0000312 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
313 if (JumpThreadCost > Threshold) {
314 DOUT << " Not threading BB '" << BB->getNameStart()
315 << "' - Cost is too high: " << JumpThreadCost << "\n";
316 return false;
317 }
318
319 // If so, we can actually do this threading. Merge any common predecessors
320 // that will act the same.
321 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
322
323 // Next, figure out which successor we are threading to. If this was an AND,
324 // the constant must be FALSE, and we must be targeting the 'false' block.
325 // If this is an OR, the constant must be TRUE, and we must be targeting the
326 // 'true' block.
327 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
328
Chris Lattnereede65c2008-04-25 04:12:29 +0000329 // If threading to the same block as we come from, we would infinite loop.
330 if (SuccBB == BB) {
331 DOUT << " Not threading BB '" << BB->getNameStart()
332 << "' - would thread to self!\n";
333 return false;
334 }
335
Chris Lattner6bf77502008-04-22 07:05:46 +0000336 // And finally, do it!
337 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
338 << "' to '" << SuccBB->getNameStart() << "' with cost: "
339 << JumpThreadCost << ", across block:\n "
340 << *BB << "\n";
341
342 ThreadEdge(BB, PredBB, SuccBB);
343 ++NumThreads;
344 return true;
345}
346
Chris Lattnera5ddb592008-04-22 21:40:39 +0000347/// ProcessBranchOnCompare - We found a branch on a comparison between a phi
348/// node and a constant. If the PHI node contains any constants as inputs, we
349/// can fold the compare for that edge and thread through it.
350bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
351 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
352 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
353
354 // If the phi isn't in the current block, an incoming edge to this block
355 // doesn't control the destination.
356 if (PN->getParent() != BB)
357 return false;
358
359 // We can do this simplification if any comparisons fold to true or false.
360 // See if any do.
361 Constant *PredCst = 0;
362 bool TrueDirection = false;
363 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
364 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
365 if (PredCst == 0) continue;
366
367 Constant *Res;
368 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
369 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
370 else
371 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
372 PredCst, RHS);
373 // If this folded to a constant expr, we can't do anything.
374 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
375 TrueDirection = ResC->getZExtValue();
376 break;
377 }
378 // If this folded to undef, just go the false way.
379 if (isa<UndefValue>(Res)) {
380 TrueDirection = false;
381 break;
382 }
383
384 // Otherwise, we can't fold this input.
385 PredCst = 0;
386 }
387
388 // If no match, bail out.
389 if (PredCst == 0)
390 return false;
391
392 // See if the cost of duplicating this block is low enough.
393 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
394 if (JumpThreadCost > Threshold) {
395 DOUT << " Not threading BB '" << BB->getNameStart()
396 << "' - Cost is too high: " << JumpThreadCost << "\n";
397 return false;
398 }
399
400 // If so, we can actually do this threading. Merge any common predecessors
401 // that will act the same.
402 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
403
404 // Next, get our successor.
405 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
406
Chris Lattnereede65c2008-04-25 04:12:29 +0000407 // If threading to the same block as we come from, we would infinite loop.
408 if (SuccBB == BB) {
409 DOUT << " Not threading BB '" << BB->getNameStart()
410 << "' - would thread to self!\n";
411 return false;
412 }
413
414
Chris Lattnera5ddb592008-04-22 21:40:39 +0000415 // And finally, do it!
416 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
417 << "' to '" << SuccBB->getNameStart() << "' with cost: "
418 << JumpThreadCost << ", across block:\n "
419 << *BB << "\n";
420
421 ThreadEdge(BB, PredBB, SuccBB);
422 ++NumThreads;
423 return true;
424}
425
Chris Lattner6bf77502008-04-22 07:05:46 +0000426
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000427/// ThreadEdge - We have decided that it is safe and profitable to thread an
428/// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
429/// change.
430void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
431 BasicBlock *SuccBB) {
432
433 // Jump Threading can not update SSA properties correctly if the values
434 // defined in the duplicated block are used outside of the block itself. For
435 // this reason, we spill all values that are used outside of BB to the stack.
Chris Lattner8554cc22008-05-05 20:21:22 +0000436 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
437 if (!I->isUsedOutsideOfBlock(BB))
438 continue;
439
440 // We found a use of I outside of BB. Create a new stack slot to
441 // break this inter-block usage pattern.
442 if (!isa<StructType>(I->getType())) {
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000443 DemoteRegToStack(*I);
Chris Lattner8554cc22008-05-05 20:21:22 +0000444 continue;
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000445 }
Chris Lattner8554cc22008-05-05 20:21:22 +0000446
447 // Alternatively, I must be a call or invoke that returns multiple retvals.
Chris Lattner9b348492008-05-06 02:31:18 +0000448 // We can't use 'DemoteRegToStack' because that will create loads and
Chris Lattner8554cc22008-05-05 20:21:22 +0000449 // stores of aggregates which is not valid yet. If I is a call, we can just
450 // pull all the getresult instructions up to this block. If I is an invoke,
451 // we are out of luck.
452 BasicBlock::iterator IP = I; ++IP;
453 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
454 UI != E; ++UI)
455 cast<GetResultInst>(UI)->moveBefore(IP);
456 }
Chris Lattnerbd3401f2008-04-20 22:39:42 +0000457
458 // We are going to have to map operands from the original BB block to the new
459 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
460 // account for entry from PredBB.
461 DenseMap<Instruction*, Value*> ValueMapping;
462
463 BasicBlock *NewBB =
464 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
465 NewBB->moveAfter(PredBB);
466
467 BasicBlock::iterator BI = BB->begin();
468 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
469 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
470
471 // Clone the non-phi instructions of BB into NewBB, keeping track of the
472 // mapping and using it to remap operands in the cloned instructions.
473 for (; !isa<TerminatorInst>(BI); ++BI) {
474 Instruction *New = BI->clone();
475 New->setName(BI->getNameStart());
476 NewBB->getInstList().push_back(New);
477 ValueMapping[BI] = New;
478
479 // Remap operands to patch up intra-block references.
480 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
481 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
482 if (Value *Remapped = ValueMapping[Inst])
483 New->setOperand(i, Remapped);
484 }
485
486 // We didn't copy the terminator from BB over to NewBB, because there is now
487 // an unconditional jump to SuccBB. Insert the unconditional jump.
488 BranchInst::Create(SuccBB, NewBB);
489
490 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
491 // PHI nodes for NewBB now.
492 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
493 PHINode *PN = cast<PHINode>(PNI);
494 // Ok, we have a PHI node. Figure out what the incoming value was for the
495 // DestBlock.
496 Value *IV = PN->getIncomingValueForBlock(BB);
497
498 // Remap the value if necessary.
499 if (Instruction *Inst = dyn_cast<Instruction>(IV))
500 if (Value *MappedIV = ValueMapping[Inst])
501 IV = MappedIV;
502 PN->addIncoming(IV, NewBB);
503 }
504
505 // Finally, NewBB is good to go. Update the terminator of PredBB to jump to
506 // NewBB instead of BB. This eliminates predecessors from BB, which requires
507 // us to simplify any PHI nodes in BB.
508 TerminatorInst *PredTerm = PredBB->getTerminator();
509 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
510 if (PredTerm->getSuccessor(i) == BB) {
511 BB->removePredecessor(PredBB);
512 PredTerm->setSuccessor(i, NewBB);
513 }
Chris Lattner177480b2008-04-20 21:13:06 +0000514}