blob: aa6efe80b32f25f82821172b321832200c7f480f [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 Lattnerc5f52e62005-09-26 05:27:10 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000018#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000019#include "llvm/Intrinsics.h"
Chris Lattner741c0ae2007-12-29 00:59:12 +000020#include "llvm/IntrinsicInst.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000021#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000023#include "llvm/Support/GetElementPtrTypeIterator.h"
24#include "llvm/Support/MathExtras.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner4d1e46e2002-05-07 18:07:59 +000027//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000028// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000029//
30
Chris Lattner4d1e46e2002-05-07 18:07:59 +000031// ConstantFoldTerminator - If a terminator instruction is predicated on a
32// constant value, convert it into an unconditional branch to the constant
33// destination.
34//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000035bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +000036 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +000037
Chris Lattner4d1e46e2002-05-07 18:07:59 +000038 // Branch - See if we are conditional jumping on constant
39 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
40 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greifc1bb13f2009-01-30 18:21:13 +000041 BasicBlock *Dest1 = BI->getSuccessor(0);
42 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000043
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000044 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000045 // Are we branching on constant?
46 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000047 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
48 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000049
Misha Brukmanfd939082005-04-21 23:48:37 +000050 //cerr << "Function: " << T->getParent()->getParent()
51 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +000052 // << "\n\nTo: " << OldDest << endl;
53
54 // Let the basic block know that we are letting go of it. Based on this,
55 // it will adjust it's PHI nodes.
56 assert(BI->getParent() && "Terminator not inserted in block!");
57 OldDest->removePredecessor(BI->getParent());
58
59 // Set the unconditional destination, and change the insn to be an
60 // unconditional branch.
61 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000062 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +000063 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +000064 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +000065 // br bool %cond, label %Dest, label %Dest
66 // and changes it into: br label %Dest
67
68 // Let the basic block know that we are letting go of one copy of it.
69 assert(BI->getParent() && "Terminator not inserted in block!");
70 Dest1->removePredecessor(BI->getParent());
71
72 // Change a conditional branch to unconditional.
73 BI->setUnconditionalDest(Dest1);
74 return true;
75 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +000076 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
77 // If we are switching on a constant, we can convert the switch into a
78 // single branch instruction!
79 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
80 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +000081 BasicBlock *DefaultDest = TheOnlyDest;
82 assert(TheOnlyDest == SI->getDefaultDest() &&
83 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +000084
Chris Lattner10b1f5a2003-08-17 20:21:14 +000085 // Figure out which case it goes to...
86 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
87 // Found case matching a constant operand?
88 if (SI->getSuccessorValue(i) == CI) {
89 TheOnlyDest = SI->getSuccessor(i);
90 break;
91 }
Chris Lattner694e37f2003-08-17 19:41:53 +000092
Chris Lattner7d6c24c2003-08-23 23:18:19 +000093 // Check to see if this branch is going to the same place as the default
94 // dest. If so, eliminate it as an explicit compare.
95 if (SI->getSuccessor(i) == DefaultDest) {
96 // Remove this entry...
97 DefaultDest->removePredecessor(SI->getParent());
98 SI->removeCase(i);
99 --i; --e; // Don't skip an entry...
100 continue;
101 }
102
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000103 // Otherwise, check to see if the switch only branches to one destination.
104 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
105 // destinations.
106 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000107 }
108
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000109 if (CI && !TheOnlyDest) {
110 // Branching on a constant, but not any of the cases, go to the default
111 // successor.
112 TheOnlyDest = SI->getDefaultDest();
113 }
114
115 // If we found a single destination that we can fold the switch into, do so
116 // now.
117 if (TheOnlyDest) {
118 // Insert the new branch..
Gabor Greif051a9502008-04-06 20:25:17 +0000119 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000120 BasicBlock *BB = SI->getParent();
121
122 // Remove entries from PHI nodes which we no longer branch to...
123 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
124 // Found case matching a constant operand?
125 BasicBlock *Succ = SI->getSuccessor(i);
126 if (Succ == TheOnlyDest)
127 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
128 else
129 Succ->removePredecessor(BB);
130 }
131
132 // Delete the old switch...
133 BB->getInstList().erase(SI);
134 return true;
135 } else if (SI->getNumSuccessors() == 2) {
136 // Otherwise, we can fold this switch into a conditional branch
137 // instruction if it has only one non-default destination.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000138 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
139 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000140 // Insert the new branch...
Gabor Greif051a9502008-04-06 20:25:17 +0000141 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000142
143 // Delete the old switch...
Dan Gohman1adec832008-06-21 22:08:46 +0000144 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000145 return true;
146 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000147 }
148 return false;
149}
150
Devang Patel1851db62009-02-05 19:15:39 +0000151//===----------------------------------------------------------------------===//
152// CFG Simplification
153//
154
155/// isTerminatorFirstRelevantInsn - Return true if Term is very first
156/// instruction ignoring Phi nodes and dbg intrinsics.
157bool llvm::isTerminatorFirstRelevantInsn(BasicBlock *BB, Instruction *Term) {
158 BasicBlock::iterator BBI = Term;
159 while (BBI != BB->begin()) {
160 --BBI;
161 if (!isa<DbgInfoIntrinsic>(BBI))
162 break;
163 }
164 if (isa<PHINode>(BBI) || &*BBI == Term)
165 return true;
166 return false;
167}
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000168
169//===----------------------------------------------------------------------===//
170// Local dead code elimination...
171//
172
Chris Lattner3481f242008-11-27 22:57:53 +0000173/// isInstructionTriviallyDead - Return true if the result produced by the
174/// instruction is not used, and the instruction has no side effects.
175///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000176bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000177 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000178
Chris Lattner741c0ae2007-12-29 00:59:12 +0000179 if (!I->mayWriteToMemory())
180 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000181
Chris Lattner741c0ae2007-12-29 00:59:12 +0000182 // Special case intrinsics that "may write to memory" but can be deleted when
183 // dead.
184 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
185 // Safe to delete llvm.stacksave if dead.
186 if (II->getIntrinsicID() == Intrinsic::stacksave)
187 return true;
188
Chris Lattnerec710c52005-05-06 05:27:34 +0000189 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000190}
191
Chris Lattner3481f242008-11-27 22:57:53 +0000192/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
193/// trivially dead instruction, delete it. If that makes any of its operands
194/// trivially dead, delete them too, recursively.
Chris Lattner4f02c742008-11-27 23:14:34 +0000195///
196/// If DeadInst is specified, the vector is filled with the instructions that
197/// are actually deleted.
198void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
199 SmallVectorImpl<Instruction*> *DeadInst) {
Chris Lattner3481f242008-11-27 22:57:53 +0000200 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner76057302008-11-28 01:20:46 +0000201 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
202 return;
Chris Lattner3481f242008-11-27 22:57:53 +0000203
Chris Lattner76057302008-11-28 01:20:46 +0000204 SmallVector<Instruction*, 16> DeadInsts;
205 DeadInsts.push_back(I);
Chris Lattner3481f242008-11-27 22:57:53 +0000206
Chris Lattner76057302008-11-28 01:20:46 +0000207 while (!DeadInsts.empty()) {
208 I = DeadInsts.back();
209 DeadInsts.pop_back();
Chris Lattner28721772008-11-28 00:58:15 +0000210
Chris Lattner76057302008-11-28 01:20:46 +0000211 // If the client wanted to know, tell it about deleted instructions.
Chris Lattner4f02c742008-11-27 23:14:34 +0000212 if (DeadInst)
213 DeadInst->push_back(I);
Chris Lattner76057302008-11-28 01:20:46 +0000214
215 // Null out all of the instruction's operands to see if any operand becomes
216 // dead as we go.
217 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
218 Value *OpV = I->getOperand(i);
219 I->setOperand(i, 0);
220
221 if (!OpV->use_empty()) continue;
222
223 // If the operand is an instruction that became dead as we nulled out the
224 // operand, and if it is 'trivially' dead, delete it in a future loop
225 // iteration.
226 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
227 if (isInstructionTriviallyDead(OpI))
228 DeadInsts.push_back(OpI);
229 }
230
231 I->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000232 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000233}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000234
Chris Lattner3481f242008-11-27 22:57:53 +0000235
Chris Lattnerb29714a2008-11-27 07:43:12 +0000236//===----------------------------------------------------------------------===//
237// Control Flow Graph Restructuring...
238//
239
240/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
241/// predecessor is known to have one successor (DestBB!). Eliminate the edge
242/// between them, moving the instructions in the predecessor into DestBB and
243/// deleting the predecessor block.
244///
245void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
246 // If BB has single-entry PHI nodes, fold them.
247 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
248 Value *NewVal = PN->getIncomingValue(0);
249 // Replace self referencing PHI with undef, it must be dead.
250 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
251 PN->replaceAllUsesWith(NewVal);
252 PN->eraseFromParent();
253 }
254
255 BasicBlock *PredBB = DestBB->getSinglePredecessor();
256 assert(PredBB && "Block doesn't have a single predecessor!");
257
258 // Splice all the instructions from PredBB to DestBB.
259 PredBB->getTerminator()->eraseFromParent();
260 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
261
262 // Anything that branched to PredBB now branches to DestBB.
263 PredBB->replaceAllUsesWith(DestBB);
264
265 // Nuke BB.
266 PredBB->eraseFromParent();
267}