blob: 2887bdc46b526874a98f52d2459fdac0ec737c5c [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"
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 Patel5622f072009-02-24 00:05:16 +000035
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();
44 // If this instruction is used, replace uses with an arbitrary value.
45 // Because control flow can't get here, we don't care what we replace the
46 // value with. Note that since this block is unreachable, and all values
47 // contained within it must dominate their uses, that all uses will
48 // eventually be removed (they are themselves dead).
49 if (!I.use_empty())
50 I.replaceAllUsesWith(UndefValue::get(I.getType()));
51 BB->getInstList().pop_back();
52 }
Devang Patel5622f072009-02-24 00:05:16 +000053
Chris Lattner2b1ba242008-12-03 06:37:44 +000054 // Zap the block!
55 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000056}
57
Chris Lattner29874e02008-12-03 19:44:02 +000058/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
59/// any single-entry PHI nodes in it, fold them away. This handles the case
60/// when all entries to the PHI nodes in a block are guaranteed equal, such as
61/// when the block has exactly one predecessor.
62void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
63 if (!isa<PHINode>(BB->begin()))
64 return;
65
66 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
67 if (PN->getIncomingValue(0) != PN)
68 PN->replaceAllUsesWith(PN->getIncomingValue(0));
69 else
70 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
71 PN->eraseFromParent();
72 }
73}
74
75
Owen Andersonb31b06d2008-07-17 00:01:40 +000076/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
77/// if possible. The return value indicates success or failure.
78bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000079 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +000080 // Can't merge the entry block.
81 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +000082
Owen Anderson11f2ec82008-07-17 19:42:29 +000083 BasicBlock *PredBB = *PI++;
84 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
85 if (*PI != PredBB) {
86 PredBB = 0; // There are multiple different predecessors...
87 break;
88 }
Owen Andersonb31b06d2008-07-17 00:01:40 +000089
Owen Anderson11f2ec82008-07-17 19:42:29 +000090 // Can't merge if there are multiple predecessors.
91 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +000092 // Don't break self-loops.
93 if (PredBB == BB) return false;
94 // Don't break invokes.
95 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +000096
97 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
98 BasicBlock* OnlySucc = BB;
99 for (; SI != SE; ++SI)
100 if (*SI != OnlySucc) {
101 OnlySucc = 0; // There are multiple distinct successors!
102 break;
103 }
104
105 // Can't merge if there are multiple successors.
106 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000107
108 // Can't merge if there is PHI loop.
109 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
110 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
111 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
112 if (PN->getIncomingValue(i) == PN)
113 return false;
114 } else
115 break;
116 }
117
Owen Andersonb31b06d2008-07-17 00:01:40 +0000118 // Begin by getting rid of unneeded PHIs.
119 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
120 PN->replaceAllUsesWith(PN->getIncomingValue(0));
121 BB->getInstList().pop_front(); // Delete the phi node...
122 }
123
124 // Delete the unconditional branch from the predecessor...
125 PredBB->getInstList().pop_back();
126
127 // Move all definitions in the successor to the predecessor...
128 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
129
130 // Make all PHI nodes that referred to BB now refer to Pred as their
131 // source...
132 BB->replaceAllUsesWith(PredBB);
133
Owen Anderson11f2ec82008-07-17 19:42:29 +0000134 // Inherit predecessors name if it exists.
135 if (!PredBB->hasName())
136 PredBB->takeName(BB);
137
Owen Andersonb31b06d2008-07-17 00:01:40 +0000138 // Finally, erase the old block and update dominator info.
139 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000140 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000141 DomTreeNode* DTN = DT->getNode(BB);
142 DomTreeNode* PredDTN = DT->getNode(PredBB);
143
144 if (DTN) {
145 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
146 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
147 DE = Children.end(); DI != DE; ++DI)
148 DT->changeImmediateDominator(*DI, PredDTN);
149
150 DT->eraseNode(BB);
151 }
152 }
153 }
154
155 BB->eraseFromParent();
156
157
158 return true;
159}
160
Chris Lattner0f67dd62005-04-21 16:04:49 +0000161/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
162/// with a value, then remove and delete the original instruction.
163///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000164void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
165 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000166 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000167 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000168 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000169
Chris Lattner86cc4232007-02-11 01:37:51 +0000170 // Make sure to propagate a name if there is one already.
171 if (I.hasName() && !V->hasName())
172 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000173
Misha Brukman5560c9d2003-08-18 14:43:39 +0000174 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000175 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000176}
177
178
Chris Lattner0f67dd62005-04-21 16:04:49 +0000179/// ReplaceInstWithInst - Replace the instruction specified by BI with the
180/// instruction specified by I. The original instruction is deleted and BI is
181/// updated to point to the new instruction.
182///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000183void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
184 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000185 assert(I->getParent() == 0 &&
186 "ReplaceInstWithInst: Instruction already inserted into basic block!");
187
188 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000189 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000190
191 // Replace all uses of the old instruction, and delete it.
192 ReplaceInstWithValue(BIL, BI, I);
193
194 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000195 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000196}
197
Chris Lattner0f67dd62005-04-21 16:04:49 +0000198/// ReplaceInstWithInst - Replace the instruction specified by From with the
199/// instruction specified by To.
200///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000201void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000202 BasicBlock::iterator BI(From);
203 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000204}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000205
Chris Lattner0f67dd62005-04-21 16:04:49 +0000206/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000207/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000208/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000209/// may have to be changed. In the case where the last successor of the block
210/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000211/// surprising change in program behavior if it is not expected.
212///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000213void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000214 assert(SuccNum < TI->getNumSuccessors() &&
215 "Trying to remove a nonexistant successor!");
216
217 // If our old successor block contains any PHI nodes, remove the entry in the
218 // PHI nodes that comes from this branch...
219 //
220 BasicBlock *BB = TI->getParent();
221 TI->getSuccessor(SuccNum)->removePredecessor(BB);
222
223 TerminatorInst *NewTI = 0;
224 switch (TI->getOpcode()) {
225 case Instruction::Br:
226 // If this is a conditional branch... convert to unconditional branch.
227 if (TI->getNumSuccessors() == 2) {
228 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
229 } else { // Otherwise convert to a return instruction...
230 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000231
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000232 // Create a value to return... if the function doesn't return null...
233 if (BB->getParent()->getReturnType() != Type::VoidTy)
234 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
235
236 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000237 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000238 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000239 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000240
241 case Instruction::Invoke: // Should convert to call
242 case Instruction::Switch: // Should remove entry
243 default:
244 case Instruction::Ret: // Cannot happen, has no successors!
245 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
246 abort();
247 }
248
249 if (NewTI) // If it's a different instruction, replace.
250 ReplaceInstWithInst(TI, NewTI);
251}
Brian Gaeked0fde302003-11-11 22:41:34 +0000252
Devang Patel80198932007-07-06 21:39:20 +0000253/// SplitEdge - Split the edge connecting specified block. Pass P must
254/// not be NULL.
255BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
256 TerminatorInst *LatchTerm = BB->getTerminator();
257 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000258#ifndef NDEBUG
259 unsigned e = LatchTerm->getNumSuccessors();
260#endif
261 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000262 assert(i != e && "Didn't find edge?");
263 if (LatchTerm->getSuccessor(i) == Succ) {
264 SuccNum = i;
265 break;
266 }
267 }
268
269 // If this is a critical edge, let SplitCriticalEdge do it.
270 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
271 return LatchTerm->getSuccessor(SuccNum);
272
273 // If the edge isn't critical, then BB has a single successor or Succ has a
274 // single pred. Split the block.
275 BasicBlock::iterator SplitPoint;
276 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
277 // If the successor only has a single pred, split the top of the successor
278 // block.
279 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000280 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000281 return SplitBlock(Succ, Succ->begin(), P);
282 } else {
283 // Otherwise, if BB has a single successor, split it at the bottom of the
284 // block.
285 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
286 "Should have a single succ!");
287 return SplitBlock(BB, BB->getTerminator(), P);
288 }
289}
290
291/// SplitBlock - Split the specified block at the specified instruction - every
292/// thing before SplitPt stays in Old and everything starting with SplitPt moves
293/// to a new block. The two blocks are joined by an unconditional branch and
294/// the loop info is updated.
295///
296BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000297 BasicBlock::iterator SplitIt = SplitPt;
298 while (isa<PHINode>(SplitIt))
299 ++SplitIt;
300 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
301
302 // The new block lives in whichever loop the old one did.
Duncan Sands1465d612009-01-28 13:14:17 +0000303 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000304 if (Loop *L = LI->getLoopFor(Old))
305 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000306
Duncan Sands1465d612009-01-28 13:14:17 +0000307 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000308 {
309 // Old dominates New. New node domiantes all other nodes dominated by Old.
310 DomTreeNode *OldNode = DT->getNode(Old);
311 std::vector<DomTreeNode *> Children;
312 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
313 I != E; ++I)
314 Children.push_back(*I);
315
316 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
317
318 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
319 E = Children.end(); I != E; ++I)
320 DT->changeImmediateDominator(*I, NewNode);
321 }
Devang Patel80198932007-07-06 21:39:20 +0000322
Duncan Sands1465d612009-01-28 13:14:17 +0000323 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000324 DF->splitBlock(Old);
325
326 return New;
327}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000328
329
330/// SplitBlockPredecessors - This method transforms BB by introducing a new
331/// basic block into the function, and moving some of the predecessors of BB to
332/// be predecessors of the new block. The new predecessors are indicated by the
333/// Preds array, which has NumPreds elements in it. The new block is given a
334/// suffix of 'Suffix'.
335///
336/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
337/// DominanceFrontier, but no other analyses.
338BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
339 BasicBlock *const *Preds,
340 unsigned NumPreds, const char *Suffix,
341 Pass *P) {
342 // Create new basic block, insert right before the original block.
343 BasicBlock *NewBB =
344 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
345
346 // The new block unconditionally branches to the old block.
347 BranchInst *BI = BranchInst::Create(BB, NewBB);
348
349 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000350 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000351 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000352
353 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000354 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000355 if (DT)
356 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000357 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000358 DF->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000359 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000360
361
362 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
363 // node becomes an incoming value for BB's phi node. However, if the Preds
364 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
365 // account for the newly created predecessor.
366 if (NumPreds == 0) {
367 // Insert dummy values as the incoming value.
368 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
369 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
370 return NewBB;
371 }
372
373 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
374 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
375 PHINode *PN = cast<PHINode>(I++);
376
377 // Check to see if all of the values coming in are the same. If so, we
378 // don't need to create a new PHI node.
379 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
380 for (unsigned i = 1; i != NumPreds; ++i)
381 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
382 InVal = 0;
383 break;
384 }
385
386 if (InVal) {
387 // If all incoming values for the new PHI would be the same, just don't
388 // make a new PHI. Instead, just remove the incoming values from the old
389 // PHI.
390 for (unsigned i = 0; i != NumPreds; ++i)
391 PN->removeIncomingValue(Preds[i], false);
392 } else {
393 // If the values coming into the block are not the same, we need a PHI.
394 // Create the new PHI node, insert it into NewBB at the end of the block
395 PHINode *NewPHI =
396 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
397 if (AA) AA->copyValue(PN, NewPHI);
398
399 // Move all of the PHI values for 'Preds' to the new PHI.
400 for (unsigned i = 0; i != NumPreds; ++i) {
401 Value *V = PN->removeIncomingValue(Preds[i], false);
402 NewPHI->addIncoming(V, Preds[i]);
403 }
404 InVal = NewPHI;
405 }
406
407 // Add an incoming value to the PHI node in the loop for the preheader
408 // edge.
409 PN->addIncoming(InVal, NewBB);
410
411 // Check to see if we can eliminate this phi node.
412 if (Value *V = PN->hasConstantValue(DT != 0)) {
413 Instruction *I = dyn_cast<Instruction>(V);
414 if (!I || DT == 0 || DT->dominates(I, PN)) {
415 PN->replaceAllUsesWith(V);
416 if (AA) AA->deleteValue(PN);
417 PN->eraseFromParent();
418 }
419 }
420 }
421
422 return NewBB;
423}
Chris Lattner52c95852008-11-27 08:10:05 +0000424
Chris Lattner4aebaee2008-11-27 08:56:30 +0000425/// AreEquivalentAddressValues - Test if A and B will obviously have the same
426/// value. This includes recognizing that %t0 and %t1 will have the same
427/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000428/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000429/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000430/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000431/// %t2 = load i32* %t1
432///
433static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
434 // Test if the values are trivially equivalent.
435 if (A == B) return true;
436
437 // Test if the values come form identical arithmetic instructions.
438 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
439 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
440 if (const Instruction *BI = dyn_cast<Instruction>(B))
441 if (cast<Instruction>(A)->isIdenticalTo(BI))
442 return true;
443
444 // Otherwise they may not be equivalent.
445 return false;
446}
447
Chris Lattner52c95852008-11-27 08:10:05 +0000448/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
449/// instruction before ScanFrom) checking to see if we have the value at the
450/// memory address *Ptr locally available within a small number of instructions.
451/// If the value is available, return it.
452///
453/// If not, return the iterator for the last validated instruction that the
454/// value would be live through. If we scanned the entire block and didn't find
455/// something that invalidates *Ptr or provides it, ScanFrom would be left at
456/// begin() and this returns null. ScanFrom could also be left
457///
458/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
459/// it is set to 0, it will scan the whole block. You can also optionally
460/// specify an alias analysis implementation, which makes this more precise.
461Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
462 BasicBlock::iterator &ScanFrom,
463 unsigned MaxInstsToScan,
464 AliasAnalysis *AA) {
465 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000466
467 // If we're using alias analysis to disambiguate get the size of *Ptr.
468 unsigned AccessSize = 0;
469 if (AA) {
470 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
471 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
472 }
Chris Lattner52c95852008-11-27 08:10:05 +0000473
474 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000475 // We must ignore debug info directives when counting (otherwise they
476 // would affect codegen).
477 Instruction *Inst = --ScanFrom;
478 if (isa<DbgInfoIntrinsic>(Inst))
479 continue;
480 // Restore ScanFrom to expected value in case next test succeeds
481 ScanFrom++;
482
Chris Lattner52c95852008-11-27 08:10:05 +0000483 // Don't scan huge blocks.
484 if (MaxInstsToScan-- == 0) return 0;
485
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000486 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000487 // If this is a load of Ptr, the loaded value is available.
488 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000489 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000490 return LI;
491
492 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
493 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000494 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000495 return SI->getOperand(0);
496
497 // If Ptr is an alloca and this is a store to a different alloca, ignore
498 // the store. This is a trivial form of alias analysis that is important
499 // for reg2mem'd code.
500 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
501 (isa<AllocaInst>(SI->getOperand(1)) ||
502 isa<GlobalVariable>(SI->getOperand(1))))
503 continue;
504
Chris Lattneree6e10b2008-11-27 08:18:12 +0000505 // If we have alias analysis and it says the store won't modify the loaded
506 // value, ignore the store.
507 if (AA &&
508 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
509 continue;
510
Chris Lattner52c95852008-11-27 08:10:05 +0000511 // Otherwise the store that may or may not alias the pointer, bail out.
512 ++ScanFrom;
513 return 0;
514 }
515
Chris Lattner52c95852008-11-27 08:10:05 +0000516 // If this is some other instruction that may clobber Ptr, bail out.
517 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000518 // If alias analysis claims that it really won't modify the load,
519 // ignore it.
520 if (AA &&
521 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
522 continue;
523
Chris Lattner52c95852008-11-27 08:10:05 +0000524 // May modify the pointer, bail out.
525 ++ScanFrom;
526 return 0;
527 }
528 }
529
530 // Got to the start of the block, we didn't find it, but are done for this
531 // block.
532 return 0;
533}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000534
535/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
536/// make a copy of the stoppoint before InsertPos (presumably before copying
537/// or moving I).
538void llvm::CopyPrecedingStopPoint(Instruction *I,
539 BasicBlock::iterator InsertPos) {
540 if (I != I->getParent()->begin()) {
541 BasicBlock::iterator BBI = I; --BBI;
542 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Dale Johannesen4945c652009-03-03 21:26:39 +0000543 CallInst *newDSPI = DSPI->clone();
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000544 newDSPI->insertBefore(InsertPos);
545 }
546 }
547}