blob: ac29de6f2886fd7da2fc257ed78ed6c36fecb007 [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.
81void 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
89 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
90 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman35738ac2009-05-04 22:30:44 +000091 RecursivelyDeleteDeadPHINode(PN);
Dan Gohmanafc36a92009-05-02 18:29:22 +000092}
93
Dan Gohman438b5832009-10-31 17:33:01 +000094/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
95/// if possible. The return value indicates success or failure.
Chris Lattner88202922009-11-01 04:57:33 +000096bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
Dan Gohman438b5832009-10-31 17:33:01 +000097 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Chris Lattner88202922009-11-01 04:57:33 +000098 // Can't merge the entry block. Don't merge away blocks who have their
99 // address taken: this is a bug if the predecessor block is the entry node
100 // (because we'd end up taking the address of the entry) and undesirable in
101 // any case.
102 if (pred_begin(BB) == pred_end(BB) ||
103 BB->hasAddressTaken()) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000104
Dan Gohman438b5832009-10-31 17:33:01 +0000105 BasicBlock *PredBB = *PI++;
106 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
107 if (*PI != PredBB) {
108 PredBB = 0; // There are multiple different predecessors...
109 break;
110 }
111
112 // Can't merge if there are multiple predecessors.
113 if (!PredBB) return false;
114 // Don't break self-loops.
115 if (PredBB == BB) return false;
116 // Don't break invokes.
117 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
118
119 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
120 BasicBlock* OnlySucc = BB;
121 for (; SI != SE; ++SI)
122 if (*SI != OnlySucc) {
123 OnlySucc = 0; // There are multiple distinct successors!
124 break;
125 }
126
127 // Can't merge if there are multiple successors.
128 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000129
Dan Gohman438b5832009-10-31 17:33:01 +0000130 // Can't merge if there is PHI loop.
131 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
132 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
133 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
134 if (PN->getIncomingValue(i) == PN)
135 return false;
136 } else
137 break;
138 }
139
140 // Begin by getting rid of unneeded PHIs.
141 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
142 PN->replaceAllUsesWith(PN->getIncomingValue(0));
143 BB->getInstList().pop_front(); // Delete the phi node...
144 }
145
Owen Andersonb31b06d2008-07-17 00:01:40 +0000146 // Delete the unconditional branch from the predecessor...
147 PredBB->getInstList().pop_back();
148
149 // Move all definitions in the successor to the predecessor...
150 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
151
152 // Make all PHI nodes that referred to BB now refer to Pred as their
153 // source...
154 BB->replaceAllUsesWith(PredBB);
155
Dan Gohman438b5832009-10-31 17:33:01 +0000156 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000157 if (!PredBB->hasName())
158 PredBB->takeName(BB);
159
Owen Andersonb31b06d2008-07-17 00:01:40 +0000160 // Finally, erase the old block and update dominator info.
161 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000162 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000163 DomTreeNode* DTN = DT->getNode(BB);
164 DomTreeNode* PredDTN = DT->getNode(PredBB);
165
166 if (DTN) {
167 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
168 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
169 DE = Children.end(); DI != DE; ++DI)
170 DT->changeImmediateDominator(*DI, PredDTN);
171
172 DT->eraseNode(BB);
173 }
174 }
175 }
176
177 BB->eraseFromParent();
178
Dan Gohman438b5832009-10-31 17:33:01 +0000179
180 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000181}
182
Chris Lattner0f67dd62005-04-21 16:04:49 +0000183/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
184/// with a value, then remove and delete the original instruction.
185///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000186void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
187 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000188 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000189 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000190 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000191
Chris Lattner86cc4232007-02-11 01:37:51 +0000192 // Make sure to propagate a name if there is one already.
193 if (I.hasName() && !V->hasName())
194 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000195
Misha Brukman5560c9d2003-08-18 14:43:39 +0000196 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000197 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000198}
199
200
Chris Lattner0f67dd62005-04-21 16:04:49 +0000201/// ReplaceInstWithInst - Replace the instruction specified by BI with the
202/// instruction specified by I. The original instruction is deleted and BI is
203/// updated to point to the new instruction.
204///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000205void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
206 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000207 assert(I->getParent() == 0 &&
208 "ReplaceInstWithInst: Instruction already inserted into basic block!");
209
210 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000211 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000212
213 // Replace all uses of the old instruction, and delete it.
214 ReplaceInstWithValue(BIL, BI, I);
215
216 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000217 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000218}
219
Chris Lattner0f67dd62005-04-21 16:04:49 +0000220/// ReplaceInstWithInst - Replace the instruction specified by From with the
221/// instruction specified by To.
222///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000223void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000224 BasicBlock::iterator BI(From);
225 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000226}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000227
Chris Lattner0f67dd62005-04-21 16:04:49 +0000228/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000229/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000230/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000231/// may have to be changed. In the case where the last successor of the block
232/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000233/// surprising change in program behavior if it is not expected.
234///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000235void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000236 assert(SuccNum < TI->getNumSuccessors() &&
237 "Trying to remove a nonexistant successor!");
238
239 // If our old successor block contains any PHI nodes, remove the entry in the
240 // PHI nodes that comes from this branch...
241 //
242 BasicBlock *BB = TI->getParent();
243 TI->getSuccessor(SuccNum)->removePredecessor(BB);
244
245 TerminatorInst *NewTI = 0;
246 switch (TI->getOpcode()) {
247 case Instruction::Br:
248 // If this is a conditional branch... convert to unconditional branch.
249 if (TI->getNumSuccessors() == 2) {
250 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
251 } else { // Otherwise convert to a return instruction...
252 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000253
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000254 // Create a value to return... if the function doesn't return null...
Benjamin Kramerf0127052010-01-05 13:12:22 +0000255 if (!BB->getParent()->getReturnType()->isVoidTy())
Owen Andersona7235ea2009-07-31 20:28:14 +0000256 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000257
258 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000259 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000260 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000261 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000262
263 case Instruction::Invoke: // Should convert to call
264 case Instruction::Switch: // Should remove entry
265 default:
266 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000267 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000268 }
269
270 if (NewTI) // If it's a different instruction, replace.
271 ReplaceInstWithInst(TI, NewTI);
272}
Brian Gaeked0fde302003-11-11 22:41:34 +0000273
Devang Patel80198932007-07-06 21:39:20 +0000274/// SplitEdge - Split the edge connecting specified block. Pass P must
275/// not be NULL.
276BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
277 TerminatorInst *LatchTerm = BB->getTerminator();
278 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000279#ifndef NDEBUG
280 unsigned e = LatchTerm->getNumSuccessors();
281#endif
282 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000283 assert(i != e && "Didn't find edge?");
284 if (LatchTerm->getSuccessor(i) == Succ) {
285 SuccNum = i;
286 break;
287 }
288 }
289
290 // If this is a critical edge, let SplitCriticalEdge do it.
291 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
292 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
Duncan Sands1465d612009-01-28 13:14:17 +0000329 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000330 {
331 // Old dominates New. New node domiantes all other nodes dominated by Old.
332 DomTreeNode *OldNode = DT->getNode(Old);
333 std::vector<DomTreeNode *> Children;
334 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
335 I != E; ++I)
336 Children.push_back(*I);
337
338 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
339
340 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
341 E = Children.end(); I != E; ++I)
342 DT->changeImmediateDominator(*I, NewNode);
343 }
Devang Patel80198932007-07-06 21:39:20 +0000344
Duncan Sands1465d612009-01-28 13:14:17 +0000345 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000346 DF->splitBlock(Old);
347
348 return New;
349}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000350
351
352/// SplitBlockPredecessors - This method transforms BB by introducing a new
353/// basic block into the function, and moving some of the predecessors of BB to
354/// be predecessors of the new block. The new predecessors are indicated by the
355/// Preds array, which has NumPreds elements in it. The new block is given a
356/// suffix of 'Suffix'.
357///
Dan Gohman5c89b522009-09-08 15:45:00 +0000358/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
359/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
360/// In particular, it does not preserve LoopSimplify (because it's
361/// complicated to handle the case where one of the edges being split
362/// is an exit of a loop with other exits).
363///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000364BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
365 BasicBlock *const *Preds,
366 unsigned NumPreds, const char *Suffix,
367 Pass *P) {
368 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000369 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
370 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000371
372 // The new block unconditionally branches to the old block.
373 BranchInst *BI = BranchInst::Create(BB, NewBB);
374
Dan Gohman5c89b522009-09-08 15:45:00 +0000375 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
376 Loop *L = LI ? LI->getLoopFor(BB) : 0;
377 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
378
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000379 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000380 // While here, if we need to preserve loop analyses, collect
381 // some information about how this split will affect loops.
382 bool HasLoopExit = false;
383 bool IsLoopEntry = !!L;
384 bool SplitMakesNewLoopHeader = false;
385 for (unsigned i = 0; i != NumPreds; ++i) {
Dan Gohmanb8eb17c2009-11-05 18:25:44 +0000386 // This is slightly more strict than necessary; the minimum requirement
387 // is that there be no more than one indirectbr branching to BB. And
388 // all BlockAddress uses would need to be updated.
389 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
390 "Cannot split an edge from an IndirectBrInst");
391
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000392 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000393
394 if (LI) {
395 // If we need to preserve LCSSA, determine if any of
396 // the preds is a loop exit.
397 if (PreserveLCSSA)
398 if (Loop *PL = LI->getLoopFor(Preds[i]))
399 if (!PL->contains(BB))
400 HasLoopExit = true;
401 // If we need to preserve LoopInfo, note whether any of the
402 // preds crosses an interesting loop boundary.
403 if (L) {
404 if (L->contains(Preds[i]))
405 IsLoopEntry = false;
406 else
407 SplitMakesNewLoopHeader = true;
408 }
409 }
410 }
411
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000412 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000413 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000414 if (DT)
415 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000416 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000417 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000418
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000419 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
420 // node becomes an incoming value for BB's phi node. However, if the Preds
421 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
422 // account for the newly created predecessor.
423 if (NumPreds == 0) {
424 // Insert dummy values as the incoming value.
425 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000426 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000427 return NewBB;
428 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000429
430 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
431
432 if (L) {
433 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000434 // Add the new block to the nearest enclosing loop (and not an
435 // adjacent loop). To find this, examine each of the predecessors and
436 // determine which loops enclose them, and select the most-nested loop
437 // which contains the loop containing the block being split.
438 Loop *InnermostPredLoop = 0;
439 for (unsigned i = 0; i != NumPreds; ++i)
440 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
441 // Seek a loop which actually contains the block being split (to
442 // avoid adjacent loops).
443 while (PredLoop && !PredLoop->contains(BB))
444 PredLoop = PredLoop->getParentLoop();
445 // Select the most-nested of these loops which contains the block.
446 if (PredLoop &&
447 PredLoop->contains(BB) &&
448 (!InnermostPredLoop ||
449 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
450 InnermostPredLoop = PredLoop;
451 }
452 if (InnermostPredLoop)
453 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000454 } else {
455 L->addBasicBlockToLoop(NewBB, LI->getBase());
456 if (SplitMakesNewLoopHeader)
457 L->moveToHeader(NewBB);
458 }
459 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000460
461 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
462 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
463 PHINode *PN = cast<PHINode>(I++);
464
465 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000466 // don't need to create a new PHI node, unless it's needed for LCSSA.
467 Value *InVal = 0;
468 if (!HasLoopExit) {
469 InVal = PN->getIncomingValueForBlock(Preds[0]);
470 for (unsigned i = 1; i != NumPreds; ++i)
471 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
472 InVal = 0;
473 break;
474 }
475 }
476
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000477 if (InVal) {
478 // If all incoming values for the new PHI would be the same, just don't
479 // make a new PHI. Instead, just remove the incoming values from the old
480 // PHI.
481 for (unsigned i = 0; i != NumPreds; ++i)
482 PN->removeIncomingValue(Preds[i], false);
483 } else {
484 // If the values coming into the block are not the same, we need a PHI.
485 // Create the new PHI node, insert it into NewBB at the end of the block
486 PHINode *NewPHI =
487 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
488 if (AA) AA->copyValue(PN, NewPHI);
489
490 // Move all of the PHI values for 'Preds' to the new PHI.
491 for (unsigned i = 0; i != NumPreds; ++i) {
492 Value *V = PN->removeIncomingValue(Preds[i], false);
493 NewPHI->addIncoming(V, Preds[i]);
494 }
495 InVal = NewPHI;
496 }
497
498 // Add an incoming value to the PHI node in the loop for the preheader
499 // edge.
500 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000501 }
502
503 return NewBB;
504}
Chris Lattner52c95852008-11-27 08:10:05 +0000505
Mike Stumpfe095f32009-05-04 18:40:41 +0000506/// FindFunctionBackedges - Analyze the specified function to find all of the
507/// loop backedges in the function and return them. This is a relatively cheap
508/// (compared to computing dominators and loop info) analysis.
509///
510/// The output is added to Result, as pairs of <from,to> edge info.
511void llvm::FindFunctionBackedges(const Function &F,
512 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
513 const BasicBlock *BB = &F.getEntryBlock();
514 if (succ_begin(BB) == succ_end(BB))
515 return;
516
517 SmallPtrSet<const BasicBlock*, 8> Visited;
518 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
519 SmallPtrSet<const BasicBlock*, 8> InStack;
520
521 Visited.insert(BB);
522 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
523 InStack.insert(BB);
524 do {
525 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
526 const BasicBlock *ParentBB = Top.first;
527 succ_const_iterator &I = Top.second;
528
529 bool FoundNew = false;
530 while (I != succ_end(ParentBB)) {
531 BB = *I++;
532 if (Visited.insert(BB)) {
533 FoundNew = true;
534 break;
535 }
536 // Successor is in VisitStack, it's a back edge.
537 if (InStack.count(BB))
538 Result.push_back(std::make_pair(ParentBB, BB));
539 }
540
541 if (FoundNew) {
542 // Go down one level if there is a unvisited successor.
543 InStack.insert(BB);
544 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
545 } else {
546 // Go up one level.
547 InStack.erase(VisitStack.pop_back_val().first);
548 }
549 } while (!VisitStack.empty());
550
551
552}
553
554
555
Chris Lattner4aebaee2008-11-27 08:56:30 +0000556/// AreEquivalentAddressValues - Test if A and B will obviously have the same
557/// value. This includes recognizing that %t0 and %t1 will have the same
558/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000559/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000560/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000561/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000562/// %t2 = load i32* %t1
563///
564static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
565 // Test if the values are trivially equivalent.
566 if (A == B) return true;
567
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000568 // Test if the values come from identical arithmetic instructions.
569 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
570 // this function is only used when one address use dominates the
571 // other, which means that they'll always either have the same
572 // value or one of them will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +0000573 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
574 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
575 if (const Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000576 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000577 return true;
578
579 // Otherwise they may not be equivalent.
580 return false;
581}
582
Chris Lattner52c95852008-11-27 08:10:05 +0000583/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
584/// instruction before ScanFrom) checking to see if we have the value at the
585/// memory address *Ptr locally available within a small number of instructions.
586/// If the value is available, return it.
587///
588/// If not, return the iterator for the last validated instruction that the
589/// value would be live through. If we scanned the entire block and didn't find
590/// something that invalidates *Ptr or provides it, ScanFrom would be left at
591/// begin() and this returns null. ScanFrom could also be left
592///
593/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
594/// it is set to 0, it will scan the whole block. You can also optionally
595/// specify an alias analysis implementation, which makes this more precise.
596Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
597 BasicBlock::iterator &ScanFrom,
598 unsigned MaxInstsToScan,
599 AliasAnalysis *AA) {
600 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000601
602 // If we're using alias analysis to disambiguate get the size of *Ptr.
603 unsigned AccessSize = 0;
604 if (AA) {
605 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000606 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000607 }
Chris Lattner52c95852008-11-27 08:10:05 +0000608
609 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000610 // We must ignore debug info directives when counting (otherwise they
611 // would affect codegen).
612 Instruction *Inst = --ScanFrom;
613 if (isa<DbgInfoIntrinsic>(Inst))
614 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000615 // We skip pointer-to-pointer bitcasts, which are NOPs.
616 // It is necessary for correctness to skip those that feed into a
617 // llvm.dbg.declare, as these are not present when debugging is off.
618 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000619 continue;
620
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000621 // Restore ScanFrom to expected value in case next test succeeds
622 ScanFrom++;
623
Chris Lattner52c95852008-11-27 08:10:05 +0000624 // Don't scan huge blocks.
625 if (MaxInstsToScan-- == 0) return 0;
626
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000627 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000628 // If this is a load of Ptr, the loaded value is available.
629 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000630 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000631 return LI;
632
633 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
634 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000635 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000636 return SI->getOperand(0);
637
638 // If Ptr is an alloca and this is a store to a different alloca, ignore
639 // the store. This is a trivial form of alias analysis that is important
640 // for reg2mem'd code.
641 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
642 (isa<AllocaInst>(SI->getOperand(1)) ||
643 isa<GlobalVariable>(SI->getOperand(1))))
644 continue;
645
Chris Lattneree6e10b2008-11-27 08:18:12 +0000646 // If we have alias analysis and it says the store won't modify the loaded
647 // value, ignore the store.
648 if (AA &&
649 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
650 continue;
651
Chris Lattner52c95852008-11-27 08:10:05 +0000652 // Otherwise the store that may or may not alias the pointer, bail out.
653 ++ScanFrom;
654 return 0;
655 }
656
Chris Lattner52c95852008-11-27 08:10:05 +0000657 // If this is some other instruction that may clobber Ptr, bail out.
658 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000659 // If alias analysis claims that it really won't modify the load,
660 // ignore it.
661 if (AA &&
662 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
663 continue;
664
Chris Lattner52c95852008-11-27 08:10:05 +0000665 // May modify the pointer, bail out.
666 ++ScanFrom;
667 return 0;
668 }
669 }
670
671 // Got to the start of the block, we didn't find it, but are done for this
672 // block.
673 return 0;
674}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000675