blob: 28864fd613aff3249bb098b1cc6939d9c686bb11 [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-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 Lattner2853a7e2004-01-12 18:35:03 +000016#include "llvm/Constants.h"
Chris Lattnerc13c7b92005-09-26 05:27:10 +000017#include "llvm/DerivedTypes.h"
Chris Lattner6b052f212004-01-12 19:56:36 +000018#include "llvm/Instructions.h"
Chris Lattnerec941f72004-06-11 06:16:23 +000019#include "llvm/Intrinsics.h"
Chris Lattner479911f2005-10-27 16:34:00 +000020#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc13c7b92005-09-26 05:27:10 +000021#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/MathExtras.h"
Alkis Evlogimenosf68f40e2004-04-21 16:11:40 +000023#include <cerrno>
Brian Gaeke174633b2004-04-16 15:57:32 +000024#include <cmath>
Chris Lattner04efa4b2003-12-19 05:56:28 +000025using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000026
Chris Lattner28537df2002-05-07 18:07:59 +000027//===----------------------------------------------------------------------===//
Misha Brukman373086d2003-05-20 21:01:22 +000028// Local constant propagation...
Chris Lattner28537df2002-05-07 18:07:59 +000029//
30
Chris Lattner04efa4b2003-12-19 05:56:28 +000031/// doConstantPropagation - If an instruction references constants, try to fold
32/// them together...
33///
34bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattnerfda72b12002-06-25 16:12:52 +000035 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner28537df2002-05-07 18:07:59 +000036 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattnerfda72b12002-06-25 16:12:52 +000037 II->replaceAllUsesWith(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +000038
Chris Lattner28537df2002-05-07 18:07:59 +000039 // Remove the instruction from the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +000040 II = II->getParent()->getInstList().erase(II);
Chris Lattner28537df2002-05-07 18:07:59 +000041 return true;
42 }
43
44 return false;
45}
46
Chris Lattnerfc6c8592004-01-12 18:25:22 +000047/// ConstantFoldInstruction - Attempt to constant fold the specified
48/// instruction. If successful, the constant result is returned, if not, null
49/// is returned. Note that this function can only fail when attempting to fold
50/// instructions like loads and stores, which have no constant expression form.
51///
52Constant *llvm::ConstantFoldInstruction(Instruction *I) {
53 if (PHINode *PN = dyn_cast<PHINode>(I)) {
54 if (PN->getNumIncomingValues() == 0)
55 return Constant::getNullValue(PN->getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +000056
Chris Lattnerfc6c8592004-01-12 18:25:22 +000057 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
58 if (Result == 0) return 0;
59
60 // Handle PHI nodes specially here...
61 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
62 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
63 return 0; // Not all the same incoming constants...
Misha Brukmanb1c93172005-04-21 23:48:37 +000064
Chris Lattnerfc6c8592004-01-12 18:25:22 +000065 // If we reach here, all incoming values are the same constant.
66 return Result;
67 }
68
69 Constant *Op0 = 0, *Op1 = 0;
70 switch (I->getNumOperands()) {
71 default:
72 case 2:
73 Op1 = dyn_cast<Constant>(I->getOperand(1));
74 if (Op1 == 0) return 0; // Not a constant?, can't fold
75 case 1:
76 Op0 = dyn_cast<Constant>(I->getOperand(0));
77 if (Op0 == 0) return 0; // Not a constant?, can't fold
78 break;
79 case 0: return 0;
80 }
81
Chris Lattnerbc3c8792006-05-27 01:18:04 +000082 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) {
83 if (Constant *Op0 = dyn_cast<Constant>(I->getOperand(0)))
84 if (Constant *Op1 = dyn_cast<Constant>(I->getOperand(1)))
85 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
86 return 0; // Operands not constants.
87 }
Chris Lattnerfc6c8592004-01-12 18:25:22 +000088
Chris Lattnerbc3c8792006-05-27 01:18:04 +000089 // Scan the operand list, checking to see if the are all constants, if so,
90 // hand off to ConstantFoldInstOperands.
91 std::vector<Constant*> Ops;
92 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
93 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
94 Ops.push_back(Op);
95 else
96 return 0; // All operands not constant!
97
98 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops);
99}
100
101/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
102/// specified opcode and operands. If successful, the constant result is
103/// returned, if not, null is returned. Note that this function can fail when
104/// attempting to fold instructions like loads and stores, which have no
105/// constant expression form.
106///
107Constant *llvm::ConstantFoldInstOperands(unsigned Opc, const Type *DestTy,
108 const std::vector<Constant*> &Ops) {
109 if (Opc >= Instruction::BinaryOpsBegin && Opc < Instruction::BinaryOpsEnd)
110 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
111
112 switch (Opc) {
Chris Lattnerfc6c8592004-01-12 18:25:22 +0000113 default: return 0;
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000114 case Instruction::Call:
115 if (Function *F = dyn_cast<Function>(Ops[0])) {
116 if (canConstantFoldCallTo(F)) {
117 std::vector<Constant*> Args(Ops.begin()+1, Ops.end());
118 return ConstantFoldCall(F, Args);
119 }
120 }
121 return 0;
122 case Instruction::Shl:
123 case Instruction::Shr:
124 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
Chris Lattnerfc6c8592004-01-12 18:25:22 +0000125 case Instruction::Cast:
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000126 return ConstantExpr::getCast(Ops[0], DestTy);
Chris Lattnercb015ee2004-03-12 05:53:03 +0000127 case Instruction::Select:
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000128 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Robert Bocchino23004482006-01-10 19:05:34 +0000129 case Instruction::ExtractElement:
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000130 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Robert Bocchinoe6336a92006-01-17 20:07:07 +0000131 case Instruction::InsertElement:
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000132 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner17bd6052006-04-08 01:19:12 +0000133 case Instruction::ShuffleVector:
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000134 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattnerfc6c8592004-01-12 18:25:22 +0000135 case Instruction::GetElementPtr:
Chris Lattnerbc3c8792006-05-27 01:18:04 +0000136 return ConstantExpr::getGetElementPtr(Ops[0],
137 std::vector<Constant*>(Ops.begin()+1,
138 Ops.end()));
Chris Lattnerfc6c8592004-01-12 18:25:22 +0000139 }
140}
141
Chris Lattner28537df2002-05-07 18:07:59 +0000142// ConstantFoldTerminator - If a terminator instruction is predicated on a
143// constant value, convert it into an unconditional branch to the constant
144// destination.
145//
Chris Lattner04efa4b2003-12-19 05:56:28 +0000146bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner4b009ad2002-05-21 20:04:50 +0000147 TerminatorInst *T = BB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000148
Chris Lattner28537df2002-05-07 18:07:59 +0000149 // Branch - See if we are conditional jumping on constant
150 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
151 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
152 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
153 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
154
155 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
156 // Are we branching on constant?
157 // YES. Change to unconditional branch...
158 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
159 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
160
Misha Brukmanb1c93172005-04-21 23:48:37 +0000161 //cerr << "Function: " << T->getParent()->getParent()
162 // << "\nRemoving branch from " << T->getParent()
Chris Lattner28537df2002-05-07 18:07:59 +0000163 // << "\n\nTo: " << OldDest << endl;
164
165 // Let the basic block know that we are letting go of it. Based on this,
166 // it will adjust it's PHI nodes.
167 assert(BI->getParent() && "Terminator not inserted in block!");
168 OldDest->removePredecessor(BI->getParent());
169
170 // Set the unconditional destination, and change the insn to be an
171 // unconditional branch.
172 BI->setUnconditionalDest(Destination);
Chris Lattner28537df2002-05-07 18:07:59 +0000173 return true;
Chris Lattner4b7e3362003-08-17 19:34:55 +0000174 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanb1c93172005-04-21 23:48:37 +0000175 // This branch matches something like this:
Chris Lattner28537df2002-05-07 18:07:59 +0000176 // br bool %cond, label %Dest, label %Dest
177 // and changes it into: br label %Dest
178
179 // Let the basic block know that we are letting go of one copy of it.
180 assert(BI->getParent() && "Terminator not inserted in block!");
181 Dest1->removePredecessor(BI->getParent());
182
183 // Change a conditional branch to unconditional.
184 BI->setUnconditionalDest(Dest1);
185 return true;
186 }
Chris Lattner821deee2003-08-17 20:21:14 +0000187 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
188 // If we are switching on a constant, we can convert the switch into a
189 // single branch instruction!
190 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
191 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattnerc54d6082003-08-23 23:18:19 +0000192 BasicBlock *DefaultDest = TheOnlyDest;
193 assert(TheOnlyDest == SI->getDefaultDest() &&
194 "Default destination is not successor #0?");
Chris Lattner031340a2003-08-17 19:41:53 +0000195
Chris Lattner821deee2003-08-17 20:21:14 +0000196 // Figure out which case it goes to...
197 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
198 // Found case matching a constant operand?
199 if (SI->getSuccessorValue(i) == CI) {
200 TheOnlyDest = SI->getSuccessor(i);
201 break;
202 }
Chris Lattner031340a2003-08-17 19:41:53 +0000203
Chris Lattnerc54d6082003-08-23 23:18:19 +0000204 // Check to see if this branch is going to the same place as the default
205 // dest. If so, eliminate it as an explicit compare.
206 if (SI->getSuccessor(i) == DefaultDest) {
207 // Remove this entry...
208 DefaultDest->removePredecessor(SI->getParent());
209 SI->removeCase(i);
210 --i; --e; // Don't skip an entry...
211 continue;
212 }
213
Chris Lattner821deee2003-08-17 20:21:14 +0000214 // Otherwise, check to see if the switch only branches to one destination.
215 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
216 // destinations.
217 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner031340a2003-08-17 19:41:53 +0000218 }
219
Chris Lattner821deee2003-08-17 20:21:14 +0000220 if (CI && !TheOnlyDest) {
221 // Branching on a constant, but not any of the cases, go to the default
222 // successor.
223 TheOnlyDest = SI->getDefaultDest();
224 }
225
226 // If we found a single destination that we can fold the switch into, do so
227 // now.
228 if (TheOnlyDest) {
229 // Insert the new branch..
230 new BranchInst(TheOnlyDest, SI);
231 BasicBlock *BB = SI->getParent();
232
233 // Remove entries from PHI nodes which we no longer branch to...
234 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
235 // Found case matching a constant operand?
236 BasicBlock *Succ = SI->getSuccessor(i);
237 if (Succ == TheOnlyDest)
238 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
239 else
240 Succ->removePredecessor(BB);
241 }
242
243 // Delete the old switch...
244 BB->getInstList().erase(SI);
245 return true;
246 } else if (SI->getNumSuccessors() == 2) {
247 // Otherwise, we can fold this switch into a conditional branch
248 // instruction if it has only one non-default destination.
249 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
250 SI->getSuccessorValue(1), "cond", SI);
251 // Insert the new branch...
252 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
253
254 // Delete the old switch...
255 SI->getParent()->getInstList().erase(SI);
256 return true;
257 }
Chris Lattner28537df2002-05-07 18:07:59 +0000258 }
259 return false;
260}
261
Chris Lattnerc13c7b92005-09-26 05:27:10 +0000262/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
263/// getelementptr constantexpr, return the constant value being addressed by the
264/// constant expression, or null if something is funny and we can't decide.
265Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
266 ConstantExpr *CE) {
267 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
268 return 0; // Do not allow stepping over the value!
269
270 // Loop over all of the operands, tracking down which value we are
271 // addressing...
272 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
273 for (++I; I != E; ++I)
274 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000275 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
276 assert(CU->getZExtValue() < STy->getNumElements() &&
Chris Lattnerc13c7b92005-09-26 05:27:10 +0000277 "Struct index out of range!");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000278 unsigned El = (unsigned)CU->getZExtValue();
Chris Lattnerc13c7b92005-09-26 05:27:10 +0000279 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
280 C = CS->getOperand(El);
281 } else if (isa<ConstantAggregateZero>(C)) {
282 C = Constant::getNullValue(STy->getElementType(El));
283 } else if (isa<UndefValue>(C)) {
284 C = UndefValue::get(STy->getElementType(El));
285 } else {
286 return 0;
287 }
288 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
Robert Bocchino027c18d2006-01-19 23:53:23 +0000289 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000290 if (CI->getZExtValue() >= ATy->getNumElements())
Chris Lattner08537002006-05-25 21:25:12 +0000291 return 0;
Robert Bocchino027c18d2006-01-19 23:53:23 +0000292 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000293 C = CA->getOperand(CI->getZExtValue());
Robert Bocchino027c18d2006-01-19 23:53:23 +0000294 else if (isa<ConstantAggregateZero>(C))
295 C = Constant::getNullValue(ATy->getElementType());
296 else if (isa<UndefValue>(C))
297 C = UndefValue::get(ATy->getElementType());
298 else
299 return 0;
300 } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000301 if (CI->getZExtValue() >= PTy->getNumElements())
Chris Lattner08537002006-05-25 21:25:12 +0000302 return 0;
Robert Bocchino027c18d2006-01-19 23:53:23 +0000303 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000304 C = CP->getOperand(CI->getZExtValue());
Robert Bocchino027c18d2006-01-19 23:53:23 +0000305 else if (isa<ConstantAggregateZero>(C))
306 C = Constant::getNullValue(PTy->getElementType());
307 else if (isa<UndefValue>(C))
308 C = UndefValue::get(PTy->getElementType());
309 else
310 return 0;
311 } else {
Chris Lattnerc13c7b92005-09-26 05:27:10 +0000312 return 0;
Robert Bocchino027c18d2006-01-19 23:53:23 +0000313 }
Chris Lattnerc13c7b92005-09-26 05:27:10 +0000314 } else {
315 return 0;
316 }
317 return C;
318}
Chris Lattner28537df2002-05-07 18:07:59 +0000319
320
321//===----------------------------------------------------------------------===//
322// Local dead code elimination...
323//
324
Chris Lattner04efa4b2003-12-19 05:56:28 +0000325bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnera36d5252005-05-06 05:27:34 +0000326 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000327
Chris Lattnera36d5252005-05-06 05:27:34 +0000328 if (!I->mayWriteToMemory()) return true;
329
330 if (CallInst *CI = dyn_cast<CallInst>(I))
Chris Lattner60f68332006-03-09 22:38:10 +0000331 if (Function *F = CI->getCalledFunction()) {
Chris Lattner70ec96f2006-04-02 03:35:01 +0000332 unsigned IntrinsicID = F->getIntrinsicID();
Chris Lattner60f68332006-03-09 22:38:10 +0000333#define GET_SIDE_EFFECT_INFO
334#include "llvm/Intrinsics.gen"
335#undef GET_SIDE_EFFECT_INFO
336 }
Chris Lattnera36d5252005-05-06 05:27:34 +0000337 return false;
Chris Lattner28537df2002-05-07 18:07:59 +0000338}
339
340// dceInstruction - Inspect the instruction at *BBI and figure out if it's
341// [trivially] dead. If so, remove the instruction and update the iterator
342// to point to the instruction that immediately succeeded the original
343// instruction.
344//
Chris Lattner04efa4b2003-12-19 05:56:28 +0000345bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner28537df2002-05-07 18:07:59 +0000346 // Look for un"used" definitions...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000347 if (isInstructionTriviallyDead(BBI)) {
348 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner28537df2002-05-07 18:07:59 +0000349 return true;
350 }
351 return false;
352}