1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Intrinsics.h"
23 #if defined(__POWERPC__) && defined(__APPLE_CC__)
24 // FIXME: Currently it seems that isnan didn't make its way into the Apple
25 // C++ headers, although it IS in the C headers (which confuses autoconf
26 // in a big way). This is a quick fix to get things compiling, until one of
27 // us has time to write a more complicated autoconf test.
28 extern "C" int isnan (double d);
29 namespace std { int isnan (double d) { return ::isnan (d); } }
32 //===----------------------------------------------------------------------===//
33 // Local constant propagation...
36 /// doConstantPropagation - If an instruction references constants, try to fold
39 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
40 if (Constant *C = ConstantFoldInstruction(II)) {
41 // Replaces all of the uses of a variable with uses of the constant.
42 II->replaceAllUsesWith(C);
44 // Remove the instruction from the basic block...
45 II = II->getParent()->getInstList().erase(II);
52 /// ConstantFoldInstruction - Attempt to constant fold the specified
53 /// instruction. If successful, the constant result is returned, if not, null
54 /// is returned. Note that this function can only fail when attempting to fold
55 /// instructions like loads and stores, which have no constant expression form.
57 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
58 if (PHINode *PN = dyn_cast<PHINode>(I)) {
59 if (PN->getNumIncomingValues() == 0)
60 return Constant::getNullValue(PN->getType());
62 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
63 if (Result == 0) return 0;
65 // Handle PHI nodes specially here...
66 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
67 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
68 return 0; // Not all the same incoming constants...
70 // If we reach here, all incoming values are the same constant.
72 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
73 if (Function *F = CI->getCalledFunction())
74 if (canConstantFoldCallTo(F)) {
75 std::vector<Constant*> Args;
76 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
77 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
81 return ConstantFoldCall(F, Args);
86 Constant *Op0 = 0, *Op1 = 0;
87 switch (I->getNumOperands()) {
90 Op1 = dyn_cast<Constant>(I->getOperand(1));
91 if (Op1 == 0) return 0; // Not a constant?, can't fold
93 Op0 = dyn_cast<Constant>(I->getOperand(0));
94 if (Op0 == 0) return 0; // Not a constant?, can't fold
99 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
100 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
102 switch (I->getOpcode()) {
104 case Instruction::Cast:
105 return ConstantExpr::getCast(Op0, I->getType());
106 case Instruction::Select:
107 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
108 return ConstantExpr::getSelect(Op0, Op1, Op2);
110 case Instruction::GetElementPtr:
111 std::vector<Constant*> IdxList;
112 IdxList.reserve(I->getNumOperands()-1);
113 if (Op1) IdxList.push_back(Op1);
114 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
115 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
116 IdxList.push_back(C);
118 return 0; // Non-constant operand
119 return ConstantExpr::getGetElementPtr(Op0, IdxList);
123 // ConstantFoldTerminator - If a terminator instruction is predicated on a
124 // constant value, convert it into an unconditional branch to the constant
127 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
128 TerminatorInst *T = BB->getTerminator();
130 // Branch - See if we are conditional jumping on constant
131 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
132 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
133 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
134 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
136 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
137 // Are we branching on constant?
138 // YES. Change to unconditional branch...
139 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
140 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
142 //cerr << "Function: " << T->getParent()->getParent()
143 // << "\nRemoving branch from " << T->getParent()
144 // << "\n\nTo: " << OldDest << endl;
146 // Let the basic block know that we are letting go of it. Based on this,
147 // it will adjust it's PHI nodes.
148 assert(BI->getParent() && "Terminator not inserted in block!");
149 OldDest->removePredecessor(BI->getParent());
151 // Set the unconditional destination, and change the insn to be an
152 // unconditional branch.
153 BI->setUnconditionalDest(Destination);
155 } else if (Dest2 == Dest1) { // Conditional branch to same location?
156 // This branch matches something like this:
157 // br bool %cond, label %Dest, label %Dest
158 // and changes it into: br label %Dest
160 // Let the basic block know that we are letting go of one copy of it.
161 assert(BI->getParent() && "Terminator not inserted in block!");
162 Dest1->removePredecessor(BI->getParent());
164 // Change a conditional branch to unconditional.
165 BI->setUnconditionalDest(Dest1);
168 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
169 // If we are switching on a constant, we can convert the switch into a
170 // single branch instruction!
171 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
172 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
173 BasicBlock *DefaultDest = TheOnlyDest;
174 assert(TheOnlyDest == SI->getDefaultDest() &&
175 "Default destination is not successor #0?");
177 // Figure out which case it goes to...
178 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
179 // Found case matching a constant operand?
180 if (SI->getSuccessorValue(i) == CI) {
181 TheOnlyDest = SI->getSuccessor(i);
185 // Check to see if this branch is going to the same place as the default
186 // dest. If so, eliminate it as an explicit compare.
187 if (SI->getSuccessor(i) == DefaultDest) {
188 // Remove this entry...
189 DefaultDest->removePredecessor(SI->getParent());
191 --i; --e; // Don't skip an entry...
195 // Otherwise, check to see if the switch only branches to one destination.
196 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
198 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
201 if (CI && !TheOnlyDest) {
202 // Branching on a constant, but not any of the cases, go to the default
204 TheOnlyDest = SI->getDefaultDest();
207 // If we found a single destination that we can fold the switch into, do so
210 // Insert the new branch..
211 new BranchInst(TheOnlyDest, SI);
212 BasicBlock *BB = SI->getParent();
214 // Remove entries from PHI nodes which we no longer branch to...
215 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
216 // Found case matching a constant operand?
217 BasicBlock *Succ = SI->getSuccessor(i);
218 if (Succ == TheOnlyDest)
219 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
221 Succ->removePredecessor(BB);
224 // Delete the old switch...
225 BB->getInstList().erase(SI);
227 } else if (SI->getNumSuccessors() == 2) {
228 // Otherwise, we can fold this switch into a conditional branch
229 // instruction if it has only one non-default destination.
230 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
231 SI->getSuccessorValue(1), "cond", SI);
232 // Insert the new branch...
233 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
235 // Delete the old switch...
236 SI->getParent()->getInstList().erase(SI);
243 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
244 /// the specified function.
245 bool llvm::canConstantFoldCallTo(Function *F) {
246 const std::string &Name = F->getName();
248 switch (F->getIntrinsicID()) {
249 case Intrinsic::isunordered: return true;
253 return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
254 Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
255 Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
258 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
263 return ConstantFP::get(Ty, V);
267 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
268 /// with the specified arguments, returning null if unsuccessful.
269 Constant *llvm::ConstantFoldCall(Function *F,
270 const std::vector<Constant*> &Operands) {
271 const std::string &Name = F->getName();
272 const Type *Ty = F->getReturnType();
274 if (Operands.size() == 1) {
275 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
276 double V = Op->getValue();
278 return ConstantFP::get(Ty, sin(V));
279 else if (Name == "cos")
280 return ConstantFP::get(Ty, cos(V));
281 else if (Name == "tan")
282 return ConstantFP::get(Ty, tan(V));
283 else if (Name == "sqrt" && V >= 0)
284 return ConstantFP::get(Ty, sqrt(V));
285 else if (Name == "exp")
286 return ConstantFP::get(Ty, exp(V));
287 else if (Name == "log" && V > 0)
288 return ConstantFP::get(Ty, log(V));
289 else if (Name == "log10")
290 return ConstantFoldFP(log10, V, Ty);
291 else if (Name == "acos")
292 return ConstantFoldFP(acos, V, Ty);
293 else if (Name == "asin")
294 return ConstantFoldFP(asin, V, Ty);
295 else if (Name == "atan")
296 return ConstantFP::get(Ty, atan(V));
298 } else if (Operands.size() == 2) {
299 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
300 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
301 double Op1V = Op1->getValue(), Op2V = Op2->getValue();
303 if (Name == "llvm.isunordered")
304 return ConstantBool::get(std::isnan(Op1V) | std::isnan(Op2V));
305 else if (Name == "pow") {
307 double V = pow(Op1V, Op2V);
309 return ConstantFP::get(Ty, V);
310 } else if (Name == "fmod") {
312 double V = fmod(Op1V, Op2V);
314 return ConstantFP::get(Ty, V);
324 //===----------------------------------------------------------------------===//
325 // Local dead code elimination...
328 bool llvm::isInstructionTriviallyDead(Instruction *I) {
329 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
332 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
333 // [trivially] dead. If so, remove the instruction and update the iterator
334 // to point to the instruction that immediately succeeded the original
337 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
338 // Look for un"used" definitions...
339 if (isInstructionTriviallyDead(BBI)) {
340 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
346 //===----------------------------------------------------------------------===//
347 // PHI Instruction Simplification
350 /// hasConstantValue - If the specified PHI node always merges together the same
351 /// value, return the value, otherwise return null.
353 Value *llvm::hasConstantValue(PHINode *PN) {
354 // If the PHI node only has one incoming value, eliminate the PHI node...
355 if (PN->getNumIncomingValues() == 1)
356 return PN->getIncomingValue(0);
358 // Otherwise if all of the incoming values are the same for the PHI, replace
359 // the PHI node with the incoming value.
362 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
363 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
364 if (InVal && PN->getIncomingValue(i) != InVal)
365 return 0; // Not the same, bail out.
367 InVal = PN->getIncomingValue(i);
369 // The only case that could cause InVal to be null is if we have a PHI node
370 // that only has entries for itself. In this case, there is no entry into the
371 // loop, so kill the PHI.
373 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
375 // All of the incoming values are the same, return the value now.