blob: 8c08638c4c3d7c7ff674d90e0b2755c8cd494bf9 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
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 various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ebc302004-01-12 18:35:03 +000016#include "llvm/Constants.h"
Chris Lattner6cc8a932009-06-16 17:23:12 +000017#include "llvm/GlobalAlias.h"
Devang Patelc79e1182009-03-06 00:19:37 +000018#include "llvm/GlobalVariable.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000020#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000021#include "llvm/Intrinsics.h"
Chris Lattner741c0ae2007-12-29 00:59:12 +000022#include "llvm/IntrinsicInst.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000024#include "llvm/Analysis/ConstantFolding.h"
Devang Patelc79e1182009-03-06 00:19:37 +000025#include "llvm/Analysis/DebugInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000026#include "llvm/Target/TargetData.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/MathExtras.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner4d1e46e2002-05-07 18:07:59 +000031//===----------------------------------------------------------------------===//
Chris Lattner6cc8a932009-06-16 17:23:12 +000032// Local analysis.
33//
34
35/// isSafeToLoadUnconditionally - Return true if we know that executing a load
36/// from this value cannot trap. If it is not obviously safe to load from the
37/// specified pointer, we do a quick local scan of the basic block containing
38/// ScanFrom, to determine if the address is already accessed.
39bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
40 // If it is an alloca it is always safe to load from.
41 if (isa<AllocaInst>(V)) return true;
42
43 // If it is a global variable it is mostly safe to load from.
44 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
45 // Don't try to evaluate aliases. External weak GV can be null.
46 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
47
48 // Otherwise, be a little bit agressive by scanning the local block where we
49 // want to check to see if the pointer is already being loaded or stored
50 // from/to. If so, the previous load or store would have already trapped,
51 // so there is no harm doing an extra load (also, CSE will later eliminate
52 // the load entirely).
53 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
54
55 while (BBI != E) {
56 --BBI;
57
58 // If we see a free or a call which may write to memory (i.e. which might do
59 // a free) the pointer could be marked invalid.
60 if (isa<FreeInst>(BBI) ||
61 (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
62 !isa<DbgInfoIntrinsic>(BBI)))
63 return false;
64
65 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
66 if (LI->getOperand(0) == V) return true;
67 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
68 if (SI->getOperand(1) == V) return true;
69 }
70 }
71 return false;
72}
73
74
75//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000076// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000077//
78
Chris Lattner4d1e46e2002-05-07 18:07:59 +000079// ConstantFoldTerminator - If a terminator instruction is predicated on a
80// constant value, convert it into an unconditional branch to the constant
81// destination.
82//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000083bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +000084 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +000085
Chris Lattner4d1e46e2002-05-07 18:07:59 +000086 // Branch - See if we are conditional jumping on constant
87 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
88 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greifc1bb13f2009-01-30 18:21:13 +000089 BasicBlock *Dest1 = BI->getSuccessor(0);
90 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000091
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000092 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000093 // Are we branching on constant?
94 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000095 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
96 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000097
Misha Brukmanfd939082005-04-21 23:48:37 +000098 //cerr << "Function: " << T->getParent()->getParent()
99 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000100 // << "\n\nTo: " << OldDest << endl;
101
102 // Let the basic block know that we are letting go of it. Based on this,
103 // it will adjust it's PHI nodes.
104 assert(BI->getParent() && "Terminator not inserted in block!");
105 OldDest->removePredecessor(BI->getParent());
106
107 // Set the unconditional destination, and change the insn to be an
108 // unconditional branch.
109 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000110 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000111 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +0000112 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000113 // br bool %cond, label %Dest, label %Dest
114 // and changes it into: br label %Dest
115
116 // Let the basic block know that we are letting go of one copy of it.
117 assert(BI->getParent() && "Terminator not inserted in block!");
118 Dest1->removePredecessor(BI->getParent());
119
120 // Change a conditional branch to unconditional.
121 BI->setUnconditionalDest(Dest1);
122 return true;
123 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000124 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
125 // If we are switching on a constant, we can convert the switch into a
126 // single branch instruction!
127 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
128 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000129 BasicBlock *DefaultDest = TheOnlyDest;
130 assert(TheOnlyDest == SI->getDefaultDest() &&
131 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000132
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000133 // Figure out which case it goes to...
134 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
135 // Found case matching a constant operand?
136 if (SI->getSuccessorValue(i) == CI) {
137 TheOnlyDest = SI->getSuccessor(i);
138 break;
139 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000140
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000141 // Check to see if this branch is going to the same place as the default
142 // dest. If so, eliminate it as an explicit compare.
143 if (SI->getSuccessor(i) == DefaultDest) {
144 // Remove this entry...
145 DefaultDest->removePredecessor(SI->getParent());
146 SI->removeCase(i);
147 --i; --e; // Don't skip an entry...
148 continue;
149 }
150
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000151 // Otherwise, check to see if the switch only branches to one destination.
152 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
153 // destinations.
154 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000155 }
156
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000157 if (CI && !TheOnlyDest) {
158 // Branching on a constant, but not any of the cases, go to the default
159 // successor.
160 TheOnlyDest = SI->getDefaultDest();
161 }
162
163 // If we found a single destination that we can fold the switch into, do so
164 // now.
165 if (TheOnlyDest) {
166 // Insert the new branch..
Gabor Greif051a9502008-04-06 20:25:17 +0000167 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000168 BasicBlock *BB = SI->getParent();
169
170 // Remove entries from PHI nodes which we no longer branch to...
171 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
172 // Found case matching a constant operand?
173 BasicBlock *Succ = SI->getSuccessor(i);
174 if (Succ == TheOnlyDest)
175 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
176 else
177 Succ->removePredecessor(BB);
178 }
179
180 // Delete the old switch...
181 BB->getInstList().erase(SI);
182 return true;
183 } else if (SI->getNumSuccessors() == 2) {
184 // Otherwise, we can fold this switch into a conditional branch
185 // instruction if it has only one non-default destination.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000186 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
187 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000188 // Insert the new branch...
Gabor Greif051a9502008-04-06 20:25:17 +0000189 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000190
191 // Delete the old switch...
Dan Gohman1adec832008-06-21 22:08:46 +0000192 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000193 return true;
194 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000195 }
196 return false;
197}
198
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000199
200//===----------------------------------------------------------------------===//
201// Local dead code elimination...
202//
203
Chris Lattner3481f242008-11-27 22:57:53 +0000204/// isInstructionTriviallyDead - Return true if the result produced by the
205/// instruction is not used, and the instruction has no side effects.
206///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000207bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000208 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000209
Dale Johannesen127a7932009-03-03 23:30:00 +0000210 // We don't want debug info removed by anything this general.
211 if (isa<DbgInfoIntrinsic>(I)) return false;
Chris Lattnerec710c52005-05-06 05:27:34 +0000212
Duncan Sands7af1c782009-05-06 06:49:50 +0000213 if (!I->mayHaveSideEffects()) return true;
214
215 // Special case intrinsics that "may have side effects" but can be deleted
216 // when dead.
Chris Lattner741c0ae2007-12-29 00:59:12 +0000217 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
218 // Safe to delete llvm.stacksave if dead.
219 if (II->getIntrinsicID() == Intrinsic::stacksave)
220 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000221 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000222}
223
Chris Lattner3481f242008-11-27 22:57:53 +0000224/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
225/// trivially dead instruction, delete it. If that makes any of its operands
226/// trivially dead, delete them too, recursively.
Dan Gohman35738ac2009-05-04 22:30:44 +0000227void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
Chris Lattner3481f242008-11-27 22:57:53 +0000228 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner76057302008-11-28 01:20:46 +0000229 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
230 return;
Chris Lattner3481f242008-11-27 22:57:53 +0000231
Chris Lattner76057302008-11-28 01:20:46 +0000232 SmallVector<Instruction*, 16> DeadInsts;
233 DeadInsts.push_back(I);
Chris Lattner3481f242008-11-27 22:57:53 +0000234
Chris Lattner76057302008-11-28 01:20:46 +0000235 while (!DeadInsts.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000236 I = DeadInsts.pop_back_val();
Chris Lattner28721772008-11-28 00:58:15 +0000237
Chris Lattner76057302008-11-28 01:20:46 +0000238 // Null out all of the instruction's operands to see if any operand becomes
239 // dead as we go.
240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
241 Value *OpV = I->getOperand(i);
242 I->setOperand(i, 0);
243
244 if (!OpV->use_empty()) continue;
245
246 // If the operand is an instruction that became dead as we nulled out the
247 // operand, and if it is 'trivially' dead, delete it in a future loop
248 // iteration.
249 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
250 if (isInstructionTriviallyDead(OpI))
251 DeadInsts.push_back(OpI);
252 }
253
254 I->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000255 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000256}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000257
Dan Gohmanafc36a92009-05-02 18:29:22 +0000258/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
259/// dead PHI node, due to being a def-use chain of single-use nodes that
260/// either forms a cycle or is terminated by a trivially dead instruction,
261/// delete it. If that makes any of its operands trivially dead, delete them
262/// too, recursively.
Dan Gohmanafc36a92009-05-02 18:29:22 +0000263void
Dan Gohman35738ac2009-05-04 22:30:44 +0000264llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
Dan Gohmanafc36a92009-05-02 18:29:22 +0000265
266 // We can remove a PHI if it is on a cycle in the def-use graph
267 // where each node in the cycle has degree one, i.e. only one use,
268 // and is an instruction with no side effects.
269 if (!PN->hasOneUse())
270 return;
271
272 SmallPtrSet<PHINode *, 4> PHIs;
273 PHIs.insert(PN);
274 for (Instruction *J = cast<Instruction>(*PN->use_begin());
Duncan Sands7af1c782009-05-06 06:49:50 +0000275 J->hasOneUse() && !J->mayHaveSideEffects();
Dan Gohmanafc36a92009-05-02 18:29:22 +0000276 J = cast<Instruction>(*J->use_begin()))
277 // If we find a PHI more than once, we're on a cycle that
278 // won't prove fruitful.
279 if (PHINode *JP = dyn_cast<PHINode>(J))
280 if (!PHIs.insert(cast<PHINode>(JP))) {
281 // Break the cycle and delete the PHI and its operands.
282 JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
Dan Gohman35738ac2009-05-04 22:30:44 +0000283 RecursivelyDeleteTriviallyDeadInstructions(JP);
Dan Gohmanafc36a92009-05-02 18:29:22 +0000284 break;
285 }
286}
Chris Lattner3481f242008-11-27 22:57:53 +0000287
Chris Lattnerb29714a2008-11-27 07:43:12 +0000288//===----------------------------------------------------------------------===//
289// Control Flow Graph Restructuring...
290//
291
292/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
293/// predecessor is known to have one successor (DestBB!). Eliminate the edge
294/// between them, moving the instructions in the predecessor into DestBB and
295/// deleting the predecessor block.
296///
297void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
298 // If BB has single-entry PHI nodes, fold them.
299 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
300 Value *NewVal = PN->getIncomingValue(0);
301 // Replace self referencing PHI with undef, it must be dead.
302 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
303 PN->replaceAllUsesWith(NewVal);
304 PN->eraseFromParent();
305 }
306
307 BasicBlock *PredBB = DestBB->getSinglePredecessor();
308 assert(PredBB && "Block doesn't have a single predecessor!");
309
310 // Splice all the instructions from PredBB to DestBB.
311 PredBB->getTerminator()->eraseFromParent();
312 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
313
314 // Anything that branched to PredBB now branches to DestBB.
315 PredBB->replaceAllUsesWith(DestBB);
316
317 // Nuke BB.
318 PredBB->eraseFromParent();
319}
Devang Patel4afc90d2009-02-10 07:00:59 +0000320
321/// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
322/// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
323/// with the DbgInfoIntrinsic that use the instruction I.
324bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
325 SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
326 if (DbgInUses)
327 DbgInUses->clear();
328
329 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
330 ++UI) {
331 if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
332 if (DbgInUses)
333 DbgInUses->push_back(DI);
334 } else {
335 if (DbgInUses)
336 DbgInUses->clear();
337 return false;
338 }
339 }
340 return true;
341}
Devang Patelc79e1182009-03-06 00:19:37 +0000342