7c99325b2dd1e8eaf3298181c146809d55a60965
[oota-llvm.git] / lib / Analysis / ConstantFolding.cpp
1 //===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/MathExtras.h"
27 #include <cerrno>
28 #include <cmath>
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 // Constant Folding internal helper functions
33 //===----------------------------------------------------------------------===//
34
35 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
36 /// from a global, return the global and the constant.  Because of
37 /// constantexprs, this function is recursive.
38 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
39                                        int64_t &Offset, const TargetData &TD) {
40   // Trivial case, constant is the global.
41   if ((GV = dyn_cast<GlobalValue>(C))) {
42     Offset = 0;
43     return true;
44   }
45   
46   // Otherwise, if this isn't a constant expr, bail out.
47   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
48   if (!CE) return false;
49   
50   // Look through ptr->int and ptr->ptr casts.
51   if (CE->getOpcode() == Instruction::PtrToInt ||
52       CE->getOpcode() == Instruction::BitCast)
53     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
54   
55   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)    
56   if (CE->getOpcode() == Instruction::GetElementPtr) {
57     // Cannot compute this if the element type of the pointer is missing size
58     // info.
59     if (!cast<PointerType>(CE->getOperand(0)->getType())
60                  ->getElementType()->isSized())
61       return false;
62     
63     // If the base isn't a global+constant, we aren't either.
64     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
65       return false;
66     
67     // Otherwise, add any offset that our operands provide.
68     gep_type_iterator GTI = gep_type_begin(CE);
69     for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
70          i != e; ++i, ++GTI) {
71       ConstantInt *CI = dyn_cast<ConstantInt>(*i);
72       if (!CI) return false;  // Index isn't a simple constant?
73       if (CI->getZExtValue() == 0) continue;  // Not adding anything.
74       
75       if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
76         // N = N + Offset
77         Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
78       } else {
79         const SequentialType *SQT = cast<SequentialType>(*GTI);
80         Offset += TD.getTypePaddedSize(SQT->getElementType())*CI->getSExtValue();
81       }
82     }
83     return true;
84   }
85   
86   return false;
87 }
88
89
90 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
91 /// Attempt to symbolically evaluate the result of a binary operator merging
92 /// these together.  If target data info is available, it is provided as TD, 
93 /// otherwise TD is null.
94 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
95                                            Constant *Op1, const TargetData *TD){
96   // SROA
97   
98   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
99   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
100   // bits.
101   
102   
103   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
104   // constant.  This happens frequently when iterating over a global array.
105   if (Opc == Instruction::Sub && TD) {
106     GlobalValue *GV1, *GV2;
107     int64_t Offs1, Offs2;
108     
109     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
110       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
111           GV1 == GV2) {
112         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
113         return ConstantInt::get(Op0->getType(), Offs1-Offs2);
114       }
115   }
116     
117   return 0;
118 }
119
120 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
121 /// constant expression, do so.
122 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
123                                          const Type *ResultTy,
124                                          const TargetData *TD) {
125   Constant *Ptr = Ops[0];
126   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
127     return 0;
128   
129   uint64_t BasePtr = 0;
130   if (!Ptr->isNullValue()) {
131     // If this is a inttoptr from a constant int, we can fold this as the base,
132     // otherwise we can't.
133     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
134       if (CE->getOpcode() == Instruction::IntToPtr)
135         if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
136           BasePtr = Base->getZExtValue();
137     
138     if (BasePtr == 0)
139       return 0;
140   }
141
142   // If this is a constant expr gep that is effectively computing an
143   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
144   for (unsigned i = 1; i != NumOps; ++i)
145     if (!isa<ConstantInt>(Ops[i]))
146       return false;
147   
148   uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
149                                          (Value**)Ops+1, NumOps-1);
150   Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset+BasePtr);
151   return ConstantExpr::getIntToPtr(C, ResultTy);
152 }
153
154 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with 
155 /// targetdata.  Return 0 if unfoldable.
156 static Constant *FoldBitCast(Constant *C, const Type *DestTy,
157                              const TargetData &TD) {
158   // If this is a bitcast from constant vector -> vector, fold it.
159   if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
160     if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
161       // If the element types match, VMCore can fold it.
162       unsigned NumDstElt = DestVTy->getNumElements();
163       unsigned NumSrcElt = CV->getNumOperands();
164       if (NumDstElt == NumSrcElt)
165         return 0;
166       
167       const Type *SrcEltTy = CV->getType()->getElementType();
168       const Type *DstEltTy = DestVTy->getElementType();
169       
170       // Otherwise, we're changing the number of elements in a vector, which 
171       // requires endianness information to do the right thing.  For example,
172       //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
173       // folds to (little endian):
174       //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
175       // and to (big endian):
176       //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
177       
178       // First thing is first.  We only want to think about integer here, so if
179       // we have something in FP form, recast it as integer.
180       if (DstEltTy->isFloatingPoint()) {
181         // Fold to an vector of integers with same size as our FP type.
182         unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
183         const Type *DestIVTy = VectorType::get(IntegerType::get(FPWidth),
184                                                NumDstElt);
185         // Recursively handle this integer conversion, if possible.
186         C = FoldBitCast(C, DestIVTy, TD);
187         if (!C) return 0;
188         
189         // Finally, VMCore can handle this now that #elts line up.
190         return ConstantExpr::getBitCast(C, DestTy);
191       }
192       
193       // Okay, we know the destination is integer, if the input is FP, convert
194       // it to integer first.
195       if (SrcEltTy->isFloatingPoint()) {
196         unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
197         const Type *SrcIVTy = VectorType::get(IntegerType::get(FPWidth),
198                                               NumSrcElt);
199         // Ask VMCore to do the conversion now that #elts line up.
200         C = ConstantExpr::getBitCast(C, SrcIVTy);
201         CV = dyn_cast<ConstantVector>(C);
202         if (!CV) return 0;  // If VMCore wasn't able to fold it, bail out.
203       }
204       
205       // Now we know that the input and output vectors are both integer vectors
206       // of the same size, and that their #elements is not the same.  Do the
207       // conversion here, which depends on whether the input or output has
208       // more elements.
209       bool isLittleEndian = TD.isLittleEndian();
210       
211       SmallVector<Constant*, 32> Result;
212       if (NumDstElt < NumSrcElt) {
213         // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
214         Constant *Zero = Constant::getNullValue(DstEltTy);
215         unsigned Ratio = NumSrcElt/NumDstElt;
216         unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
217         unsigned SrcElt = 0;
218         for (unsigned i = 0; i != NumDstElt; ++i) {
219           // Build each element of the result.
220           Constant *Elt = Zero;
221           unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
222           for (unsigned j = 0; j != Ratio; ++j) {
223             Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
224             if (!Src) return 0;  // Reject constantexpr elements.
225             
226             // Zero extend the element to the right size.
227             Src = ConstantExpr::getZExt(Src, Elt->getType());
228             
229             // Shift it to the right place, depending on endianness.
230             Src = ConstantExpr::getShl(Src, 
231                                     ConstantInt::get(Src->getType(), ShiftAmt));
232             ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
233             
234             // Mix it in.
235             Elt = ConstantExpr::getOr(Elt, Src);
236           }
237           Result.push_back(Elt);
238         }
239       } else {
240         // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
241         unsigned Ratio = NumDstElt/NumSrcElt;
242         unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
243         
244         // Loop over each source value, expanding into multiple results.
245         for (unsigned i = 0; i != NumSrcElt; ++i) {
246           Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
247           if (!Src) return 0;  // Reject constantexpr elements.
248
249           unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
250           for (unsigned j = 0; j != Ratio; ++j) {
251             // Shift the piece of the value into the right place, depending on
252             // endianness.
253             Constant *Elt = ConstantExpr::getLShr(Src, 
254                                 ConstantInt::get(Src->getType(), ShiftAmt));
255             ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
256
257             // Truncate and remember this piece.
258             Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
259           }
260         }
261       }
262       
263       return ConstantVector::get(&Result[0], Result.size());
264     }
265   }
266   
267   return 0;
268 }
269
270
271 //===----------------------------------------------------------------------===//
272 // Constant Folding public APIs
273 //===----------------------------------------------------------------------===//
274
275
276 /// ConstantFoldInstruction - Attempt to constant fold the specified
277 /// instruction.  If successful, the constant result is returned, if not, null
278 /// is returned.  Note that this function can only fail when attempting to fold
279 /// instructions like loads and stores, which have no constant expression form.
280 ///
281 Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
282   if (PHINode *PN = dyn_cast<PHINode>(I)) {
283     if (PN->getNumIncomingValues() == 0)
284       return UndefValue::get(PN->getType());
285
286     Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
287     if (Result == 0) return 0;
288
289     // Handle PHI nodes specially here...
290     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
291       if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
292         return 0;   // Not all the same incoming constants...
293
294     // If we reach here, all incoming values are the same constant.
295     return Result;
296   }
297
298   // Scan the operand list, checking to see if they are all constants, if so,
299   // hand off to ConstantFoldInstOperands.
300   SmallVector<Constant*, 8> Ops;
301   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
302     if (Constant *Op = dyn_cast<Constant>(*i))
303       Ops.push_back(Op);
304     else
305       return 0;  // All operands not constant!
306
307   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
308     return ConstantFoldCompareInstOperands(CI->getPredicate(),
309                                            &Ops[0], Ops.size(), TD);
310   else
311     return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
312                                     &Ops[0], Ops.size(), TD);
313 }
314
315 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
316 /// using the specified TargetData.  If successful, the constant result is
317 /// result is returned, if not, null is returned.
318 Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
319                                                const TargetData *TD) {
320   assert(TD && "ConstantFoldConstantExpression requires a valid TargetData.");
321
322   SmallVector<Constant*, 8> Ops;
323   for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
324     Ops.push_back(cast<Constant>(*i));
325
326   if (CE->isCompare())
327     return ConstantFoldCompareInstOperands(CE->getPredicate(),
328                                            &Ops[0], Ops.size(), TD);
329   else 
330     return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
331                                     &Ops[0], Ops.size(), TD);
332 }
333
334 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
335 /// specified opcode and operands.  If successful, the constant result is
336 /// returned, if not, null is returned.  Note that this function can fail when
337 /// attempting to fold instructions like loads and stores, which have no
338 /// constant expression form.
339 ///
340 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy, 
341                                          Constant* const* Ops, unsigned NumOps,
342                                          const TargetData *TD) {
343   // Handle easy binops first.
344   if (Instruction::isBinaryOp(Opcode)) {
345     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
346       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
347         return C;
348     
349     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
350   }
351   
352   switch (Opcode) {
353   default: return 0;
354   case Instruction::Call:
355     if (Function *F = dyn_cast<Function>(Ops[0]))
356       if (canConstantFoldCallTo(F))
357         return ConstantFoldCall(F, Ops+1, NumOps-1);
358     return 0;
359   case Instruction::ICmp:
360   case Instruction::FCmp:
361   case Instruction::VICmp:
362   case Instruction::VFCmp:
363     assert(0 &&"This function is invalid for compares: no predicate specified");
364   case Instruction::PtrToInt:
365     // If the input is a inttoptr, eliminate the pair.  This requires knowing
366     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
367     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
368       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
369         Constant *Input = CE->getOperand(0);
370         unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
371         if (TD->getPointerSizeInBits() < InWidth) {
372           Constant *Mask = 
373             ConstantInt::get(APInt::getLowBitsSet(InWidth,
374                                                   TD->getPointerSizeInBits()));
375           Input = ConstantExpr::getAnd(Input, Mask);
376         }
377         // Do a zext or trunc to get to the dest size.
378         return ConstantExpr::getIntegerCast(Input, DestTy, false);
379       }
380     }
381     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
382   case Instruction::IntToPtr:
383     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
384     // the int size is >= the ptr size.  This requires knowing the width of a
385     // pointer, so it can't be done in ConstantExpr::getCast.
386     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
387       if (TD &&
388           TD->getPointerSizeInBits() <=
389           CE->getType()->getPrimitiveSizeInBits()) {
390         if (CE->getOpcode() == Instruction::PtrToInt) {
391           Constant *Input = CE->getOperand(0);
392           Constant *C = FoldBitCast(Input, DestTy, *TD);
393           return C ? C : ConstantExpr::getBitCast(Input, DestTy);
394         }
395         // If there's a constant offset added to the integer value before
396         // it is casted back to a pointer, see if the expression can be
397         // converted into a GEP.
398         if (CE->getOpcode() == Instruction::Add)
399           if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
400             if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
401               if (R->getOpcode() == Instruction::PtrToInt)
402                 if (GlobalVariable *GV =
403                       dyn_cast<GlobalVariable>(R->getOperand(0))) {
404                   const PointerType *GVTy = cast<PointerType>(GV->getType());
405                   if (const ArrayType *AT =
406                         dyn_cast<ArrayType>(GVTy->getElementType())) {
407                     const Type *ElTy = AT->getElementType();
408                     uint64_t PaddedSize = TD->getTypePaddedSize(ElTy);
409                     APInt PSA(L->getValue().getBitWidth(), PaddedSize);
410                     if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
411                         L->getValue().urem(PSA) == 0) {
412                       APInt ElemIdx = L->getValue().udiv(PSA);
413                       if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
414                                             AT->getNumElements()))) {
415                         Constant *Index[] = {
416                           Constant::getNullValue(CE->getType()),
417                           ConstantInt::get(ElemIdx)
418                         };
419                         return ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
420                       }
421                     }
422                   }
423                 }
424       }
425     }
426     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
427   case Instruction::Trunc:
428   case Instruction::ZExt:
429   case Instruction::SExt:
430   case Instruction::FPTrunc:
431   case Instruction::FPExt:
432   case Instruction::UIToFP:
433   case Instruction::SIToFP:
434   case Instruction::FPToUI:
435   case Instruction::FPToSI:
436       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
437   case Instruction::BitCast:
438     if (TD)
439       if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD))
440         return C;
441     return ConstantExpr::getBitCast(Ops[0], DestTy);
442   case Instruction::Select:
443     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
444   case Instruction::ExtractElement:
445     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
446   case Instruction::InsertElement:
447     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
448   case Instruction::ShuffleVector:
449     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
450   case Instruction::GetElementPtr:
451     if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
452       return C;
453     
454     return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
455   }
456 }
457
458 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
459 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
460 /// returns a constant expression of the specified operands.
461 ///
462 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
463                                                 Constant*const * Ops, 
464                                                 unsigned NumOps,
465                                                 const TargetData *TD) {
466   // fold: icmp (inttoptr x), null         -> icmp x, 0
467   // fold: icmp (ptrtoint x), 0            -> icmp x, null
468   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
469   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
470   //
471   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
472   // around to know if bit truncation is happening.
473   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
474     if (TD && Ops[1]->isNullValue()) {
475       const Type *IntPtrTy = TD->getIntPtrType();
476       if (CE0->getOpcode() == Instruction::IntToPtr) {
477         // Convert the integer value to the right size to ensure we get the
478         // proper extension or truncation.
479         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
480                                                    IntPtrTy, false);
481         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
482         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
483       }
484       
485       // Only do this transformation if the int is intptrty in size, otherwise
486       // there is a truncation or extension that we aren't modeling.
487       if (CE0->getOpcode() == Instruction::PtrToInt && 
488           CE0->getType() == IntPtrTy) {
489         Constant *C = CE0->getOperand(0);
490         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
491         // FIXME!
492         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
493       }
494     }
495     
496     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
497       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
498         const Type *IntPtrTy = TD->getIntPtrType();
499
500         if (CE0->getOpcode() == Instruction::IntToPtr) {
501           // Convert the integer value to the right size to ensure we get the
502           // proper extension or truncation.
503           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
504                                                       IntPtrTy, false);
505           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
506                                                       IntPtrTy, false);
507           Constant *NewOps[] = { C0, C1 };
508           return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
509         }
510
511         // Only do this transformation if the int is intptrty in size, otherwise
512         // there is a truncation or extension that we aren't modeling.
513         if ((CE0->getOpcode() == Instruction::PtrToInt &&
514              CE0->getType() == IntPtrTy &&
515              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
516           Constant *NewOps[] = { 
517             CE0->getOperand(0), CE1->getOperand(0) 
518           };
519           return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
520         }
521       }
522     }
523   }
524   return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
525 }
526
527
528 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
529 /// getelementptr constantexpr, return the constant value being addressed by the
530 /// constant expression, or null if something is funny and we can't decide.
531 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
532                                                        ConstantExpr *CE) {
533   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
534     return 0;  // Do not allow stepping over the value!
535   
536   // Loop over all of the operands, tracking down which value we are
537   // addressing...
538   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
539   for (++I; I != E; ++I)
540     if (const StructType *STy = dyn_cast<StructType>(*I)) {
541       ConstantInt *CU = cast<ConstantInt>(I.getOperand());
542       assert(CU->getZExtValue() < STy->getNumElements() &&
543              "Struct index out of range!");
544       unsigned El = (unsigned)CU->getZExtValue();
545       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
546         C = CS->getOperand(El);
547       } else if (isa<ConstantAggregateZero>(C)) {
548         C = Constant::getNullValue(STy->getElementType(El));
549       } else if (isa<UndefValue>(C)) {
550         C = UndefValue::get(STy->getElementType(El));
551       } else {
552         return 0;
553       }
554     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
555       if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
556         if (CI->getZExtValue() >= ATy->getNumElements())
557          return 0;
558         if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
559           C = CA->getOperand(CI->getZExtValue());
560         else if (isa<ConstantAggregateZero>(C))
561           C = Constant::getNullValue(ATy->getElementType());
562         else if (isa<UndefValue>(C))
563           C = UndefValue::get(ATy->getElementType());
564         else
565           return 0;
566       } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
567         if (CI->getZExtValue() >= PTy->getNumElements())
568           return 0;
569         if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
570           C = CP->getOperand(CI->getZExtValue());
571         else if (isa<ConstantAggregateZero>(C))
572           C = Constant::getNullValue(PTy->getElementType());
573         else if (isa<UndefValue>(C))
574           C = UndefValue::get(PTy->getElementType());
575         else
576           return 0;
577       } else {
578         return 0;
579       }
580     } else {
581       return 0;
582     }
583   return C;
584 }
585
586
587 //===----------------------------------------------------------------------===//
588 //  Constant Folding for Calls
589 //
590
591 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
592 /// the specified function.
593 bool
594 llvm::canConstantFoldCallTo(const Function *F) {
595   switch (F->getIntrinsicID()) {
596   case Intrinsic::sqrt:
597   case Intrinsic::powi:
598   case Intrinsic::bswap:
599   case Intrinsic::ctpop:
600   case Intrinsic::ctlz:
601   case Intrinsic::cttz:
602     return true;
603   default: break;
604   }
605
606   if (!F->hasName()) return false;
607   const char *Str = F->getNameStart();
608   unsigned Len = F->getNameLen();
609   
610   // In these cases, the check of the length is required.  We don't want to
611   // return true for a name like "cos\0blah" which strcmp would return equal to
612   // "cos", but has length 8.
613   switch (Str[0]) {
614   default: return false;
615   case 'a':
616     if (Len == 4)
617       return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
618              !strcmp(Str, "atan");
619     else if (Len == 5)
620       return !strcmp(Str, "atan2");
621     return false;
622   case 'c':
623     if (Len == 3)
624       return !strcmp(Str, "cos");
625     else if (Len == 4)
626       return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
627              !strcmp(Str, "cosh");
628     return false;
629   case 'e':
630     if (Len == 3)
631       return !strcmp(Str, "exp");
632     return false;
633   case 'f':
634     if (Len == 4)
635       return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
636     else if (Len == 5)
637       return !strcmp(Str, "floor");
638     return false;
639     break;
640   case 'l':
641     if (Len == 3 && !strcmp(Str, "log"))
642       return true;
643     if (Len == 5 && !strcmp(Str, "log10"))
644       return true;
645     return false;
646   case 'p':
647     if (Len == 3 && !strcmp(Str, "pow"))
648       return true;
649     return false;
650   case 's':
651     if (Len == 3)
652       return !strcmp(Str, "sin");
653     if (Len == 4)
654       return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
655              !strcmp(Str, "sinf");
656     if (Len == 5)
657       return !strcmp(Str, "sqrtf");
658     return false;
659   case 't':
660     if (Len == 3 && !strcmp(Str, "tan"))
661       return true;
662     else if (Len == 4 && !strcmp(Str, "tanh"))
663       return true;
664     return false;
665   }
666 }
667
668 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, 
669                                 const Type *Ty) {
670   errno = 0;
671   V = NativeFP(V);
672   if (errno != 0) {
673     errno = 0;
674     return 0;
675   }
676   
677   if (Ty == Type::FloatTy)
678     return ConstantFP::get(APFloat((float)V));
679   if (Ty == Type::DoubleTy)
680     return ConstantFP::get(APFloat(V));
681   assert(0 && "Can only constant fold float/double");
682   return 0; // dummy return to suppress warning
683 }
684
685 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
686                                       double V, double W,
687                                       const Type *Ty) {
688   errno = 0;
689   V = NativeFP(V, W);
690   if (errno != 0) {
691     errno = 0;
692     return 0;
693   }
694   
695   if (Ty == Type::FloatTy)
696     return ConstantFP::get(APFloat((float)V));
697   if (Ty == Type::DoubleTy)
698     return ConstantFP::get(APFloat(V));
699   assert(0 && "Can only constant fold float/double");
700   return 0; // dummy return to suppress warning
701 }
702
703 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
704 /// with the specified arguments, returning null if unsuccessful.
705
706 Constant *
707 llvm::ConstantFoldCall(Function *F, 
708                        Constant* const* Operands, unsigned NumOperands) {
709   if (!F->hasName()) return 0;
710   const char *Str = F->getNameStart();
711   unsigned Len = F->getNameLen();
712   
713   const Type *Ty = F->getReturnType();
714   if (NumOperands == 1) {
715     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
716       if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
717         return 0;
718       /// Currently APFloat versions of these functions do not exist, so we use
719       /// the host native double versions.  Float versions are not called
720       /// directly but for all these it is true (float)(f((double)arg)) ==
721       /// f(arg).  Long double not supported yet.
722       double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
723                                      Op->getValueAPF().convertToDouble();
724       switch (Str[0]) {
725       case 'a':
726         if (Len == 4 && !strcmp(Str, "acos"))
727           return ConstantFoldFP(acos, V, Ty);
728         else if (Len == 4 && !strcmp(Str, "asin"))
729           return ConstantFoldFP(asin, V, Ty);
730         else if (Len == 4 && !strcmp(Str, "atan"))
731           return ConstantFoldFP(atan, V, Ty);
732         break;
733       case 'c':
734         if (Len == 4 && !strcmp(Str, "ceil"))
735           return ConstantFoldFP(ceil, V, Ty);
736         else if (Len == 3 && !strcmp(Str, "cos"))
737           return ConstantFoldFP(cos, V, Ty);
738         else if (Len == 4 && !strcmp(Str, "cosh"))
739           return ConstantFoldFP(cosh, V, Ty);
740         else if (Len == 4 && !strcmp(Str, "cosf"))
741           return ConstantFoldFP(cos, V, Ty);
742         break;
743       case 'e':
744         if (Len == 3 && !strcmp(Str, "exp"))
745           return ConstantFoldFP(exp, V, Ty);
746         break;
747       case 'f':
748         if (Len == 4 && !strcmp(Str, "fabs"))
749           return ConstantFoldFP(fabs, V, Ty);
750         else if (Len == 5 && !strcmp(Str, "floor"))
751           return ConstantFoldFP(floor, V, Ty);
752         break;
753       case 'l':
754         if (Len == 3 && !strcmp(Str, "log") && V > 0)
755           return ConstantFoldFP(log, V, Ty);
756         else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
757           return ConstantFoldFP(log10, V, Ty);
758         else if (!strcmp(Str, "llvm.sqrt.f32") ||
759                  !strcmp(Str, "llvm.sqrt.f64")) {
760           if (V >= -0.0)
761             return ConstantFoldFP(sqrt, V, Ty);
762           else // Undefined
763             return Constant::getNullValue(Ty);
764         }
765         break;
766       case 's':
767         if (Len == 3 && !strcmp(Str, "sin"))
768           return ConstantFoldFP(sin, V, Ty);
769         else if (Len == 4 && !strcmp(Str, "sinh"))
770           return ConstantFoldFP(sinh, V, Ty);
771         else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
772           return ConstantFoldFP(sqrt, V, Ty);
773         else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
774           return ConstantFoldFP(sqrt, V, Ty);
775         else if (Len == 4 && !strcmp(Str, "sinf"))
776           return ConstantFoldFP(sin, V, Ty);
777         break;
778       case 't':
779         if (Len == 3 && !strcmp(Str, "tan"))
780           return ConstantFoldFP(tan, V, Ty);
781         else if (Len == 4 && !strcmp(Str, "tanh"))
782           return ConstantFoldFP(tanh, V, Ty);
783         break;
784       default:
785         break;
786       }
787     } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
788       if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
789         return ConstantInt::get(Op->getValue().byteSwap());
790       else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
791         return ConstantInt::get(Ty, Op->getValue().countPopulation());
792       else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
793         return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
794       else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
795         return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
796     }
797   } else if (NumOperands == 2) {
798     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
799       if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
800         return 0;
801       double Op1V = Ty==Type::FloatTy ? 
802                       (double)Op1->getValueAPF().convertToFloat():
803                       Op1->getValueAPF().convertToDouble();
804       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
805         double Op2V = Ty==Type::FloatTy ? 
806                       (double)Op2->getValueAPF().convertToFloat():
807                       Op2->getValueAPF().convertToDouble();
808
809         if (Len == 3 && !strcmp(Str, "pow")) {
810           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
811         } else if (Len == 4 && !strcmp(Str, "fmod")) {
812           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
813         } else if (Len == 5 && !strcmp(Str, "atan2")) {
814           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
815         }
816       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
817         if (!strcmp(Str, "llvm.powi.f32")) {
818           return ConstantFP::get(APFloat((float)std::pow((float)Op1V,
819                                                  (int)Op2C->getZExtValue())));
820         } else if (!strcmp(Str, "llvm.powi.f64")) {
821           return ConstantFP::get(APFloat((double)std::pow((double)Op1V,
822                                                  (int)Op2C->getZExtValue())));
823         }
824       }
825     }
826   }
827   return 0;
828 }
829