blob: 964fcc083d245501cf80ce3f486835fd07b1dabc [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"
Devang Patelbd75b832009-02-11 01:29:06 +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"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000025#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner71af9b02008-12-03 06:40:52 +000028/// DeleteDeadBlock - Delete the specified block, which must have no
29/// predecessors.
30void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000031 assert((pred_begin(BB) == pred_end(BB) ||
32 // Can delete self loop.
33 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000034 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patelbd75b832009-02-11 01:29:06 +000035 Value *DbgRegionEndContext = NULL;
Chris Lattner2b1ba242008-12-03 06:37:44 +000036 // Loop through all of our successors and make sure they know that one
37 // of their predecessors is going away.
38 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
39 BBTerm->getSuccessor(i)->removePredecessor(BB);
40
41 // Zap all the instructions in the block.
42 while (!BB->empty()) {
43 Instruction &I = BB->back();
Devang Patelbd75b832009-02-11 01:29:06 +000044 // It is possible to have multiple llvm.dbg.region.end in a block.
45 if (DbgRegionEndInst *DREI = dyn_cast<DbgRegionEndInst>(&I))
46 DbgRegionEndContext = DREI->getContext();
47
Chris Lattner2b1ba242008-12-03 06:37:44 +000048 // 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())
54 I.replaceAllUsesWith(UndefValue::get(I.getType()));
55 BB->getInstList().pop_back();
56 }
Devang Patelbd75b832009-02-11 01:29:06 +000057
58 if (DbgRegionEndContext) {
59 // Delete corresponding llvm.dbg.func.start from entry block.
60 BasicBlock &Entry = BB->getParent()->getEntryBlock();
61 DbgFuncStartInst *DbgFuncStart = NULL;
62 for (BasicBlock::iterator BI = Entry.begin(), BE = Entry.end();
63 BI != BE; ++BI) {
64 if (DbgFuncStartInst *DFSI = dyn_cast<DbgFuncStartInst>(BI)) {
65 DbgFuncStart = DFSI;
66 break;
67 }
68 }
69 if (DbgFuncStart && DbgFuncStart->getSubprogram() == DbgRegionEndContext)
70 DbgFuncStart->eraseFromParent();
71 }
72
Chris Lattner2b1ba242008-12-03 06:37:44 +000073 // Zap the block!
74 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000075}
76
Chris Lattner29874e02008-12-03 19:44:02 +000077/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
78/// any single-entry PHI nodes in it, fold them away. This handles the case
79/// when all entries to the PHI nodes in a block are guaranteed equal, such as
80/// when the block has exactly one predecessor.
81void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
82 if (!isa<PHINode>(BB->begin()))
83 return;
84
85 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
86 if (PN->getIncomingValue(0) != PN)
87 PN->replaceAllUsesWith(PN->getIncomingValue(0));
88 else
89 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
90 PN->eraseFromParent();
91 }
92}
93
94
Owen Andersonb31b06d2008-07-17 00:01:40 +000095/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
96/// if possible. The return value indicates success or failure.
97bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000098 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +000099 // Can't merge the entry block.
100 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000101
Owen Anderson11f2ec82008-07-17 19:42:29 +0000102 BasicBlock *PredBB = *PI++;
103 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
104 if (*PI != PredBB) {
105 PredBB = 0; // There are multiple different predecessors...
106 break;
107 }
Owen Andersonb31b06d2008-07-17 00:01:40 +0000108
Owen Anderson11f2ec82008-07-17 19:42:29 +0000109 // Can't merge if there are multiple predecessors.
110 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000111 // Don't break self-loops.
112 if (PredBB == BB) return false;
113 // Don't break invokes.
114 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000115
116 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
117 BasicBlock* OnlySucc = BB;
118 for (; SI != SE; ++SI)
119 if (*SI != OnlySucc) {
120 OnlySucc = 0; // There are multiple distinct successors!
121 break;
122 }
123
124 // Can't merge if there are multiple successors.
125 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000126
127 // Can't merge if there is PHI loop.
128 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
129 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
130 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
131 if (PN->getIncomingValue(i) == PN)
132 return false;
133 } else
134 break;
135 }
136
Owen Andersonb31b06d2008-07-17 00:01:40 +0000137 // Begin by getting rid of unneeded PHIs.
138 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
139 PN->replaceAllUsesWith(PN->getIncomingValue(0));
140 BB->getInstList().pop_front(); // Delete the phi node...
141 }
142
143 // Delete the unconditional branch from the predecessor...
144 PredBB->getInstList().pop_back();
145
146 // Move all definitions in the successor to the predecessor...
147 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
148
149 // Make all PHI nodes that referred to BB now refer to Pred as their
150 // source...
151 BB->replaceAllUsesWith(PredBB);
152
Owen Anderson11f2ec82008-07-17 19:42:29 +0000153 // Inherit predecessors name if it exists.
154 if (!PredBB->hasName())
155 PredBB->takeName(BB);
156
Owen Andersonb31b06d2008-07-17 00:01:40 +0000157 // Finally, erase the old block and update dominator info.
158 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000159 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000160 DomTreeNode* DTN = DT->getNode(BB);
161 DomTreeNode* PredDTN = DT->getNode(PredBB);
162
163 if (DTN) {
164 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
165 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
166 DE = Children.end(); DI != DE; ++DI)
167 DT->changeImmediateDominator(*DI, PredDTN);
168
169 DT->eraseNode(BB);
170 }
171 }
172 }
173
174 BB->eraseFromParent();
175
176
177 return true;
178}
179
Chris Lattner0f67dd62005-04-21 16:04:49 +0000180/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
181/// with a value, then remove and delete the original instruction.
182///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000183void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
184 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000185 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000186 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000187 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000188
Chris Lattner86cc4232007-02-11 01:37:51 +0000189 // Make sure to propagate a name if there is one already.
190 if (I.hasName() && !V->hasName())
191 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000192
Misha Brukman5560c9d2003-08-18 14:43:39 +0000193 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000194 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000195}
196
197
Chris Lattner0f67dd62005-04-21 16:04:49 +0000198/// ReplaceInstWithInst - Replace the instruction specified by BI with the
199/// instruction specified by I. The original instruction is deleted and BI is
200/// updated to point to the new instruction.
201///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000202void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
203 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000204 assert(I->getParent() == 0 &&
205 "ReplaceInstWithInst: Instruction already inserted into basic block!");
206
207 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000208 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000209
210 // Replace all uses of the old instruction, and delete it.
211 ReplaceInstWithValue(BIL, BI, I);
212
213 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000214 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000215}
216
Chris Lattner0f67dd62005-04-21 16:04:49 +0000217/// ReplaceInstWithInst - Replace the instruction specified by From with the
218/// instruction specified by To.
219///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000220void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000221 BasicBlock::iterator BI(From);
222 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000223}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000224
Chris Lattner0f67dd62005-04-21 16:04:49 +0000225/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000226/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000227/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000228/// may have to be changed. In the case where the last successor of the block
229/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000230/// surprising change in program behavior if it is not expected.
231///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000232void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000233 assert(SuccNum < TI->getNumSuccessors() &&
234 "Trying to remove a nonexistant successor!");
235
236 // If our old successor block contains any PHI nodes, remove the entry in the
237 // PHI nodes that comes from this branch...
238 //
239 BasicBlock *BB = TI->getParent();
240 TI->getSuccessor(SuccNum)->removePredecessor(BB);
241
242 TerminatorInst *NewTI = 0;
243 switch (TI->getOpcode()) {
244 case Instruction::Br:
245 // If this is a conditional branch... convert to unconditional branch.
246 if (TI->getNumSuccessors() == 2) {
247 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
248 } else { // Otherwise convert to a return instruction...
249 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000250
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000251 // Create a value to return... if the function doesn't return null...
252 if (BB->getParent()->getReturnType() != Type::VoidTy)
253 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
254
255 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000256 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000257 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000258 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000259
260 case Instruction::Invoke: // Should convert to call
261 case Instruction::Switch: // Should remove entry
262 default:
263 case Instruction::Ret: // Cannot happen, has no successors!
264 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
265 abort();
266 }
267
268 if (NewTI) // If it's a different instruction, replace.
269 ReplaceInstWithInst(TI, NewTI);
270}
Brian Gaeked0fde302003-11-11 22:41:34 +0000271
Devang Patel80198932007-07-06 21:39:20 +0000272/// SplitEdge - Split the edge connecting specified block. Pass P must
273/// not be NULL.
274BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
275 TerminatorInst *LatchTerm = BB->getTerminator();
276 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000277#ifndef NDEBUG
278 unsigned e = LatchTerm->getNumSuccessors();
279#endif
280 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000281 assert(i != e && "Didn't find edge?");
282 if (LatchTerm->getSuccessor(i) == Succ) {
283 SuccNum = i;
284 break;
285 }
286 }
287
288 // If this is a critical edge, let SplitCriticalEdge do it.
289 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
290 return LatchTerm->getSuccessor(SuccNum);
291
292 // If the edge isn't critical, then BB has a single successor or Succ has a
293 // single pred. Split the block.
294 BasicBlock::iterator SplitPoint;
295 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
296 // If the successor only has a single pred, split the top of the successor
297 // block.
298 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000299 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000300 return SplitBlock(Succ, Succ->begin(), P);
301 } else {
302 // Otherwise, if BB has a single successor, split it at the bottom of the
303 // block.
304 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
305 "Should have a single succ!");
306 return SplitBlock(BB, BB->getTerminator(), P);
307 }
308}
309
310/// SplitBlock - Split the specified block at the specified instruction - every
311/// thing before SplitPt stays in Old and everything starting with SplitPt moves
312/// to a new block. The two blocks are joined by an unconditional branch and
313/// the loop info is updated.
314///
315BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000316 BasicBlock::iterator SplitIt = SplitPt;
317 while (isa<PHINode>(SplitIt))
318 ++SplitIt;
319 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
320
321 // The new block lives in whichever loop the old one did.
Duncan Sands1465d612009-01-28 13:14:17 +0000322 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000323 if (Loop *L = LI->getLoopFor(Old))
324 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000325
Duncan Sands1465d612009-01-28 13:14:17 +0000326 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000327 {
328 // Old dominates New. New node domiantes all other nodes dominated by Old.
329 DomTreeNode *OldNode = DT->getNode(Old);
330 std::vector<DomTreeNode *> Children;
331 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
332 I != E; ++I)
333 Children.push_back(*I);
334
335 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
336
337 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
338 E = Children.end(); I != E; ++I)
339 DT->changeImmediateDominator(*I, NewNode);
340 }
Devang Patel80198932007-07-06 21:39:20 +0000341
Duncan Sands1465d612009-01-28 13:14:17 +0000342 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000343 DF->splitBlock(Old);
344
345 return New;
346}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000347
348
349/// SplitBlockPredecessors - This method transforms BB by introducing a new
350/// basic block into the function, and moving some of the predecessors of BB to
351/// be predecessors of the new block. The new predecessors are indicated by the
352/// Preds array, which has NumPreds elements in it. The new block is given a
353/// suffix of 'Suffix'.
354///
355/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
356/// DominanceFrontier, but no other analyses.
357BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
358 BasicBlock *const *Preds,
359 unsigned NumPreds, const char *Suffix,
360 Pass *P) {
361 // Create new basic block, insert right before the original block.
362 BasicBlock *NewBB =
363 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
364
365 // The new block unconditionally branches to the old block.
366 BranchInst *BI = BranchInst::Create(BB, NewBB);
367
368 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000369 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000370 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000371
372 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000373 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000374 if (DT)
375 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000376 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000377 DF->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000378 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000379
380
381 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
382 // node becomes an incoming value for BB's phi node. However, if the Preds
383 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
384 // account for the newly created predecessor.
385 if (NumPreds == 0) {
386 // Insert dummy values as the incoming value.
387 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
388 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
389 return NewBB;
390 }
391
392 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
393 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
394 PHINode *PN = cast<PHINode>(I++);
395
396 // Check to see if all of the values coming in are the same. If so, we
397 // don't need to create a new PHI node.
398 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
399 for (unsigned i = 1; i != NumPreds; ++i)
400 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
401 InVal = 0;
402 break;
403 }
404
405 if (InVal) {
406 // If all incoming values for the new PHI would be the same, just don't
407 // make a new PHI. Instead, just remove the incoming values from the old
408 // PHI.
409 for (unsigned i = 0; i != NumPreds; ++i)
410 PN->removeIncomingValue(Preds[i], false);
411 } else {
412 // If the values coming into the block are not the same, we need a PHI.
413 // Create the new PHI node, insert it into NewBB at the end of the block
414 PHINode *NewPHI =
415 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
416 if (AA) AA->copyValue(PN, NewPHI);
417
418 // Move all of the PHI values for 'Preds' to the new PHI.
419 for (unsigned i = 0; i != NumPreds; ++i) {
420 Value *V = PN->removeIncomingValue(Preds[i], false);
421 NewPHI->addIncoming(V, Preds[i]);
422 }
423 InVal = NewPHI;
424 }
425
426 // Add an incoming value to the PHI node in the loop for the preheader
427 // edge.
428 PN->addIncoming(InVal, NewBB);
429
430 // Check to see if we can eliminate this phi node.
431 if (Value *V = PN->hasConstantValue(DT != 0)) {
432 Instruction *I = dyn_cast<Instruction>(V);
433 if (!I || DT == 0 || DT->dominates(I, PN)) {
434 PN->replaceAllUsesWith(V);
435 if (AA) AA->deleteValue(PN);
436 PN->eraseFromParent();
437 }
438 }
439 }
440
441 return NewBB;
442}
Chris Lattner52c95852008-11-27 08:10:05 +0000443
Chris Lattner4aebaee2008-11-27 08:56:30 +0000444/// AreEquivalentAddressValues - Test if A and B will obviously have the same
445/// value. This includes recognizing that %t0 and %t1 will have the same
446/// value in code like this:
447/// %t0 = getelementptr @a, 0, 3
448/// store i32 0, i32* %t0
449/// %t1 = getelementptr @a, 0, 3
450/// %t2 = load i32* %t1
451///
452static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
453 // Test if the values are trivially equivalent.
454 if (A == B) return true;
455
456 // Test if the values come form identical arithmetic instructions.
457 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
458 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
459 if (const Instruction *BI = dyn_cast<Instruction>(B))
460 if (cast<Instruction>(A)->isIdenticalTo(BI))
461 return true;
462
463 // Otherwise they may not be equivalent.
464 return false;
465}
466
Chris Lattner52c95852008-11-27 08:10:05 +0000467/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
468/// instruction before ScanFrom) checking to see if we have the value at the
469/// memory address *Ptr locally available within a small number of instructions.
470/// If the value is available, return it.
471///
472/// If not, return the iterator for the last validated instruction that the
473/// value would be live through. If we scanned the entire block and didn't find
474/// something that invalidates *Ptr or provides it, ScanFrom would be left at
475/// begin() and this returns null. ScanFrom could also be left
476///
477/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
478/// it is set to 0, it will scan the whole block. You can also optionally
479/// specify an alias analysis implementation, which makes this more precise.
480Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
481 BasicBlock::iterator &ScanFrom,
482 unsigned MaxInstsToScan,
483 AliasAnalysis *AA) {
484 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000485
486 // If we're using alias analysis to disambiguate get the size of *Ptr.
487 unsigned AccessSize = 0;
488 if (AA) {
489 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
490 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
491 }
Chris Lattner52c95852008-11-27 08:10:05 +0000492
493 while (ScanFrom != ScanBB->begin()) {
494 // Don't scan huge blocks.
495 if (MaxInstsToScan-- == 0) return 0;
496
497 Instruction *Inst = --ScanFrom;
498
499 // If this is a load of Ptr, the loaded value is available.
500 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000501 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000502 return LI;
503
504 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
505 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000506 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000507 return SI->getOperand(0);
508
509 // If Ptr is an alloca and this is a store to a different alloca, ignore
510 // the store. This is a trivial form of alias analysis that is important
511 // for reg2mem'd code.
512 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
513 (isa<AllocaInst>(SI->getOperand(1)) ||
514 isa<GlobalVariable>(SI->getOperand(1))))
515 continue;
516
Chris Lattneree6e10b2008-11-27 08:18:12 +0000517 // If we have alias analysis and it says the store won't modify the loaded
518 // value, ignore the store.
519 if (AA &&
520 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
521 continue;
522
Chris Lattner52c95852008-11-27 08:10:05 +0000523 // Otherwise the store that may or may not alias the pointer, bail out.
524 ++ScanFrom;
525 return 0;
526 }
527
Chris Lattner52c95852008-11-27 08:10:05 +0000528 // If this is some other instruction that may clobber Ptr, bail out.
529 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000530 // If alias analysis claims that it really won't modify the load,
531 // ignore it.
532 if (AA &&
533 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
534 continue;
535
Chris Lattner52c95852008-11-27 08:10:05 +0000536 // May modify the pointer, bail out.
537 ++ScanFrom;
538 return 0;
539 }
540 }
541
542 // Got to the start of the block, we didn't find it, but are done for this
543 // block.
544 return 0;
545}