8c398462d408556b84b947853bfe64f42e03e903
[oota-llvm.git] / lib / Analysis / ConstantFolding.cpp
1 //===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
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 determines the possibility of performing constant
11 // folding.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 #include "llvm/Support/MathExtras.h"
26 #include <cerrno>
27 #include <cmath>
28 using namespace llvm;
29
30 //===----------------------------------------------------------------------===//
31 // Constant Folding internal helper functions
32 //===----------------------------------------------------------------------===//
33
34 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
35 /// from a global, return the global and the constant.  Because of
36 /// constantexprs, this function is recursive.
37 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
38                                        int64_t &Offset, const TargetData &TD) {
39   // Trivial case, constant is the global.
40   if ((GV = dyn_cast<GlobalValue>(C))) {
41     Offset = 0;
42     return true;
43   }
44   
45   // Otherwise, if this isn't a constant expr, bail out.
46   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
47   if (!CE) return false;
48   
49   // Look through ptr->int and ptr->ptr casts.
50   if (CE->getOpcode() == Instruction::PtrToInt ||
51       CE->getOpcode() == Instruction::BitCast)
52     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
53   
54   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)    
55   if (CE->getOpcode() == Instruction::GetElementPtr) {
56     // Cannot compute this if the element type of the pointer is missing size
57     // info.
58     if (!cast<PointerType>(CE->getOperand(0)->getType())
59                  ->getElementType()->isSized())
60       return false;
61     
62     // If the base isn't a global+constant, we aren't either.
63     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
64       return false;
65     
66     // Otherwise, add any offset that our operands provide.
67     gep_type_iterator GTI = gep_type_begin(CE);
68     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i, ++GTI) {
69       ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(i));
70       if (!CI) return false;  // Index isn't a simple constant?
71       if (CI->getZExtValue() == 0) continue;  // Not adding anything.
72       
73       if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
74         // N = N + Offset
75         Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
76       } else {
77         const SequentialType *SQT = cast<SequentialType>(*GTI);
78         Offset += TD.getABITypeSize(SQT->getElementType())*CI->getSExtValue();
79       }
80     }
81     return true;
82   }
83   
84   return false;
85 }
86
87
88 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
89 /// Attempt to symbolically evaluate the result of  a binary operator merging
90 /// these together.  If target data info is available, it is provided as TD, 
91 /// otherwise TD is null.
92 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
93                                            Constant *Op1, const TargetData *TD){
94   // SROA
95   
96   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
97   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
98   // bits.
99   
100   
101   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
102   // constant.  This happens frequently when iterating over a global array.
103   if (Opc == Instruction::Sub && TD) {
104     GlobalValue *GV1, *GV2;
105     int64_t Offs1, Offs2;
106     
107     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
108       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
109           GV1 == GV2) {
110         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
111         return ConstantInt::get(Op0->getType(), Offs1-Offs2);
112       }
113   }
114     
115   // TODO: Fold icmp setne/seteq as well.
116   return 0;
117 }
118
119 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
120 /// constant expression, do so.
121 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
122                                          const Type *ResultTy,
123                                          const TargetData *TD) {
124   Constant *Ptr = Ops[0];
125   if (!cast<PointerType>(Ptr->getType())->getElementType()->isSized())
126     return 0;
127   
128   if (TD && Ptr->isNullValue()) {
129     // If this is a constant expr gep that is effectively computing an
130     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
131     bool isFoldableGEP = true;
132     for (unsigned i = 1; i != NumOps; ++i)
133       if (!isa<ConstantInt>(Ops[i])) {
134         isFoldableGEP = false;
135         break;
136       }
137     if (isFoldableGEP) {
138       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
139                                              (Value**)Ops+1, NumOps-1);
140       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
141       return ConstantExpr::getIntToPtr(C, ResultTy);
142     }
143   }
144   
145   return 0;
146 }
147
148
149 //===----------------------------------------------------------------------===//
150 // Constant Folding public APIs
151 //===----------------------------------------------------------------------===//
152
153
154 /// ConstantFoldInstruction - Attempt to constant fold the specified
155 /// instruction.  If successful, the constant result is returned, if not, null
156 /// is returned.  Note that this function can only fail when attempting to fold
157 /// instructions like loads and stores, which have no constant expression form.
158 ///
159 Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
160   if (PHINode *PN = dyn_cast<PHINode>(I)) {
161     if (PN->getNumIncomingValues() == 0)
162       return Constant::getNullValue(PN->getType());
163
164     Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
165     if (Result == 0) return 0;
166
167     // Handle PHI nodes specially here...
168     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
169       if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
170         return 0;   // Not all the same incoming constants...
171
172     // If we reach here, all incoming values are the same constant.
173     return Result;
174   }
175
176   // Scan the operand list, checking to see if they are all constants, if so,
177   // hand off to ConstantFoldInstOperands.
178   SmallVector<Constant*, 8> Ops;
179   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
180     if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
181       Ops.push_back(Op);
182     else
183       return 0;  // All operands not constant!
184
185   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
186     return ConstantFoldCompareInstOperands(CI->getPredicate(),
187                                            &Ops[0], Ops.size(), TD);
188   else
189     return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
190                                     &Ops[0], Ops.size(), TD);
191 }
192
193 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
194 /// specified opcode and operands.  If successful, the constant result is
195 /// returned, if not, null is returned.  Note that this function can fail when
196 /// attempting to fold instructions like loads and stores, which have no
197 /// constant expression form.
198 ///
199 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy, 
200                                          Constant* const* Ops, unsigned NumOps,
201                                          const TargetData *TD) {
202   // Handle easy binops first.
203   if (Instruction::isBinaryOp(Opcode)) {
204     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
205       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
206         return C;
207     
208     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
209   }
210   
211   switch (Opcode) {
212   default: return 0;
213   case Instruction::Call:
214     if (Function *F = dyn_cast<Function>(Ops[0]))
215       if (canConstantFoldCallTo(F))
216         return ConstantFoldCall(F, Ops+1, NumOps-1);
217     return 0;
218   case Instruction::ICmp:
219   case Instruction::FCmp:
220     assert(0 &&"This function is invalid for compares: no predicate specified");
221   case Instruction::PtrToInt:
222     // If the input is a inttoptr, eliminate the pair.  This requires knowing
223     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
224     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
225       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
226         Constant *Input = CE->getOperand(0);
227         unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
228         Constant *Mask = 
229           ConstantInt::get(APInt::getLowBitsSet(InWidth,
230                                                 TD->getPointerSizeInBits()));
231         Input = ConstantExpr::getAnd(Input, Mask);
232         // Do a zext or trunc to get to the dest size.
233         return ConstantExpr::getIntegerCast(Input, DestTy, false);
234       }
235     }
236     // FALL THROUGH.
237   case Instruction::IntToPtr:
238   case Instruction::Trunc:
239   case Instruction::ZExt:
240   case Instruction::SExt:
241   case Instruction::FPTrunc:
242   case Instruction::FPExt:
243   case Instruction::UIToFP:
244   case Instruction::SIToFP:
245   case Instruction::FPToUI:
246   case Instruction::FPToSI:
247   case Instruction::BitCast:
248     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
249   case Instruction::Select:
250     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
251   case Instruction::ExtractElement:
252     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
253   case Instruction::InsertElement:
254     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
255   case Instruction::ShuffleVector:
256     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
257   case Instruction::GetElementPtr:
258     if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
259       return C;
260     
261     return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
262   }
263 }
264
265 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
266 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
267 /// returns a constant expression of the specified operands.
268 ///
269 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
270                                                 Constant*const * Ops, 
271                                                 unsigned NumOps,
272                                                 const TargetData *TD) {
273   // fold: icmp (inttoptr x), null         -> icmp x, 0
274   // fold: icmp (ptrtoint x), 0            -> icmp x, null
275   // fold: icmp (inttoptr x), (inttoptr y) -> icmp x, y
276   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
277   //
278   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
279   // around to know if bit truncation is happening.
280   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
281     if (TD && Ops[1]->isNullValue()) {
282       const Type *IntPtrTy = TD->getIntPtrType();
283       if (CE0->getOpcode() == Instruction::IntToPtr) {
284         // Convert the integer value to the right size to ensure we get the
285         // proper extension or truncation.
286         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
287                                                    IntPtrTy, false);
288         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
289         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
290       }
291       
292       // Only do this transformation if the int is intptrty in size, otherwise
293       // there is a truncation or extension that we aren't modeling.
294       if (CE0->getOpcode() == Instruction::PtrToInt && 
295           CE0->getType() == IntPtrTy) {
296         Constant *C = CE0->getOperand(0);
297         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
298         // FIXME!
299         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
300       }
301     }
302     
303     if (TD && isa<ConstantExpr>(Ops[1]) &&
304         cast<ConstantExpr>(Ops[1])->getOpcode() == CE0->getOpcode()) {
305       const Type *IntPtrTy = TD->getIntPtrType();
306       // Only do this transformation if the int is intptrty in size, otherwise
307       // there is a truncation or extension that we aren't modeling.
308       if ((CE0->getOpcode() == Instruction::IntToPtr &&
309            CE0->getOperand(0)->getType() == IntPtrTy &&
310            CE0->getOperand(1)->getType() == IntPtrTy) ||
311           (CE0->getOpcode() == Instruction::PtrToInt &&
312            CE0->getType() == IntPtrTy &&
313            CE0->getOperand(0)->getType() == CE0->getOperand(1)->getType())) {
314         Constant *NewOps[] = { 
315           CE0->getOperand(0), cast<ConstantExpr>(Ops[1])->getOperand(0) 
316         };
317         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
318       }
319     }
320   }
321   return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]); 
322 }
323
324
325 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
326 /// getelementptr constantexpr, return the constant value being addressed by the
327 /// constant expression, or null if something is funny and we can't decide.
328 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
329                                                        ConstantExpr *CE) {
330   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
331     return 0;  // Do not allow stepping over the value!
332   
333   // Loop over all of the operands, tracking down which value we are
334   // addressing...
335   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
336   for (++I; I != E; ++I)
337     if (const StructType *STy = dyn_cast<StructType>(*I)) {
338       ConstantInt *CU = cast<ConstantInt>(I.getOperand());
339       assert(CU->getZExtValue() < STy->getNumElements() &&
340              "Struct index out of range!");
341       unsigned El = (unsigned)CU->getZExtValue();
342       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
343         C = CS->getOperand(El);
344       } else if (isa<ConstantAggregateZero>(C)) {
345         C = Constant::getNullValue(STy->getElementType(El));
346       } else if (isa<UndefValue>(C)) {
347         C = UndefValue::get(STy->getElementType(El));
348       } else {
349         return 0;
350       }
351     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
352       if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
353         if (CI->getZExtValue() >= ATy->getNumElements())
354          return 0;
355         if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
356           C = CA->getOperand(CI->getZExtValue());
357         else if (isa<ConstantAggregateZero>(C))
358           C = Constant::getNullValue(ATy->getElementType());
359         else if (isa<UndefValue>(C))
360           C = UndefValue::get(ATy->getElementType());
361         else
362           return 0;
363       } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
364         if (CI->getZExtValue() >= PTy->getNumElements())
365           return 0;
366         if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
367           C = CP->getOperand(CI->getZExtValue());
368         else if (isa<ConstantAggregateZero>(C))
369           C = Constant::getNullValue(PTy->getElementType());
370         else if (isa<UndefValue>(C))
371           C = UndefValue::get(PTy->getElementType());
372         else
373           return 0;
374       } else {
375         return 0;
376       }
377     } else {
378       return 0;
379     }
380   return C;
381 }
382
383
384 //===----------------------------------------------------------------------===//
385 //  Constant Folding for Calls
386 //
387
388 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
389 /// the specified function.
390 bool
391 llvm::canConstantFoldCallTo(Function *F) {
392   switch (F->getIntrinsicID()) {
393   case Intrinsic::sqrt:
394   case Intrinsic::powi:
395   case Intrinsic::bswap:
396   case Intrinsic::ctpop:
397   case Intrinsic::ctlz:
398   case Intrinsic::cttz:
399     return true;
400   default: break;
401   }
402
403   const ValueName *NameVal = F->getValueName();
404   if (NameVal == 0) return false;
405   const char *Str = NameVal->getKeyData();
406   unsigned Len = NameVal->getKeyLength();
407   
408   // In these cases, the check of the length is required.  We don't want to
409   // return true for a name like "cos\0blah" which strcmp would return equal to
410   // "cos", but has length 8.
411   switch (Str[0]) {
412   default: return false;
413   case 'a':
414     if (Len == 4)
415       return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
416              !strcmp(Str, "atan");
417     else if (Len == 5)
418       return !strcmp(Str, "atan2");
419     return false;
420   case 'c':
421     if (Len == 3)
422       return !strcmp(Str, "cos");
423     else if (Len == 4)
424       return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
425              !strcmp(Str, "cosh");
426     return false;
427   case 'e':
428     if (Len == 3)
429       return !strcmp(Str, "exp");
430     return false;
431   case 'f':
432     if (Len == 4)
433       return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
434     else if (Len == 5)
435       return !strcmp(Str, "floor");
436     return false;
437     break;
438   case 'l':
439     if (Len == 3 && !strcmp(Str, "log"))
440       return true;
441     if (Len == 5 && !strcmp(Str, "log10"))
442       return true;
443     return false;
444   case 'p':
445     if (Len == 3 && !strcmp(Str, "pow"))
446       return true;
447     return false;
448   case 's':
449     if (Len == 3)
450       return !strcmp(Str, "sin");
451     if (Len == 4)
452       return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt");
453     if (Len == 5)
454       return !strcmp(Str, "sqrtf");
455     return false;
456   case 't':
457     if (Len == 3 && !strcmp(Str, "tan"))
458       return true;
459     else if (Len == 4 && !strcmp(Str, "tanh"))
460       return true;
461     return false;
462   }
463 }
464
465 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, 
466                                 const Type *Ty) {
467   errno = 0;
468   V = NativeFP(V);
469   if (errno == 0) {
470     if (Ty==Type::FloatTy)
471       return ConstantFP::get(Ty, APFloat((float)V));
472     else if (Ty==Type::DoubleTy)
473       return ConstantFP::get(Ty, APFloat(V));
474     else
475       assert(0);
476   }
477   errno = 0;
478   return 0;
479 }
480
481 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
482                                       double V, double W,
483                                       const Type *Ty) {
484   errno = 0;
485   V = NativeFP(V, W);
486   if (errno == 0) {
487     if (Ty==Type::FloatTy)
488       return ConstantFP::get(Ty, APFloat((float)V));
489     else if (Ty==Type::DoubleTy)
490       return ConstantFP::get(Ty, APFloat(V));
491     else
492       assert(0);
493   }
494   errno = 0;
495   return 0;
496 }
497
498 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
499 /// with the specified arguments, returning null if unsuccessful.
500
501 Constant *
502 llvm::ConstantFoldCall(Function *F, 
503                        Constant* const* Operands, unsigned NumOperands) {
504   const ValueName *NameVal = F->getValueName();
505   if (NameVal == 0) return 0;
506   const char *Str = NameVal->getKeyData();
507   unsigned Len = NameVal->getKeyLength();
508   
509   const Type *Ty = F->getReturnType();
510   if (NumOperands == 1) {
511     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
512       if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
513         return 0;
514       /// Currently APFloat versions of these functions do not exist, so we use
515       /// the host native double versions.  Float versions are not called
516       /// directly but for all these it is true (float)(f((double)arg)) ==
517       /// f(arg).  Long double not supported yet.
518       double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
519                                      Op->getValueAPF().convertToDouble();
520       switch (Str[0]) {
521       case 'a':
522         if (Len == 4 && !strcmp(Str, "acos"))
523           return ConstantFoldFP(acos, V, Ty);
524         else if (Len == 4 && !strcmp(Str, "asin"))
525           return ConstantFoldFP(asin, V, Ty);
526         else if (Len == 4 && !strcmp(Str, "atan"))
527           return ConstantFoldFP(atan, V, Ty);
528         break;
529       case 'c':
530         if (Len == 4 && !strcmp(Str, "ceil"))
531           return ConstantFoldFP(ceil, V, Ty);
532         else if (Len == 3 && !strcmp(Str, "cos"))
533           return ConstantFoldFP(cos, V, Ty);
534         else if (Len == 4 && !strcmp(Str, "cosh"))
535           return ConstantFoldFP(cosh, V, Ty);
536         break;
537       case 'e':
538         if (Len == 3 && !strcmp(Str, "exp"))
539           return ConstantFoldFP(exp, V, Ty);
540         break;
541       case 'f':
542         if (Len == 4 && !strcmp(Str, "fabs"))
543           return ConstantFoldFP(fabs, V, Ty);
544         else if (Len == 5 && !strcmp(Str, "floor"))
545           return ConstantFoldFP(floor, V, Ty);
546         break;
547       case 'l':
548         if (Len == 3 && !strcmp(Str, "log") && V > 0)
549           return ConstantFoldFP(log, V, Ty);
550         else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
551           return ConstantFoldFP(log10, V, Ty);
552         else if (!strcmp(Str, "llvm.sqrt.f32") ||
553                  !strcmp(Str, "llvm.sqrt.f64")) {
554           if (V >= -0.0)
555             return ConstantFoldFP(sqrt, V, Ty);
556           else // Undefined
557             return ConstantFP::get(Ty, Ty==Type::FloatTy ? APFloat(0.0f) :
558                                        APFloat(0.0));
559         }
560         break;
561       case 's':
562         if (Len == 3 && !strcmp(Str, "sin"))
563           return ConstantFoldFP(sin, V, Ty);
564         else if (Len == 4 && !strcmp(Str, "sinh"))
565           return ConstantFoldFP(sinh, V, Ty);
566         else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
567           return ConstantFoldFP(sqrt, V, Ty);
568         else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
569           return ConstantFoldFP(sqrt, V, Ty);
570         break;
571       case 't':
572         if (Len == 3 && !strcmp(Str, "tan"))
573           return ConstantFoldFP(tan, V, Ty);
574         else if (Len == 4 && !strcmp(Str, "tanh"))
575           return ConstantFoldFP(tanh, V, Ty);
576         break;
577       default:
578         break;
579       }
580     } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
581       if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
582         return ConstantInt::get(Op->getValue().byteSwap());
583       else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
584         return ConstantInt::get(Ty, Op->getValue().countPopulation());
585       else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
586         return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
587       else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
588         return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
589     }
590   } else if (NumOperands == 2) {
591     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
592       if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
593         return 0;
594       double Op1V = Ty==Type::FloatTy ? 
595                       (double)Op1->getValueAPF().convertToFloat():
596                       Op1->getValueAPF().convertToDouble();
597       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
598         double Op2V = Ty==Type::FloatTy ? 
599                       (double)Op2->getValueAPF().convertToFloat():
600                       Op2->getValueAPF().convertToDouble();
601
602         if (Len == 3 && !strcmp(Str, "pow")) {
603           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
604         } else if (Len == 4 && !strcmp(Str, "fmod")) {
605           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
606         } else if (Len == 5 && !strcmp(Str, "atan2")) {
607           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
608         }
609       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
610         if (!strcmp(Str, "llvm.powi.f32")) {
611           return ConstantFP::get(Ty, APFloat((float)std::pow((float)Op1V,
612                                               (int)Op2C->getZExtValue())));
613         } else if (!strcmp(Str, "llvm.powi.f64")) {
614           return ConstantFP::get(Ty, APFloat((double)std::pow((double)Op1V,
615                                               (int)Op2C->getZExtValue())));
616         }
617       }
618     }
619   }
620   return 0;
621 }
622