Comment out the isnan stuff until we get a proper autoconf test for it
[oota-llvm.git] / lib / Transforms / Utils / Local.cpp
1 //===-- Local.cpp - Functions to perform local transformations ------------===//
2 // 
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 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Intrinsics.h"
19 #include <cerrno>
20 #include <cmath>
21 using namespace llvm;
22
23 #if 0
24 #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.
29 extern "C" int isnan (double d);
30 namespace std { int isnan (double d) { return ::isnan (d); } }
31 #endif
32
33 #endif
34
35 //===----------------------------------------------------------------------===//
36 //  Local constant propagation...
37 //
38
39 /// doConstantPropagation - If an instruction references constants, try to fold
40 /// them together...
41 ///
42 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
43   if (Constant *C = ConstantFoldInstruction(II)) {
44     // Replaces all of the uses of a variable with uses of the constant.
45     II->replaceAllUsesWith(C);
46     
47     // Remove the instruction from the basic block...
48     II = II->getParent()->getInstList().erase(II);
49     return true;
50   }
51
52   return false;
53 }
54
55 /// 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 ///
60 Constant *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;
75   } 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;
87   }
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
102   if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
103     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());
109   case Instruction::Select:
110     if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
111       return ConstantExpr::getSelect(Op0, Op1, Op2);
112     return 0;
113   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
126 // ConstantFoldTerminator - If a terminator instruction is predicated on a
127 // constant value, convert it into an unconditional branch to the constant
128 // destination.
129 //
130 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
131   TerminatorInst *T = BB->getTerminator();
132       
133   // 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);
157       return true;
158     } else if (Dest2 == Dest1) {       // Conditional branch to same location?
159       // 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     }
171   } 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
176     BasicBlock *DefaultDest = TheOnlyDest;
177     assert(TheOnlyDest == SI->getDefaultDest() &&
178            "Default destination is not successor #0?");
179
180     // 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       }
187
188       // 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
198       // 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;
202     }
203
204     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     }
242   }
243   return false;
244 }
245
246 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
247 /// the specified function.
248 bool llvm::canConstantFoldCallTo(Function *F) {
249   const std::string &Name = F->getName();
250
251   switch (F->getIntrinsicID()) {
252   case Intrinsic::isunordered: return true;
253   default: break;
254   }
255
256   return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
257          Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
258          Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
259 }
260
261 static 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;
268 }
269
270 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
271 /// with the specified arguments, returning null if unsuccessful.
272 Constant *llvm::ConstantFoldCall(Function *F,
273                                  const std::vector<Constant*> &Operands) {
274   const std::string &Name = F->getName();
275   const Type *Ty = F->getReturnType();
276
277   if (Operands.size() == 1) {
278     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
279       double V = Op->getValue();
280       if (Name == "sin")
281         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])) {
304         double Op1V = Op1->getValue(), Op2V = Op2->getValue();
305
306 #if 0
307         if (Name == "llvm.isunordered")
308           return ConstantBool::get(std::isnan(Op1V) | std::isnan(Op2V));
309         else 
310 #endif
311         if (Name == "pow") {
312           errno = 0;
313           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);
319           if (errno == 0)
320             return ConstantFP::get(Ty, V);
321         }
322       }
323   }
324   return 0;
325 }
326
327
328
329
330 //===----------------------------------------------------------------------===//
331 //  Local dead code elimination...
332 //
333
334 bool llvm::isInstructionTriviallyDead(Instruction *I) {
335   return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
336 }
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 //
343 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
344   // Look for un"used" definitions...
345   if (isInstructionTriviallyDead(BBI)) {
346     BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
347     return true;
348   }
349   return false;
350 }
351
352 //===----------------------------------------------------------------------===//
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 ///
359 Value *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 }