blob: 60185d2687a5b5b6530627ab2c8dce43d112720c [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 Gohman438b5832009-10-31 17:33:01 +0000100 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Chris Lattner88202922009-11-01 04:57:33 +0000101 // Can't merge the entry block. Don't merge away blocks who have their
102 // address taken: this is a bug if the predecessor block is the entry node
103 // (because we'd end up taking the address of the entry) and undesirable in
104 // any case.
105 if (pred_begin(BB) == pred_end(BB) ||
106 BB->hasAddressTaken()) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000107
Dan Gohman438b5832009-10-31 17:33:01 +0000108 BasicBlock *PredBB = *PI++;
109 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
110 if (*PI != PredBB) {
111 PredBB = 0; // There are multiple different predecessors...
112 break;
113 }
114
115 // Can't merge if there are multiple predecessors.
116 if (!PredBB) return false;
117 // Don't break self-loops.
118 if (PredBB == BB) return false;
119 // Don't break invokes.
120 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
121
122 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
123 BasicBlock* OnlySucc = BB;
124 for (; SI != SE; ++SI)
125 if (*SI != OnlySucc) {
126 OnlySucc = 0; // There are multiple distinct successors!
127 break;
128 }
129
130 // Can't merge if there are multiple successors.
131 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000132
Dan Gohman438b5832009-10-31 17:33:01 +0000133 // Can't merge if there is PHI loop.
134 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
135 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
136 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
137 if (PN->getIncomingValue(i) == PN)
138 return false;
139 } else
140 break;
141 }
142
143 // Begin by getting rid of unneeded PHIs.
144 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
145 PN->replaceAllUsesWith(PN->getIncomingValue(0));
146 BB->getInstList().pop_front(); // Delete the phi node...
147 }
148
Owen Andersonb31b06d2008-07-17 00:01:40 +0000149 // Delete the unconditional branch from the predecessor...
150 PredBB->getInstList().pop_back();
151
152 // Move all definitions in the successor to the predecessor...
153 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
154
155 // Make all PHI nodes that referred to BB now refer to Pred as their
156 // source...
157 BB->replaceAllUsesWith(PredBB);
158
Dan Gohman438b5832009-10-31 17:33:01 +0000159 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000160 if (!PredBB->hasName())
161 PredBB->takeName(BB);
162
Owen Andersonb31b06d2008-07-17 00:01:40 +0000163 // Finally, erase the old block and update dominator info.
164 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000165 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000166 DomTreeNode* DTN = DT->getNode(BB);
167 DomTreeNode* PredDTN = DT->getNode(PredBB);
168
169 if (DTN) {
170 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
171 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
172 DE = Children.end(); DI != DE; ++DI)
173 DT->changeImmediateDominator(*DI, PredDTN);
174
175 DT->eraseNode(BB);
176 }
177 }
178 }
179
180 BB->eraseFromParent();
181
Dan Gohman438b5832009-10-31 17:33:01 +0000182
183 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000184}
185
Chris Lattner0f67dd62005-04-21 16:04:49 +0000186/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
187/// with a value, then remove and delete the original instruction.
188///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000189void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
190 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000191 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000192 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000193 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000194
Chris Lattner86cc4232007-02-11 01:37:51 +0000195 // Make sure to propagate a name if there is one already.
196 if (I.hasName() && !V->hasName())
197 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000198
Misha Brukman5560c9d2003-08-18 14:43:39 +0000199 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000200 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000201}
202
203
Chris Lattner0f67dd62005-04-21 16:04:49 +0000204/// ReplaceInstWithInst - Replace the instruction specified by BI with the
205/// instruction specified by I. The original instruction is deleted and BI is
206/// updated to point to the new instruction.
207///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000208void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
209 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000210 assert(I->getParent() == 0 &&
211 "ReplaceInstWithInst: Instruction already inserted into basic block!");
212
213 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000214 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000215
216 // Replace all uses of the old instruction, and delete it.
217 ReplaceInstWithValue(BIL, BI, I);
218
219 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000220 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000221}
222
Chris Lattner0f67dd62005-04-21 16:04:49 +0000223/// ReplaceInstWithInst - Replace the instruction specified by From with the
224/// instruction specified by To.
225///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000226void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000227 BasicBlock::iterator BI(From);
228 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000229}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000230
Chris Lattner0f67dd62005-04-21 16:04:49 +0000231/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000232/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000233/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000234/// may have to be changed. In the case where the last successor of the block
235/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000236/// surprising change in program behavior if it is not expected.
237///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000238void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000239 assert(SuccNum < TI->getNumSuccessors() &&
240 "Trying to remove a nonexistant successor!");
241
242 // If our old successor block contains any PHI nodes, remove the entry in the
243 // PHI nodes that comes from this branch...
244 //
245 BasicBlock *BB = TI->getParent();
246 TI->getSuccessor(SuccNum)->removePredecessor(BB);
247
248 TerminatorInst *NewTI = 0;
249 switch (TI->getOpcode()) {
250 case Instruction::Br:
251 // If this is a conditional branch... convert to unconditional branch.
252 if (TI->getNumSuccessors() == 2) {
253 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
254 } else { // Otherwise convert to a return instruction...
255 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000256
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000257 // Create a value to return... if the function doesn't return null...
Benjamin Kramerf0127052010-01-05 13:12:22 +0000258 if (!BB->getParent()->getReturnType()->isVoidTy())
Owen Andersona7235ea2009-07-31 20:28:14 +0000259 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000260
261 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000262 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000263 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000264 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000265
266 case Instruction::Invoke: // Should convert to call
267 case Instruction::Switch: // Should remove entry
268 default:
269 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000270 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000271 }
272
273 if (NewTI) // If it's a different instruction, replace.
274 ReplaceInstWithInst(TI, NewTI);
275}
Brian Gaeked0fde302003-11-11 22:41:34 +0000276
Bob Wilsonadb6f222010-02-16 19:49:17 +0000277/// SuccessorNumber - Search for the specified successor of basic block BB and
278/// return its position in the terminator instruction's list of successors.
279/// It is an error to call this with a block that is not a successor.
280unsigned llvm::SuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
281 TerminatorInst *Term = BB->getTerminator();
Devang Patel8a88a142008-11-03 23:14:09 +0000282#ifndef NDEBUG
Bob Wilsonadb6f222010-02-16 19:49:17 +0000283 unsigned e = Term->getNumSuccessors();
Devang Patel8a88a142008-11-03 23:14:09 +0000284#endif
285 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000286 assert(i != e && "Didn't find edge?");
Bob Wilsonadb6f222010-02-16 19:49:17 +0000287 if (Term->getSuccessor(i) == Succ)
288 return i;
Devang Patel80198932007-07-06 21:39:20 +0000289 }
Bob Wilsonadb6f222010-02-16 19:49:17 +0000290 return 0;
291}
292
293/// SplitEdge - Split the edge connecting specified block. Pass P must
294/// not be NULL.
295BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
296 unsigned SuccNum = SuccessorNumber(BB, Succ);
Devang Patel80198932007-07-06 21:39:20 +0000297
298 // If this is a critical edge, let SplitCriticalEdge do it.
Bob Wilsonadb6f222010-02-16 19:49:17 +0000299 TerminatorInst *LatchTerm = BB->getTerminator();
300 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
Devang Patel80198932007-07-06 21:39:20 +0000301 return LatchTerm->getSuccessor(SuccNum);
302
303 // If the edge isn't critical, then BB has a single successor or Succ has a
304 // single pred. Split the block.
305 BasicBlock::iterator SplitPoint;
306 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
307 // If the successor only has a single pred, split the top of the successor
308 // block.
309 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000310 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000311 return SplitBlock(Succ, Succ->begin(), P);
312 } else {
313 // Otherwise, if BB has a single successor, split it at the bottom of the
314 // block.
315 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
316 "Should have a single succ!");
317 return SplitBlock(BB, BB->getTerminator(), P);
318 }
319}
320
321/// SplitBlock - Split the specified block at the specified instruction - every
322/// thing before SplitPt stays in Old and everything starting with SplitPt moves
323/// to a new block. The two blocks are joined by an unconditional branch and
324/// the loop info is updated.
325///
326BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000327 BasicBlock::iterator SplitIt = SplitPt;
328 while (isa<PHINode>(SplitIt))
329 ++SplitIt;
330 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
331
Dan Gohman5c89b522009-09-08 15:45:00 +0000332 // The new block lives in whichever loop the old one did. This preserves
333 // LCSSA as well, because we force the split point to be after any PHI nodes.
Duncan Sands1465d612009-01-28 13:14:17 +0000334 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000335 if (Loop *L = LI->getLoopFor(Old))
336 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000337
Duncan Sands1465d612009-01-28 13:14:17 +0000338 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000339 {
340 // Old dominates New. New node domiantes all other nodes dominated by Old.
341 DomTreeNode *OldNode = DT->getNode(Old);
342 std::vector<DomTreeNode *> Children;
343 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
344 I != E; ++I)
345 Children.push_back(*I);
346
347 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
348
349 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
350 E = Children.end(); I != E; ++I)
351 DT->changeImmediateDominator(*I, NewNode);
352 }
Devang Patel80198932007-07-06 21:39:20 +0000353
Duncan Sands1465d612009-01-28 13:14:17 +0000354 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000355 DF->splitBlock(Old);
356
357 return New;
358}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000359
360
361/// SplitBlockPredecessors - This method transforms BB by introducing a new
362/// basic block into the function, and moving some of the predecessors of BB to
363/// be predecessors of the new block. The new predecessors are indicated by the
364/// Preds array, which has NumPreds elements in it. The new block is given a
365/// suffix of 'Suffix'.
366///
Dan Gohman5c89b522009-09-08 15:45:00 +0000367/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
368/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
369/// In particular, it does not preserve LoopSimplify (because it's
370/// complicated to handle the case where one of the edges being split
371/// is an exit of a loop with other exits).
372///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000373BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
374 BasicBlock *const *Preds,
375 unsigned NumPreds, const char *Suffix,
376 Pass *P) {
377 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000378 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
379 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000380
381 // The new block unconditionally branches to the old block.
382 BranchInst *BI = BranchInst::Create(BB, NewBB);
383
Dan Gohman5c89b522009-09-08 15:45:00 +0000384 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
385 Loop *L = LI ? LI->getLoopFor(BB) : 0;
386 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
387
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000388 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000389 // While here, if we need to preserve loop analyses, collect
390 // some information about how this split will affect loops.
391 bool HasLoopExit = false;
392 bool IsLoopEntry = !!L;
393 bool SplitMakesNewLoopHeader = false;
394 for (unsigned i = 0; i != NumPreds; ++i) {
Dan Gohmanb8eb17c2009-11-05 18:25:44 +0000395 // This is slightly more strict than necessary; the minimum requirement
396 // is that there be no more than one indirectbr branching to BB. And
397 // all BlockAddress uses would need to be updated.
398 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
399 "Cannot split an edge from an IndirectBrInst");
400
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000401 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000402
403 if (LI) {
404 // If we need to preserve LCSSA, determine if any of
405 // the preds is a loop exit.
406 if (PreserveLCSSA)
407 if (Loop *PL = LI->getLoopFor(Preds[i]))
408 if (!PL->contains(BB))
409 HasLoopExit = true;
410 // If we need to preserve LoopInfo, note whether any of the
411 // preds crosses an interesting loop boundary.
412 if (L) {
413 if (L->contains(Preds[i]))
414 IsLoopEntry = false;
415 else
416 SplitMakesNewLoopHeader = true;
417 }
418 }
419 }
420
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000421 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000422 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000423 if (DT)
424 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000425 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000426 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000427
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000428 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
429 // node becomes an incoming value for BB's phi node. However, if the Preds
430 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
431 // account for the newly created predecessor.
432 if (NumPreds == 0) {
433 // Insert dummy values as the incoming value.
434 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000435 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000436 return NewBB;
437 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000438
439 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
440
441 if (L) {
442 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000443 // Add the new block to the nearest enclosing loop (and not an
444 // adjacent loop). To find this, examine each of the predecessors and
445 // determine which loops enclose them, and select the most-nested loop
446 // which contains the loop containing the block being split.
447 Loop *InnermostPredLoop = 0;
448 for (unsigned i = 0; i != NumPreds; ++i)
449 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
450 // Seek a loop which actually contains the block being split (to
451 // avoid adjacent loops).
452 while (PredLoop && !PredLoop->contains(BB))
453 PredLoop = PredLoop->getParentLoop();
454 // Select the most-nested of these loops which contains the block.
455 if (PredLoop &&
456 PredLoop->contains(BB) &&
457 (!InnermostPredLoop ||
458 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
459 InnermostPredLoop = PredLoop;
460 }
461 if (InnermostPredLoop)
462 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000463 } else {
464 L->addBasicBlockToLoop(NewBB, LI->getBase());
465 if (SplitMakesNewLoopHeader)
466 L->moveToHeader(NewBB);
467 }
468 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000469
470 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
471 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
472 PHINode *PN = cast<PHINode>(I++);
473
474 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000475 // don't need to create a new PHI node, unless it's needed for LCSSA.
476 Value *InVal = 0;
477 if (!HasLoopExit) {
478 InVal = PN->getIncomingValueForBlock(Preds[0]);
479 for (unsigned i = 1; i != NumPreds; ++i)
480 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
481 InVal = 0;
482 break;
483 }
484 }
485
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000486 if (InVal) {
487 // If all incoming values for the new PHI would be the same, just don't
488 // make a new PHI. Instead, just remove the incoming values from the old
489 // PHI.
490 for (unsigned i = 0; i != NumPreds; ++i)
491 PN->removeIncomingValue(Preds[i], false);
492 } else {
493 // If the values coming into the block are not the same, we need a PHI.
494 // Create the new PHI node, insert it into NewBB at the end of the block
495 PHINode *NewPHI =
496 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
497 if (AA) AA->copyValue(PN, NewPHI);
498
499 // Move all of the PHI values for 'Preds' to the new PHI.
500 for (unsigned i = 0; i != NumPreds; ++i) {
501 Value *V = PN->removeIncomingValue(Preds[i], false);
502 NewPHI->addIncoming(V, Preds[i]);
503 }
504 InVal = NewPHI;
505 }
506
507 // Add an incoming value to the PHI node in the loop for the preheader
508 // edge.
509 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000510 }
511
512 return NewBB;
513}
Chris Lattner52c95852008-11-27 08:10:05 +0000514
Mike Stumpfe095f32009-05-04 18:40:41 +0000515/// FindFunctionBackedges - Analyze the specified function to find all of the
516/// loop backedges in the function and return them. This is a relatively cheap
517/// (compared to computing dominators and loop info) analysis.
518///
519/// The output is added to Result, as pairs of <from,to> edge info.
520void llvm::FindFunctionBackedges(const Function &F,
521 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
522 const BasicBlock *BB = &F.getEntryBlock();
523 if (succ_begin(BB) == succ_end(BB))
524 return;
525
526 SmallPtrSet<const BasicBlock*, 8> Visited;
527 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
528 SmallPtrSet<const BasicBlock*, 8> InStack;
529
530 Visited.insert(BB);
531 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
532 InStack.insert(BB);
533 do {
534 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
535 const BasicBlock *ParentBB = Top.first;
536 succ_const_iterator &I = Top.second;
537
538 bool FoundNew = false;
539 while (I != succ_end(ParentBB)) {
540 BB = *I++;
541 if (Visited.insert(BB)) {
542 FoundNew = true;
543 break;
544 }
545 // Successor is in VisitStack, it's a back edge.
546 if (InStack.count(BB))
547 Result.push_back(std::make_pair(ParentBB, BB));
548 }
549
550 if (FoundNew) {
551 // Go down one level if there is a unvisited successor.
552 InStack.insert(BB);
553 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
554 } else {
555 // Go up one level.
556 InStack.erase(VisitStack.pop_back_val().first);
557 }
558 } while (!VisitStack.empty());
559
560
561}
562
563
564
Chris Lattner4aebaee2008-11-27 08:56:30 +0000565/// AreEquivalentAddressValues - Test if A and B will obviously have the same
566/// value. This includes recognizing that %t0 and %t1 will have the same
567/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000568/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000569/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000570/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000571/// %t2 = load i32* %t1
572///
573static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
574 // Test if the values are trivially equivalent.
575 if (A == B) return true;
576
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000577 // Test if the values come from identical arithmetic instructions.
578 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
579 // this function is only used when one address use dominates the
580 // other, which means that they'll always either have the same
581 // value or one of them will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +0000582 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
583 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
584 if (const Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000585 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000586 return true;
587
588 // Otherwise they may not be equivalent.
589 return false;
590}
591
Chris Lattner52c95852008-11-27 08:10:05 +0000592/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
593/// instruction before ScanFrom) checking to see if we have the value at the
594/// memory address *Ptr locally available within a small number of instructions.
595/// If the value is available, return it.
596///
597/// If not, return the iterator for the last validated instruction that the
598/// value would be live through. If we scanned the entire block and didn't find
599/// something that invalidates *Ptr or provides it, ScanFrom would be left at
600/// begin() and this returns null. ScanFrom could also be left
601///
602/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
603/// it is set to 0, it will scan the whole block. You can also optionally
604/// specify an alias analysis implementation, which makes this more precise.
605Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
606 BasicBlock::iterator &ScanFrom,
607 unsigned MaxInstsToScan,
608 AliasAnalysis *AA) {
609 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000610
611 // If we're using alias analysis to disambiguate get the size of *Ptr.
612 unsigned AccessSize = 0;
613 if (AA) {
614 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000615 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000616 }
Chris Lattner52c95852008-11-27 08:10:05 +0000617
618 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000619 // We must ignore debug info directives when counting (otherwise they
620 // would affect codegen).
621 Instruction *Inst = --ScanFrom;
622 if (isa<DbgInfoIntrinsic>(Inst))
623 continue;
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000624
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000625 // Restore ScanFrom to expected value in case next test succeeds
626 ScanFrom++;
627
Chris Lattner52c95852008-11-27 08:10:05 +0000628 // Don't scan huge blocks.
629 if (MaxInstsToScan-- == 0) return 0;
630
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000631 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000632 // If this is a load of Ptr, the loaded value is available.
633 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000634 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000635 return LI;
636
637 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
638 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000639 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000640 return SI->getOperand(0);
641
642 // If Ptr is an alloca and this is a store to a different alloca, ignore
643 // the store. This is a trivial form of alias analysis that is important
644 // for reg2mem'd code.
645 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
646 (isa<AllocaInst>(SI->getOperand(1)) ||
647 isa<GlobalVariable>(SI->getOperand(1))))
648 continue;
649
Chris Lattneree6e10b2008-11-27 08:18:12 +0000650 // If we have alias analysis and it says the store won't modify the loaded
651 // value, ignore the store.
652 if (AA &&
653 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
654 continue;
655
Chris Lattner52c95852008-11-27 08:10:05 +0000656 // Otherwise the store that may or may not alias the pointer, bail out.
657 ++ScanFrom;
658 return 0;
659 }
660
Chris Lattner52c95852008-11-27 08:10:05 +0000661 // If this is some other instruction that may clobber Ptr, bail out.
662 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000663 // If alias analysis claims that it really won't modify the load,
664 // ignore it.
665 if (AA &&
666 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
667 continue;
668
Chris Lattner52c95852008-11-27 08:10:05 +0000669 // May modify the pointer, bail out.
670 ++ScanFrom;
671 return 0;
672 }
673 }
674
675 // Got to the start of the block, we didn't find it, but are done for this
676 // block.
677 return 0;
678}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000679