1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Jump Threading pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "jump-threading"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/IntrinsicInst.h"
17 #include "llvm/Pass.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/ADT/SmallPtrSet.h"
31 STATISTIC(NumThreads, "Number of jumps threaded");
32 STATISTIC(NumFolds, "Number of terminators folded");
34 static cl::opt<unsigned>
35 Threshold("jump-threading-threshold",
36 cl::desc("Max block size to duplicate for jump threading"),
37 cl::init(6), cl::Hidden);
40 /// This pass performs 'jump threading', which looks at blocks that have
41 /// multiple predecessors and multiple successors. If one or more of the
42 /// predecessors of the block can be proven to always jump to one of the
43 /// successors, we forward the edge from the predecessor to the successor by
44 /// duplicating the contents of this block.
46 /// An example of when this can occur is code like this:
53 /// In this case, the unconditional branch at the end of the first if can be
54 /// revectored to the false side of the second if.
56 class VISIBILITY_HIDDEN JumpThreading : public FunctionPass {
59 static char ID; // Pass identification
60 JumpThreading() : FunctionPass(&ID) {}
62 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<TargetData>();
66 bool runOnFunction(Function &F);
67 bool ProcessBlock(BasicBlock *BB);
68 void ThreadEdge(BasicBlock *BB, BasicBlock *PredBB, BasicBlock *SuccBB);
69 BasicBlock *FactorCommonPHIPreds(PHINode *PN, Constant *CstVal);
71 bool ProcessJumpOnPHI(PHINode *PN);
72 bool ProcessBranchOnLogical(Value *V, BasicBlock *BB, bool isAnd);
73 bool ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB);
75 bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
79 char JumpThreading::ID = 0;
80 static RegisterPass<JumpThreading>
81 X("jump-threading", "Jump Threading");
83 // Public interface to the Jump Threading pass
84 FunctionPass *llvm::createJumpThreadingPass() { return new JumpThreading(); }
86 /// runOnFunction - Top level algorithm.
88 bool JumpThreading::runOnFunction(Function &F) {
89 DOUT << "Jump threading on function '" << F.getNameStart() << "'\n";
90 TD = &getAnalysis<TargetData>();
92 bool AnotherIteration = true, EverChanged = false;
93 while (AnotherIteration) {
94 AnotherIteration = false;
96 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
97 while (ProcessBlock(I))
99 AnotherIteration = Changed;
100 EverChanged |= Changed;
105 /// FactorCommonPHIPreds - If there are multiple preds with the same incoming
106 /// value for the PHI, factor them together so we get one block to thread for
108 /// This is important for things like "phi i1 [true, true, false, true, x]"
109 /// where we only need to clone the block for the true blocks once.
111 BasicBlock *JumpThreading::FactorCommonPHIPreds(PHINode *PN, Constant *CstVal) {
112 SmallVector<BasicBlock*, 16> CommonPreds;
113 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
114 if (PN->getIncomingValue(i) == CstVal)
115 CommonPreds.push_back(PN->getIncomingBlock(i));
117 if (CommonPreds.size() == 1)
118 return CommonPreds[0];
120 DOUT << " Factoring out " << CommonPreds.size()
121 << " common predecessors.\n";
122 return SplitBlockPredecessors(PN->getParent(),
123 &CommonPreds[0], CommonPreds.size(),
128 /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
129 /// thread across it.
130 static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB) {
131 /// Ignore PHI nodes, these will be flattened when duplication happens.
132 BasicBlock::const_iterator I = BB->getFirstNonPHI();
134 // Sum up the cost of each instruction until we get to the terminator. Don't
135 // include the terminator because the copy won't include it.
137 for (; !isa<TerminatorInst>(I); ++I) {
138 // Debugger intrinsics don't incur code size.
139 if (isa<DbgInfoIntrinsic>(I)) continue;
141 // If this is a pointer->pointer bitcast, it is free.
142 if (isa<BitCastInst>(I) && isa<PointerType>(I->getType()))
145 // All other instructions count for at least one unit.
148 // Calls are more expensive. If they are non-intrinsic calls, we model them
149 // as having cost of 4. If they are a non-vector intrinsic, we model them
150 // as having cost of 2 total, and if they are a vector intrinsic, we model
151 // them as having cost 1.
152 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
153 if (!isa<IntrinsicInst>(CI))
155 else if (isa<VectorType>(CI->getType()))
160 // Threading through a switch statement is particularly profitable. If this
161 // block ends in a switch, decrease its cost to make it more likely to happen.
162 if (isa<SwitchInst>(I))
163 Size = Size > 6 ? Size-6 : 0;
168 /// ProcessBlock - If there are any predecessors whose control can be threaded
169 /// through to a successor, transform them now.
170 bool JumpThreading::ProcessBlock(BasicBlock *BB) {
171 // If this block has a single predecessor, and if that pred has a single
172 // successor, merge the blocks. This encourages recursive jump threading
173 // because now the condition in this block can be threaded through
174 // predecessors of our predecessor block.
175 if (BasicBlock *SinglePred = BB->getSinglePredecessor())
176 if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
178 // Remember if SinglePred was the entry block of the function. If so, we
179 // will need to move BB back to the entry position.
180 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
181 MergeBasicBlockIntoOnlyPred(BB);
183 if (isEntry && BB != &BB->getParent()->getEntryBlock())
184 BB->moveBefore(&BB->getParent()->getEntryBlock());
188 // See if this block ends with a branch or switch. If so, see if the
189 // condition is a phi node. If so, and if an entry of the phi node is a
190 // constant, we can thread the block.
192 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
193 // Can't thread an unconditional jump.
194 if (BI->isUnconditional()) return false;
195 Condition = BI->getCondition();
196 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
197 Condition = SI->getCondition();
199 return false; // Must be an invoke.
201 // If the terminator of this block is branching on a constant, simplify the
202 // terminator to an unconditional branch. This can occur due to threading in
204 if (isa<ConstantInt>(Condition)) {
205 DOUT << " In block '" << BB->getNameStart()
206 << "' folding terminator: " << *BB->getTerminator();
208 ConstantFoldTerminator(BB);
212 // If there is only a single predecessor of this block, nothing to fold.
213 if (BB->getSinglePredecessor())
216 // See if this is a phi node in the current block.
217 PHINode *PN = dyn_cast<PHINode>(Condition);
218 if (PN && PN->getParent() == BB)
219 return ProcessJumpOnPHI(PN);
221 // If this is a conditional branch whose condition is and/or of a phi, try to
223 if (BinaryOperator *CondI = dyn_cast<BinaryOperator>(Condition)) {
224 if ((CondI->getOpcode() == Instruction::And ||
225 CondI->getOpcode() == Instruction::Or) &&
226 isa<BranchInst>(BB->getTerminator()) &&
227 ProcessBranchOnLogical(CondI, BB,
228 CondI->getOpcode() == Instruction::And))
232 // If we have "br (phi != 42)" and the phi node has any constant values as
233 // operands, we can thread through this block.
234 if (CmpInst *CondCmp = dyn_cast<CmpInst>(Condition))
235 if (isa<PHINode>(CondCmp->getOperand(0)) &&
236 isa<Constant>(CondCmp->getOperand(1)) &&
237 ProcessBranchOnCompare(CondCmp, BB))
240 // Check for some cases that are worth simplifying. Right now we want to look
241 // for loads that are used by a switch or by the condition for the branch. If
242 // we see one, check to see if it's partially redundant. If so, insert a PHI
243 // which can then be used to thread the values.
245 // This is particularly important because reg2mem inserts loads and stores all
246 // over the place, and this blocks jump threading if we don't zap them.
247 Value *SimplifyValue = Condition;
248 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
249 if (isa<Constant>(CondCmp->getOperand(1)))
250 SimplifyValue = CondCmp->getOperand(0);
252 if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
253 if (SimplifyPartiallyRedundantLoad(LI))
256 // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
257 // "(X == 4)" thread through this block.
262 /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
263 /// load instruction, eliminate it by replacing it with a PHI node. This is an
264 /// important optimization that encourages jump threading, and needs to be run
265 /// interlaced with other jump threading tasks.
266 bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
267 // Don't hack volatile loads.
268 if (LI->isVolatile()) return false;
270 // If the load is defined in a block with exactly one predecessor, it can't be
271 // partially redundant.
272 BasicBlock *LoadBB = LI->getParent();
273 if (LoadBB->getSinglePredecessor())
276 Value *LoadedPtr = LI->getOperand(0);
278 // If the loaded operand is defined in the LoadBB, it can't be available.
279 // FIXME: Could do PHI translation, that would be fun :)
280 if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
281 if (PtrOp->getParent() == LoadBB)
284 // Scan a few instructions up from the load, to see if it is obviously live at
285 // the entry to its block.
286 BasicBlock::iterator BBIt = LI;
288 if (Value *AvailableVal = FindAvailableLoadedValue(LoadedPtr, LoadBB,
290 // If the value if the load is locally available within the block, just use
291 // it. This frequently occurs for reg2mem'd allocas.
292 //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
293 LI->replaceAllUsesWith(AvailableVal);
294 LI->eraseFromParent();
298 // Otherwise, if we scanned the whole block and got to the top of the block,
299 // we know the block is locally transparent to the load. If not, something
300 // might clobber its value.
301 if (BBIt != LoadBB->begin())
305 SmallPtrSet<BasicBlock*, 8> PredsScanned;
306 typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
307 AvailablePredsTy AvailablePreds;
308 BasicBlock *OneUnavailablePred = 0;
310 // If we got here, the loaded value is transparent through to the start of the
311 // block. Check to see if it is available in any of the predecessor blocks.
312 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
314 BasicBlock *PredBB = *PI;
316 // If we already scanned this predecessor, skip it.
317 if (!PredsScanned.insert(PredBB))
320 // Scan the predecessor to see if the value is available in the pred.
321 BBIt = PredBB->end();
322 Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6);
323 if (!PredAvailable) {
324 OneUnavailablePred = PredBB;
328 // If so, this load is partially redundant. Remember this info so that we
329 // can create a PHI node.
330 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
333 // If the loaded value isn't available in any predecessor, it isn't partially
335 if (AvailablePreds.empty()) return false;
337 // Okay, the loaded value is available in at least one (and maybe all!)
338 // predecessors. If the value is unavailable in more than one unique
339 // predecessor, we want to insert a merge block for those common predecessors.
340 // This ensures that we only have to insert one reload, thus not increasing
342 BasicBlock *UnavailablePred = 0;
344 // If there is exactly one predecessor where the value is unavailable, the
345 // already computed 'OneUnavailablePred' block is it. If it ends in an
346 // unconditional branch, we know that it isn't a critical edge.
347 if (PredsScanned.size() == AvailablePreds.size()+1 &&
348 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
349 UnavailablePred = OneUnavailablePred;
350 } else if (PredsScanned.size() != AvailablePreds.size()) {
351 // Otherwise, we had multiple unavailable predecessors or we had a critical
352 // edge from the one.
353 SmallVector<BasicBlock*, 8> PredsToSplit;
354 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
356 for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
357 AvailablePredSet.insert(AvailablePreds[i].first);
359 // Add all the unavailable predecessors to the PredsToSplit list.
360 for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
362 if (!AvailablePredSet.count(*PI))
363 PredsToSplit.push_back(*PI);
365 // Split them out to their own block.
367 SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
368 "thread-split", this);
371 // If the value isn't available in all predecessors, then there will be
372 // exactly one where it isn't available. Insert a load on that edge and add
373 // it to the AvailablePreds list.
374 if (UnavailablePred) {
375 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
376 "Can't handle critical edge here!");
377 Value *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr",
378 UnavailablePred->getTerminator());
379 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
382 // Now we know that each predecessor of this block has a value in
383 // AvailablePreds, sort them for efficient access as we're walking the preds.
384 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
386 // Create a PHI node at the start of the block for the PRE'd load value.
387 PHINode *PN = PHINode::Create(LI->getType(), "", LoadBB->begin());
390 // Insert new entries into the PHI for each predecessor. A single block may
391 // have multiple entries here.
392 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
394 AvailablePredsTy::iterator I =
395 std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
396 std::make_pair(*PI, (Value*)0));
398 assert(I != AvailablePreds.end() && I->first == *PI &&
399 "Didn't find entry for predecessor!");
401 PN->addIncoming(I->second, I->first);
404 //cerr << "PRE: " << *LI << *PN << "\n";
406 LI->replaceAllUsesWith(PN);
407 LI->eraseFromParent();
413 /// ProcessJumpOnPHI - We have a conditional branch of switch on a PHI node in
414 /// the current block. See if there are any simplifications we can do based on
415 /// inputs to the phi node.
417 bool JumpThreading::ProcessJumpOnPHI(PHINode *PN) {
418 // See if the phi node has any constant values. If so, we can determine where
419 // the corresponding predecessor will branch.
420 ConstantInt *PredCst = 0;
421 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
422 if ((PredCst = dyn_cast<ConstantInt>(PN->getIncomingValue(i))))
425 // If no incoming value has a constant, we don't know the destination of any
430 // See if the cost of duplicating this block is low enough.
431 BasicBlock *BB = PN->getParent();
432 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
433 if (JumpThreadCost > Threshold) {
434 DOUT << " Not threading BB '" << BB->getNameStart()
435 << "' - Cost is too high: " << JumpThreadCost << "\n";
439 // If so, we can actually do this threading. Merge any common predecessors
440 // that will act the same.
441 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
443 // Next, figure out which successor we are threading to.
445 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
446 SuccBB = BI->getSuccessor(PredCst == ConstantInt::getFalse());
448 SwitchInst *SI = cast<SwitchInst>(BB->getTerminator());
449 SuccBB = SI->getSuccessor(SI->findCaseValue(PredCst));
452 // If threading to the same block as we come from, we would infinite loop.
454 DOUT << " Not threading BB '" << BB->getNameStart()
455 << "' - would thread to self!\n";
459 // And finally, do it!
460 DOUT << " Threading edge from '" << PredBB->getNameStart() << "' to '"
461 << SuccBB->getNameStart() << "' with cost: " << JumpThreadCost
462 << ", across block:\n "
465 ThreadEdge(BB, PredBB, SuccBB);
470 /// ProcessJumpOnLogicalPHI - PN's basic block contains a conditional branch
471 /// whose condition is an AND/OR where one side is PN. If PN has constant
472 /// operands that permit us to evaluate the condition for some operand, thread
473 /// through the block. For example with:
474 /// br (and X, phi(Y, Z, false))
475 /// the predecessor corresponding to the 'false' will always jump to the false
476 /// destination of the branch.
478 bool JumpThreading::ProcessBranchOnLogical(Value *V, BasicBlock *BB,
480 // If this is a binary operator tree of the same AND/OR opcode, check the
482 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
483 if ((isAnd && BO->getOpcode() == Instruction::And) ||
484 (!isAnd && BO->getOpcode() == Instruction::Or)) {
485 if (ProcessBranchOnLogical(BO->getOperand(0), BB, isAnd))
487 if (ProcessBranchOnLogical(BO->getOperand(1), BB, isAnd))
491 // If this isn't a PHI node, we can't handle it.
492 PHINode *PN = dyn_cast<PHINode>(V);
493 if (!PN || PN->getParent() != BB) return false;
495 // We can only do the simplification for phi nodes of 'false' with AND or
496 // 'true' with OR. See if we have any entries in the phi for this.
497 unsigned PredNo = ~0U;
498 ConstantInt *PredCst = ConstantInt::get(Type::Int1Ty, !isAnd);
499 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
500 if (PN->getIncomingValue(i) == PredCst) {
506 // If no match, bail out.
510 // See if the cost of duplicating this block is low enough.
511 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
512 if (JumpThreadCost > Threshold) {
513 DOUT << " Not threading BB '" << BB->getNameStart()
514 << "' - Cost is too high: " << JumpThreadCost << "\n";
518 // If so, we can actually do this threading. Merge any common predecessors
519 // that will act the same.
520 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
522 // Next, figure out which successor we are threading to. If this was an AND,
523 // the constant must be FALSE, and we must be targeting the 'false' block.
524 // If this is an OR, the constant must be TRUE, and we must be targeting the
526 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(isAnd);
528 // If threading to the same block as we come from, we would infinite loop.
530 DOUT << " Not threading BB '" << BB->getNameStart()
531 << "' - would thread to self!\n";
535 // And finally, do it!
536 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
537 << "' to '" << SuccBB->getNameStart() << "' with cost: "
538 << JumpThreadCost << ", across block:\n "
541 ThreadEdge(BB, PredBB, SuccBB);
546 /// ProcessBranchOnCompare - We found a branch on a comparison between a phi
547 /// node and a constant. If the PHI node contains any constants as inputs, we
548 /// can fold the compare for that edge and thread through it.
549 bool JumpThreading::ProcessBranchOnCompare(CmpInst *Cmp, BasicBlock *BB) {
550 PHINode *PN = cast<PHINode>(Cmp->getOperand(0));
551 Constant *RHS = cast<Constant>(Cmp->getOperand(1));
553 // If the phi isn't in the current block, an incoming edge to this block
554 // doesn't control the destination.
555 if (PN->getParent() != BB)
558 // We can do this simplification if any comparisons fold to true or false.
560 Constant *PredCst = 0;
561 bool TrueDirection = false;
562 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
563 PredCst = dyn_cast<Constant>(PN->getIncomingValue(i));
564 if (PredCst == 0) continue;
567 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cmp))
568 Res = ConstantExpr::getICmp(ICI->getPredicate(), PredCst, RHS);
570 Res = ConstantExpr::getFCmp(cast<FCmpInst>(Cmp)->getPredicate(),
572 // If this folded to a constant expr, we can't do anything.
573 if (ConstantInt *ResC = dyn_cast<ConstantInt>(Res)) {
574 TrueDirection = ResC->getZExtValue();
577 // If this folded to undef, just go the false way.
578 if (isa<UndefValue>(Res)) {
579 TrueDirection = false;
583 // Otherwise, we can't fold this input.
587 // If no match, bail out.
591 // See if the cost of duplicating this block is low enough.
592 unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB);
593 if (JumpThreadCost > Threshold) {
594 DOUT << " Not threading BB '" << BB->getNameStart()
595 << "' - Cost is too high: " << JumpThreadCost << "\n";
599 // If so, we can actually do this threading. Merge any common predecessors
600 // that will act the same.
601 BasicBlock *PredBB = FactorCommonPHIPreds(PN, PredCst);
603 // Next, get our successor.
604 BasicBlock *SuccBB = BB->getTerminator()->getSuccessor(!TrueDirection);
606 // If threading to the same block as we come from, we would infinite loop.
608 DOUT << " Not threading BB '" << BB->getNameStart()
609 << "' - would thread to self!\n";
614 // And finally, do it!
615 DOUT << " Threading edge through bool from '" << PredBB->getNameStart()
616 << "' to '" << SuccBB->getNameStart() << "' with cost: "
617 << JumpThreadCost << ", across block:\n "
620 ThreadEdge(BB, PredBB, SuccBB);
626 /// ThreadEdge - We have decided that it is safe and profitable to thread an
627 /// edge from PredBB to SuccBB across BB. Transform the IR to reflect this
629 void JumpThreading::ThreadEdge(BasicBlock *BB, BasicBlock *PredBB,
630 BasicBlock *SuccBB) {
632 // Jump Threading can not update SSA properties correctly if the values
633 // defined in the duplicated block are used outside of the block itself. For
634 // this reason, we spill all values that are used outside of BB to the stack.
635 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
636 if (!I->isUsedOutsideOfBlock(BB))
639 // We found a use of I outside of BB. Create a new stack slot to
640 // break this inter-block usage pattern.
641 DemoteRegToStack(*I);
644 // We are going to have to map operands from the original BB block to the new
645 // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
646 // account for entry from PredBB.
647 DenseMap<Instruction*, Value*> ValueMapping;
650 BasicBlock::Create(BB->getName()+".thread", BB->getParent(), BB);
651 NewBB->moveAfter(PredBB);
653 BasicBlock::iterator BI = BB->begin();
654 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
655 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
657 // Clone the non-phi instructions of BB into NewBB, keeping track of the
658 // mapping and using it to remap operands in the cloned instructions.
659 for (; !isa<TerminatorInst>(BI); ++BI) {
660 Instruction *New = BI->clone();
661 New->setName(BI->getNameStart());
662 NewBB->getInstList().push_back(New);
663 ValueMapping[BI] = New;
665 // Remap operands to patch up intra-block references.
666 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
667 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i)))
668 if (Value *Remapped = ValueMapping[Inst])
669 New->setOperand(i, Remapped);
672 // We didn't copy the terminator from BB over to NewBB, because there is now
673 // an unconditional jump to SuccBB. Insert the unconditional jump.
674 BranchInst::Create(SuccBB, NewBB);
676 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
677 // PHI nodes for NewBB now.
678 for (BasicBlock::iterator PNI = SuccBB->begin(); isa<PHINode>(PNI); ++PNI) {
679 PHINode *PN = cast<PHINode>(PNI);
680 // Ok, we have a PHI node. Figure out what the incoming value was for the
682 Value *IV = PN->getIncomingValueForBlock(BB);
684 // Remap the value if necessary.
685 if (Instruction *Inst = dyn_cast<Instruction>(IV))
686 if (Value *MappedIV = ValueMapping[Inst])
688 PN->addIncoming(IV, NewBB);
691 // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
692 // NewBB instead of BB. This eliminates predecessors from BB, which requires
693 // us to simplify any PHI nodes in BB.
694 TerminatorInst *PredTerm = PredBB->getTerminator();
695 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
696 if (PredTerm->getSuccessor(i) == BB) {
697 BB->removePredecessor(PredBB);
698 PredTerm->setSuccessor(i, NewBB);
701 // At this point, the IR is fully up to date and consistent. Do a quick scan
702 // over the new instructions and zap any that are constants or dead. This
703 // frequently happens because of phi translation.
705 for (BasicBlock::iterator E = NewBB->end(); BI != E; ) {
706 Instruction *Inst = BI++;
707 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
708 Inst->replaceAllUsesWith(C);
709 Inst->eraseFromParent();
713 RecursivelyDeleteTriviallyDeadInstructions(Inst);