blob: c28b02755677b2d80a61e14e57bd256b7b78f6f8 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
16#include "llvm/Function.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Dale Johannesenbd8e6502009-03-03 01:09:07 +000018#include "llvm/IntrinsicInst.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000019#include "llvm/Constant.h"
20#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000021#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000022#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/Dominators.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000024#include "llvm/Target/TargetData.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000025#include "llvm/Transforms/Utils/Local.h"
Dan Gohman5c89b522009-09-08 15:45:00 +000026#include "llvm/Transforms/Scalar.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000028#include "llvm/Support/ValueHandle.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000029#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattner71af9b02008-12-03 06:40:52 +000032/// DeleteDeadBlock - Delete the specified block, which must have no
33/// predecessors.
34void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000035 assert((pred_begin(BB) == pred_end(BB) ||
36 // Can delete self loop.
37 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000038 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patel5622f072009-02-24 00:05:16 +000039
Chris Lattner2b1ba242008-12-03 06:37:44 +000040 // Loop through all of our successors and make sure they know that one
41 // of their predecessors is going away.
42 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
43 BBTerm->getSuccessor(i)->removePredecessor(BB);
44
45 // Zap all the instructions in the block.
46 while (!BB->empty()) {
47 Instruction &I = BB->back();
48 // If this instruction is used, replace uses with an arbitrary value.
49 // Because control flow can't get here, we don't care what we replace the
50 // value with. Note that since this block is unreachable, and all values
51 // contained within it must dominate their uses, that all uses will
52 // eventually be removed (they are themselves dead).
53 if (!I.use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000054 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner2b1ba242008-12-03 06:37:44 +000055 BB->getInstList().pop_back();
56 }
Devang Patel5622f072009-02-24 00:05:16 +000057
Chris Lattner2b1ba242008-12-03 06:37:44 +000058 // Zap the block!
59 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000060}
61
Chris Lattner29874e02008-12-03 19:44:02 +000062/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
63/// any single-entry PHI nodes in it, fold them away. This handles the case
64/// when all entries to the PHI nodes in a block are guaranteed equal, such as
65/// when the block has exactly one predecessor.
66void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
Chris Lattner29874e02008-12-03 19:44:02 +000067 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
68 if (PN->getIncomingValue(0) != PN)
69 PN->replaceAllUsesWith(PN->getIncomingValue(0));
70 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000071 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner29874e02008-12-03 19:44:02 +000072 PN->eraseFromParent();
73 }
74}
75
76
Dan Gohmanafc36a92009-05-02 18:29:22 +000077/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
78/// is dead. Also recursively delete any operands that become dead as
79/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000080/// it is ultimately unused or if it reaches an unused cycle.
Dan Gohman90fe0bd2010-01-05 15:45:31 +000081bool llvm::DeleteDeadPHIs(BasicBlock *BB) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000082 // Recursively deleting a PHI may cause multiple PHIs to be deleted
83 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
84 SmallVector<WeakVH, 8> PHIs;
85 for (BasicBlock::iterator I = BB->begin();
86 PHINode *PN = dyn_cast<PHINode>(I); ++I)
87 PHIs.push_back(PN);
88
Dan Gohman90fe0bd2010-01-05 15:45:31 +000089 bool Changed = false;
Dan Gohmanafc36a92009-05-02 18:29:22 +000090 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
91 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman90fe0bd2010-01-05 15:45:31 +000092 Changed |= RecursivelyDeleteDeadPHINode(PN);
93
94 return Changed;
Dan Gohmanafc36a92009-05-02 18:29:22 +000095}
96
Dan Gohman438b5832009-10-31 17:33:01 +000097/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
98/// if possible. The return value indicates success or failure.
Chris Lattner88202922009-11-01 04:57:33 +000099bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
Dan Gohman1c034dc2010-08-17 17:07:02 +0000100 // Don't merge away blocks who have their address taken.
101 if (BB->hasAddressTaken()) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000102
Dan Gohman1c034dc2010-08-17 17:07:02 +0000103 // Can't merge if there are multiple predecessors, or no predecessors.
104 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman438b5832009-10-31 17:33:01 +0000105 if (!PredBB) return false;
Dan Gohman1c034dc2010-08-17 17:07:02 +0000106
Dan Gohman438b5832009-10-31 17:33:01 +0000107 // Don't break self-loops.
108 if (PredBB == BB) return false;
109 // Don't break invokes.
110 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
111
112 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
113 BasicBlock* OnlySucc = BB;
114 for (; SI != SE; ++SI)
115 if (*SI != OnlySucc) {
116 OnlySucc = 0; // There are multiple distinct successors!
117 break;
118 }
119
120 // Can't merge if there are multiple successors.
121 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000122
Dan Gohman438b5832009-10-31 17:33:01 +0000123 // Can't merge if there is PHI loop.
124 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
125 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
126 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
127 if (PN->getIncomingValue(i) == PN)
128 return false;
129 } else
130 break;
131 }
132
133 // Begin by getting rid of unneeded PHIs.
134 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
135 PN->replaceAllUsesWith(PN->getIncomingValue(0));
136 BB->getInstList().pop_front(); // Delete the phi node...
137 }
138
Owen Andersonb31b06d2008-07-17 00:01:40 +0000139 // Delete the unconditional branch from the predecessor...
140 PredBB->getInstList().pop_back();
141
142 // Move all definitions in the successor to the predecessor...
143 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
144
145 // Make all PHI nodes that referred to BB now refer to Pred as their
146 // source...
147 BB->replaceAllUsesWith(PredBB);
148
Dan Gohman438b5832009-10-31 17:33:01 +0000149 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000150 if (!PredBB->hasName())
151 PredBB->takeName(BB);
152
Owen Andersonb31b06d2008-07-17 00:01:40 +0000153 // Finally, erase the old block and update dominator info.
154 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000155 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000156 DomTreeNode* DTN = DT->getNode(BB);
157 DomTreeNode* PredDTN = DT->getNode(PredBB);
158
159 if (DTN) {
160 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
161 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
162 DE = Children.end(); DI != DE; ++DI)
163 DT->changeImmediateDominator(*DI, PredDTN);
164
165 DT->eraseNode(BB);
166 }
167 }
168 }
169
170 BB->eraseFromParent();
171
Dan Gohman438b5832009-10-31 17:33:01 +0000172
173 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000174}
175
Chris Lattner0f67dd62005-04-21 16:04:49 +0000176/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
177/// with a value, then remove and delete the original instruction.
178///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000179void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
180 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000181 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000182 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000183 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000184
Chris Lattner86cc4232007-02-11 01:37:51 +0000185 // Make sure to propagate a name if there is one already.
186 if (I.hasName() && !V->hasName())
187 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000188
Misha Brukman5560c9d2003-08-18 14:43:39 +0000189 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000190 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000191}
192
193
Chris Lattner0f67dd62005-04-21 16:04:49 +0000194/// ReplaceInstWithInst - Replace the instruction specified by BI with the
195/// instruction specified by I. The original instruction is deleted and BI is
196/// updated to point to the new instruction.
197///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000198void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
199 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000200 assert(I->getParent() == 0 &&
201 "ReplaceInstWithInst: Instruction already inserted into basic block!");
202
203 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000204 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000205
206 // Replace all uses of the old instruction, and delete it.
207 ReplaceInstWithValue(BIL, BI, I);
208
209 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000210 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000211}
212
Chris Lattner0f67dd62005-04-21 16:04:49 +0000213/// ReplaceInstWithInst - Replace the instruction specified by From with the
214/// instruction specified by To.
215///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000216void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000217 BasicBlock::iterator BI(From);
218 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000219}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000220
Chris Lattner0f67dd62005-04-21 16:04:49 +0000221/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000222/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000223/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000224/// may have to be changed. In the case where the last successor of the block
225/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000226/// surprising change in program behavior if it is not expected.
227///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000228void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000229 assert(SuccNum < TI->getNumSuccessors() &&
230 "Trying to remove a nonexistant successor!");
231
232 // If our old successor block contains any PHI nodes, remove the entry in the
233 // PHI nodes that comes from this branch...
234 //
235 BasicBlock *BB = TI->getParent();
236 TI->getSuccessor(SuccNum)->removePredecessor(BB);
237
238 TerminatorInst *NewTI = 0;
239 switch (TI->getOpcode()) {
240 case Instruction::Br:
241 // If this is a conditional branch... convert to unconditional branch.
242 if (TI->getNumSuccessors() == 2) {
243 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
244 } else { // Otherwise convert to a return instruction...
245 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000246
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000247 // Create a value to return... if the function doesn't return null...
Benjamin Kramerf0127052010-01-05 13:12:22 +0000248 if (!BB->getParent()->getReturnType()->isVoidTy())
Owen Andersona7235ea2009-07-31 20:28:14 +0000249 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000250
251 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000252 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000253 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000254 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000255
256 case Instruction::Invoke: // Should convert to call
257 case Instruction::Switch: // Should remove entry
258 default:
259 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000260 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000261 }
262
263 if (NewTI) // If it's a different instruction, replace.
264 ReplaceInstWithInst(TI, NewTI);
265}
Brian Gaeked0fde302003-11-11 22:41:34 +0000266
Bob Wilsonae23daf2010-02-16 21:06:42 +0000267/// GetSuccessorNumber - Search for the specified successor of basic block BB
268/// and return its position in the terminator instruction's list of
269/// successors. It is an error to call this with a block that is not a
270/// successor.
271unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
Bob Wilsonadb6f222010-02-16 19:49:17 +0000272 TerminatorInst *Term = BB->getTerminator();
Devang Patel8a88a142008-11-03 23:14:09 +0000273#ifndef NDEBUG
Bob Wilsonadb6f222010-02-16 19:49:17 +0000274 unsigned e = Term->getNumSuccessors();
Devang Patel8a88a142008-11-03 23:14:09 +0000275#endif
276 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000277 assert(i != e && "Didn't find edge?");
Bob Wilsonadb6f222010-02-16 19:49:17 +0000278 if (Term->getSuccessor(i) == Succ)
279 return i;
Devang Patel80198932007-07-06 21:39:20 +0000280 }
Bob Wilsonadb6f222010-02-16 19:49:17 +0000281 return 0;
282}
283
284/// SplitEdge - Split the edge connecting specified block. Pass P must
285/// not be NULL.
286BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Bob Wilsonae23daf2010-02-16 21:06:42 +0000287 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Devang Patel80198932007-07-06 21:39:20 +0000288
289 // If this is a critical edge, let SplitCriticalEdge do it.
Bob Wilsonadb6f222010-02-16 19:49:17 +0000290 TerminatorInst *LatchTerm = BB->getTerminator();
291 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
Devang Patel80198932007-07-06 21:39:20 +0000292 return LatchTerm->getSuccessor(SuccNum);
293
294 // If the edge isn't critical, then BB has a single successor or Succ has a
295 // single pred. Split the block.
296 BasicBlock::iterator SplitPoint;
297 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
298 // If the successor only has a single pred, split the top of the successor
299 // block.
300 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000301 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000302 return SplitBlock(Succ, Succ->begin(), P);
303 } else {
304 // Otherwise, if BB has a single successor, split it at the bottom of the
305 // block.
306 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
307 "Should have a single succ!");
308 return SplitBlock(BB, BB->getTerminator(), P);
309 }
310}
311
312/// SplitBlock - Split the specified block at the specified instruction - every
313/// thing before SplitPt stays in Old and everything starting with SplitPt moves
314/// to a new block. The two blocks are joined by an unconditional branch and
315/// the loop info is updated.
316///
317BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000318 BasicBlock::iterator SplitIt = SplitPt;
319 while (isa<PHINode>(SplitIt))
320 ++SplitIt;
321 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
322
Dan Gohman5c89b522009-09-08 15:45:00 +0000323 // The new block lives in whichever loop the old one did. This preserves
324 // LCSSA as well, because we force the split point to be after any PHI nodes.
Duncan Sands1465d612009-01-28 13:14:17 +0000325 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000326 if (Loop *L = LI->getLoopFor(Old))
327 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000328
Evan Cheng0f1666b2010-04-05 21:16:25 +0000329 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
330 // Old dominates New. New node domiantes all other nodes dominated by Old.
331 DomTreeNode *OldNode = DT->getNode(Old);
332 std::vector<DomTreeNode *> Children;
333 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
334 I != E; ++I)
335 Children.push_back(*I);
Devang Patela8a8a362007-07-19 02:29:24 +0000336
Evan Cheng0f1666b2010-04-05 21:16:25 +0000337 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
Devang Patela8a8a362007-07-19 02:29:24 +0000338 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
339 E = Children.end(); I != E; ++I)
340 DT->changeImmediateDominator(*I, NewNode);
Evan Cheng0f1666b2010-04-05 21:16:25 +0000341 }
Devang Patel80198932007-07-06 21:39:20 +0000342
Duncan Sands1465d612009-01-28 13:14:17 +0000343 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000344 DF->splitBlock(Old);
345
346 return New;
347}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000348
349
350/// SplitBlockPredecessors - This method transforms BB by introducing a new
351/// basic block into the function, and moving some of the predecessors of BB to
352/// be predecessors of the new block. The new predecessors are indicated by the
353/// Preds array, which has NumPreds elements in it. The new block is given a
354/// suffix of 'Suffix'.
355///
Dan Gohman5c89b522009-09-08 15:45:00 +0000356/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
357/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
358/// In particular, it does not preserve LoopSimplify (because it's
359/// complicated to handle the case where one of the edges being split
360/// is an exit of a loop with other exits).
361///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000362BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
363 BasicBlock *const *Preds,
364 unsigned NumPreds, const char *Suffix,
365 Pass *P) {
366 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000367 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
368 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000369
370 // The new block unconditionally branches to the old block.
371 BranchInst *BI = BranchInst::Create(BB, NewBB);
372
Dan Gohman5c89b522009-09-08 15:45:00 +0000373 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
374 Loop *L = LI ? LI->getLoopFor(BB) : 0;
375 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
376
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000377 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000378 // While here, if we need to preserve loop analyses, collect
379 // some information about how this split will affect loops.
380 bool HasLoopExit = false;
381 bool IsLoopEntry = !!L;
382 bool SplitMakesNewLoopHeader = false;
383 for (unsigned i = 0; i != NumPreds; ++i) {
Dan Gohmanb8eb17c2009-11-05 18:25:44 +0000384 // This is slightly more strict than necessary; the minimum requirement
385 // is that there be no more than one indirectbr branching to BB. And
386 // all BlockAddress uses would need to be updated.
387 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
388 "Cannot split an edge from an IndirectBrInst");
389
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000390 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000391
392 if (LI) {
393 // If we need to preserve LCSSA, determine if any of
394 // the preds is a loop exit.
395 if (PreserveLCSSA)
396 if (Loop *PL = LI->getLoopFor(Preds[i]))
397 if (!PL->contains(BB))
398 HasLoopExit = true;
399 // If we need to preserve LoopInfo, note whether any of the
400 // preds crosses an interesting loop boundary.
401 if (L) {
402 if (L->contains(Preds[i]))
403 IsLoopEntry = false;
404 else
405 SplitMakesNewLoopHeader = true;
406 }
407 }
408 }
409
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000410 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000411 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000412 if (DT)
413 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000414 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000415 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000416
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000417 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
418 // node becomes an incoming value for BB's phi node. However, if the Preds
419 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
420 // account for the newly created predecessor.
421 if (NumPreds == 0) {
422 // Insert dummy values as the incoming value.
423 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000424 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000425 return NewBB;
426 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000427
428 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
429
430 if (L) {
431 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000432 // Add the new block to the nearest enclosing loop (and not an
433 // adjacent loop). To find this, examine each of the predecessors and
434 // determine which loops enclose them, and select the most-nested loop
435 // which contains the loop containing the block being split.
436 Loop *InnermostPredLoop = 0;
437 for (unsigned i = 0; i != NumPreds; ++i)
438 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
439 // Seek a loop which actually contains the block being split (to
440 // avoid adjacent loops).
441 while (PredLoop && !PredLoop->contains(BB))
442 PredLoop = PredLoop->getParentLoop();
443 // Select the most-nested of these loops which contains the block.
444 if (PredLoop &&
445 PredLoop->contains(BB) &&
446 (!InnermostPredLoop ||
447 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
448 InnermostPredLoop = PredLoop;
449 }
450 if (InnermostPredLoop)
451 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000452 } else {
453 L->addBasicBlockToLoop(NewBB, LI->getBase());
454 if (SplitMakesNewLoopHeader)
455 L->moveToHeader(NewBB);
456 }
457 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000458
459 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
460 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
461 PHINode *PN = cast<PHINode>(I++);
462
463 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000464 // don't need to create a new PHI node, unless it's needed for LCSSA.
465 Value *InVal = 0;
466 if (!HasLoopExit) {
467 InVal = PN->getIncomingValueForBlock(Preds[0]);
468 for (unsigned i = 1; i != NumPreds; ++i)
469 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
470 InVal = 0;
471 break;
472 }
473 }
474
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000475 if (InVal) {
476 // If all incoming values for the new PHI would be the same, just don't
477 // make a new PHI. Instead, just remove the incoming values from the old
478 // PHI.
479 for (unsigned i = 0; i != NumPreds; ++i)
480 PN->removeIncomingValue(Preds[i], false);
481 } else {
482 // If the values coming into the block are not the same, we need a PHI.
483 // Create the new PHI node, insert it into NewBB at the end of the block
484 PHINode *NewPHI =
485 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
486 if (AA) AA->copyValue(PN, NewPHI);
487
488 // Move all of the PHI values for 'Preds' to the new PHI.
489 for (unsigned i = 0; i != NumPreds; ++i) {
490 Value *V = PN->removeIncomingValue(Preds[i], false);
491 NewPHI->addIncoming(V, Preds[i]);
492 }
493 InVal = NewPHI;
494 }
495
496 // Add an incoming value to the PHI node in the loop for the preheader
497 // edge.
498 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000499 }
500
501 return NewBB;
502}
Chris Lattner52c95852008-11-27 08:10:05 +0000503
Mike Stumpfe095f32009-05-04 18:40:41 +0000504/// FindFunctionBackedges - Analyze the specified function to find all of the
505/// loop backedges in the function and return them. This is a relatively cheap
506/// (compared to computing dominators and loop info) analysis.
507///
508/// The output is added to Result, as pairs of <from,to> edge info.
509void llvm::FindFunctionBackedges(const Function &F,
510 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
511 const BasicBlock *BB = &F.getEntryBlock();
512 if (succ_begin(BB) == succ_end(BB))
513 return;
514
515 SmallPtrSet<const BasicBlock*, 8> Visited;
516 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
517 SmallPtrSet<const BasicBlock*, 8> InStack;
518
519 Visited.insert(BB);
520 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
521 InStack.insert(BB);
522 do {
523 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
524 const BasicBlock *ParentBB = Top.first;
525 succ_const_iterator &I = Top.second;
526
527 bool FoundNew = false;
528 while (I != succ_end(ParentBB)) {
529 BB = *I++;
530 if (Visited.insert(BB)) {
531 FoundNew = true;
532 break;
533 }
534 // Successor is in VisitStack, it's a back edge.
535 if (InStack.count(BB))
536 Result.push_back(std::make_pair(ParentBB, BB));
537 }
538
539 if (FoundNew) {
540 // Go down one level if there is a unvisited successor.
541 InStack.insert(BB);
542 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
543 } else {
544 // Go up one level.
545 InStack.erase(VisitStack.pop_back_val().first);
546 }
547 } while (!VisitStack.empty());
548
549
550}