blob: 677a7dcc1ca68fe5203fbf5190c893823f1dfbc4 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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 Lattner7822c2a2004-01-12 19:56:36 +000017#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000018#include "llvm/Intrinsics.h"
Alkis Evlogimenos09233fb2004-04-21 16:11:40 +000019#include <cerrno>
Brian Gaekec5985172004-04-16 15:57:32 +000020#include <cmath>
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000021using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000022
Chris Lattner30c02f72004-06-21 06:17:21 +000023#if 0
Brian Gaekefda2cce2004-06-14 06:33:19 +000024#if defined(__POWERPC__) && defined(__APPLE_CC__)
25// FIXME: Currently it seems that isnan didn't make its way into the Apple
26// C++ headers, although it IS in the C headers (which confuses autoconf
27// in a big way). This is a quick fix to get things compiling, until one of
28// us has time to write a more complicated autoconf test.
29extern "C" int isnan (double d);
Brian Gaekeafe16e12004-06-17 22:27:04 +000030namespace std { int isnan (double d) { return ::isnan (d); } }
Brian Gaekefda2cce2004-06-14 06:33:19 +000031#endif
32
Chris Lattner30c02f72004-06-21 06:17:21 +000033#endif
34
Chris Lattner4d1e46e2002-05-07 18:07:59 +000035//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000036// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000037//
38
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000039/// doConstantPropagation - If an instruction references constants, try to fold
40/// them together...
41///
42bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000043 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000044 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000045 II->replaceAllUsesWith(C);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000046
47 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000048 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000049 return true;
50 }
51
52 return false;
53}
54
Chris Lattner8f90b002004-01-12 18:25:22 +000055/// ConstantFoldInstruction - Attempt to constant fold the specified
56/// instruction. If successful, the constant result is returned, if not, null
57/// is returned. Note that this function can only fail when attempting to fold
58/// instructions like loads and stores, which have no constant expression form.
59///
60Constant *llvm::ConstantFoldInstruction(Instruction *I) {
61 if (PHINode *PN = dyn_cast<PHINode>(I)) {
62 if (PN->getNumIncomingValues() == 0)
63 return Constant::getNullValue(PN->getType());
64
65 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
66 if (Result == 0) return 0;
67
68 // Handle PHI nodes specially here...
69 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
70 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
71 return 0; // Not all the same incoming constants...
72
73 // If we reach here, all incoming values are the same constant.
74 return Result;
Chris Lattner25b83902004-04-13 19:28:52 +000075 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
76 if (Function *F = CI->getCalledFunction())
77 if (canConstantFoldCallTo(F)) {
78 std::vector<Constant*> Args;
79 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
80 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
81 Args.push_back(Op);
82 else
83 return 0;
84 return ConstantFoldCall(F, Args);
85 }
86 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +000087 }
88
89 Constant *Op0 = 0, *Op1 = 0;
90 switch (I->getNumOperands()) {
91 default:
92 case 2:
93 Op1 = dyn_cast<Constant>(I->getOperand(1));
94 if (Op1 == 0) return 0; // Not a constant?, can't fold
95 case 1:
96 Op0 = dyn_cast<Constant>(I->getOperand(0));
97 if (Op0 == 0) return 0; // Not a constant?, can't fold
98 break;
99 case 0: return 0;
100 }
101
Chris Lattnerc6646eb2004-01-12 19:10:58 +0000102 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Chris Lattner8f90b002004-01-12 18:25:22 +0000103 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
104
105 switch (I->getOpcode()) {
106 default: return 0;
107 case Instruction::Cast:
108 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattner17fd2732004-03-12 05:53:03 +0000109 case Instruction::Select:
110 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
111 return ConstantExpr::getSelect(Op0, Op1, Op2);
112 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +0000113 case Instruction::GetElementPtr:
114 std::vector<Constant*> IdxList;
115 IdxList.reserve(I->getNumOperands()-1);
116 if (Op1) IdxList.push_back(Op1);
117 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
118 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
119 IdxList.push_back(C);
120 else
121 return 0; // Non-constant operand
122 return ConstantExpr::getGetElementPtr(Op0, IdxList);
123 }
124}
125
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000126// ConstantFoldTerminator - If a terminator instruction is predicated on a
127// constant value, convert it into an unconditional branch to the constant
128// destination.
129//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000130bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000131 TerminatorInst *T = BB->getTerminator();
132
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000133 // Branch - See if we are conditional jumping on constant
134 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
135 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
136 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
137 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
138
139 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
140 // Are we branching on constant?
141 // YES. Change to unconditional branch...
142 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
143 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
144
145 //cerr << "Function: " << T->getParent()->getParent()
146 // << "\nRemoving branch from " << T->getParent()
147 // << "\n\nTo: " << OldDest << endl;
148
149 // Let the basic block know that we are letting go of it. Based on this,
150 // it will adjust it's PHI nodes.
151 assert(BI->getParent() && "Terminator not inserted in block!");
152 OldDest->removePredecessor(BI->getParent());
153
154 // Set the unconditional destination, and change the insn to be an
155 // unconditional branch.
156 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000157 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000158 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000159 // This branch matches something like this:
160 // br bool %cond, label %Dest, label %Dest
161 // and changes it into: br label %Dest
162
163 // Let the basic block know that we are letting go of one copy of it.
164 assert(BI->getParent() && "Terminator not inserted in block!");
165 Dest1->removePredecessor(BI->getParent());
166
167 // Change a conditional branch to unconditional.
168 BI->setUnconditionalDest(Dest1);
169 return true;
170 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000171 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
172 // If we are switching on a constant, we can convert the switch into a
173 // single branch instruction!
174 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
175 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000176 BasicBlock *DefaultDest = TheOnlyDest;
177 assert(TheOnlyDest == SI->getDefaultDest() &&
178 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000179
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000180 // Figure out which case it goes to...
181 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
182 // Found case matching a constant operand?
183 if (SI->getSuccessorValue(i) == CI) {
184 TheOnlyDest = SI->getSuccessor(i);
185 break;
186 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000187
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000188 // Check to see if this branch is going to the same place as the default
189 // dest. If so, eliminate it as an explicit compare.
190 if (SI->getSuccessor(i) == DefaultDest) {
191 // Remove this entry...
192 DefaultDest->removePredecessor(SI->getParent());
193 SI->removeCase(i);
194 --i; --e; // Don't skip an entry...
195 continue;
196 }
197
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000198 // Otherwise, check to see if the switch only branches to one destination.
199 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
200 // destinations.
201 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000202 }
203
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000204 if (CI && !TheOnlyDest) {
205 // Branching on a constant, but not any of the cases, go to the default
206 // successor.
207 TheOnlyDest = SI->getDefaultDest();
208 }
209
210 // If we found a single destination that we can fold the switch into, do so
211 // now.
212 if (TheOnlyDest) {
213 // Insert the new branch..
214 new BranchInst(TheOnlyDest, SI);
215 BasicBlock *BB = SI->getParent();
216
217 // Remove entries from PHI nodes which we no longer branch to...
218 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
219 // Found case matching a constant operand?
220 BasicBlock *Succ = SI->getSuccessor(i);
221 if (Succ == TheOnlyDest)
222 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
223 else
224 Succ->removePredecessor(BB);
225 }
226
227 // Delete the old switch...
228 BB->getInstList().erase(SI);
229 return true;
230 } else if (SI->getNumSuccessors() == 2) {
231 // Otherwise, we can fold this switch into a conditional branch
232 // instruction if it has only one non-default destination.
233 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
234 SI->getSuccessorValue(1), "cond", SI);
235 // Insert the new branch...
236 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
237
238 // Delete the old switch...
239 SI->getParent()->getInstList().erase(SI);
240 return true;
241 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000242 }
243 return false;
244}
245
Chris Lattner25b83902004-04-13 19:28:52 +0000246/// canConstantFoldCallTo - Return true if its even possible to fold a call to
247/// the specified function.
248bool llvm::canConstantFoldCallTo(Function *F) {
249 const std::string &Name = F->getName();
Chris Lattnercf110352004-06-11 06:16:23 +0000250
251 switch (F->getIntrinsicID()) {
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000252 case Intrinsic::isunordered: return true;
Chris Lattnercf110352004-06-11 06:16:23 +0000253 default: break;
254 }
255
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000256 return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000257 Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
Chris Lattner8dfe5702004-05-27 07:25:00 +0000258 Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000259}
260
261static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
262 const Type *Ty) {
263 errno = 0;
264 V = NativeFP(V);
265 if (errno == 0)
266 return ConstantFP::get(Ty, V);
267 return 0;
Chris Lattner25b83902004-04-13 19:28:52 +0000268}
269
270/// ConstantFoldCall - Attempt to constant fold a call to the specified function
271/// with the specified arguments, returning null if unsuccessful.
272Constant *llvm::ConstantFoldCall(Function *F,
273 const std::vector<Constant*> &Operands) {
274 const std::string &Name = F->getName();
275 const Type *Ty = F->getReturnType();
276
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000277 if (Operands.size() == 1) {
278 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
279 double V = Op->getValue();
Brian Gaeke83a70492004-06-15 23:09:50 +0000280 if (Name == "sin")
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000281 return ConstantFP::get(Ty, sin(V));
282 else if (Name == "cos")
283 return ConstantFP::get(Ty, cos(V));
284 else if (Name == "tan")
285 return ConstantFP::get(Ty, tan(V));
286 else if (Name == "sqrt" && V >= 0)
287 return ConstantFP::get(Ty, sqrt(V));
288 else if (Name == "exp")
289 return ConstantFP::get(Ty, exp(V));
290 else if (Name == "log" && V > 0)
291 return ConstantFP::get(Ty, log(V));
292 else if (Name == "log10")
293 return ConstantFoldFP(log10, V, Ty);
294 else if (Name == "acos")
295 return ConstantFoldFP(acos, V, Ty);
296 else if (Name == "asin")
297 return ConstantFoldFP(asin, V, Ty);
298 else if (Name == "atan")
299 return ConstantFP::get(Ty, atan(V));
300 }
301 } else if (Operands.size() == 2) {
302 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
303 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner8dfe5702004-05-27 07:25:00 +0000304 double Op1V = Op1->getValue(), Op2V = Op2->getValue();
305
Chris Lattner30c02f72004-06-21 06:17:21 +0000306#if 0
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000307 if (Name == "llvm.isunordered")
Chris Lattner5253f052004-06-17 21:20:52 +0000308 return ConstantBool::get(std::isnan(Op1V) | std::isnan(Op2V));
Chris Lattner30c02f72004-06-21 06:17:21 +0000309 else
310#endif
311 if (Name == "pow") {
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000312 errno = 0;
Chris Lattner8dfe5702004-05-27 07:25:00 +0000313 double V = pow(Op1V, Op2V);
314 if (errno == 0)
315 return ConstantFP::get(Ty, V);
316 } else if (Name == "fmod") {
317 errno = 0;
318 double V = fmod(Op1V, Op2V);
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000319 if (errno == 0)
320 return ConstantFP::get(Ty, V);
321 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000322 }
Chris Lattner25b83902004-04-13 19:28:52 +0000323 }
324 return 0;
325}
326
327
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000328
329
330//===----------------------------------------------------------------------===//
331// Local dead code elimination...
332//
333
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000334bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerf0a93ed2003-02-24 20:48:32 +0000335 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000336}
337
338// dceInstruction - Inspect the instruction at *BBI and figure out if it's
339// [trivially] dead. If so, remove the instruction and update the iterator
340// to point to the instruction that immediately succeeded the original
341// instruction.
342//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000343bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000344 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000345 if (isInstructionTriviallyDead(BBI)) {
346 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000347 return true;
348 }
349 return false;
350}
Brian Gaeked0fde302003-11-11 22:41:34 +0000351
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000352//===----------------------------------------------------------------------===//
353// PHI Instruction Simplification
354//
355
356/// hasConstantValue - If the specified PHI node always merges together the same
357/// value, return the value, otherwise return null.
358///
359Value *llvm::hasConstantValue(PHINode *PN) {
360 // If the PHI node only has one incoming value, eliminate the PHI node...
361 if (PN->getNumIncomingValues() == 1)
362 return PN->getIncomingValue(0);
363
364 // Otherwise if all of the incoming values are the same for the PHI, replace
365 // the PHI node with the incoming value.
366 //
367 Value *InVal = 0;
368 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
369 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
370 if (InVal && PN->getIncomingValue(i) != InVal)
371 return 0; // Not the same, bail out.
372 else
373 InVal = PN->getIncomingValue(i);
374
375 // The only case that could cause InVal to be null is if we have a PHI node
376 // that only has entries for itself. In this case, there is no entry into the
377 // loop, so kill the PHI.
378 //
379 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
380
381 // All of the incoming values are the same, return the value now.
382 return InVal;
383}