LLVM API Documentation

ConstantFolding.cpp

Go to the documentation of this file.
00001 //===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions determines the possibility of performing constant
00011 // folding.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Function.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Intrinsics.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/Target/TargetData.h"
00024 #include "llvm/Support/GetElementPtrTypeIterator.h"
00025 #include "llvm/Support/MathExtras.h"
00026 #include <cerrno>
00027 #include <cmath>
00028 using namespace llvm;
00029 
00030 //===----------------------------------------------------------------------===//
00031 // Constant Folding internal helper functions
00032 //===----------------------------------------------------------------------===//
00033 
00034 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
00035 /// from a global, return the global and the constant.  Because of
00036 /// constantexprs, this function is recursive.
00037 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
00038                                        int64_t &Offset, const TargetData &TD) {
00039   // Trivial case, constant is the global.
00040   if ((GV = dyn_cast<GlobalValue>(C))) {
00041     Offset = 0;
00042     return true;
00043   }
00044   
00045   // Otherwise, if this isn't a constant expr, bail out.
00046   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00047   if (!CE) return false;
00048   
00049   // Look through ptr->int and ptr->ptr casts.
00050   if (CE->getOpcode() == Instruction::PtrToInt ||
00051       CE->getOpcode() == Instruction::BitCast)
00052     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
00053   
00054   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)    
00055   if (CE->getOpcode() == Instruction::GetElementPtr) {
00056     // Cannot compute this if the element type of the pointer is missing size
00057     // info.
00058     if (!cast<PointerType>(CE->getOperand(0)->getType())
00059                  ->getElementType()->isSized())
00060       return false;
00061     
00062     // If the base isn't a global+constant, we aren't either.
00063     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
00064       return false;
00065     
00066     // Otherwise, add any offset that our operands provide.
00067     gep_type_iterator GTI = gep_type_begin(CE);
00068     for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
00069          i != e; ++i, ++GTI) {
00070       ConstantInt *CI = dyn_cast<ConstantInt>(*i);
00071       if (!CI) return false;  // Index isn't a simple constant?
00072       if (CI->getZExtValue() == 0) continue;  // Not adding anything.
00073       
00074       if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
00075         // N = N + Offset
00076         Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
00077       } else {
00078         const SequentialType *SQT = cast<SequentialType>(*GTI);
00079         Offset += TD.getTypePaddedSize(SQT->getElementType())*CI->getSExtValue();
00080       }
00081     }
00082     return true;
00083   }
00084   
00085   return false;
00086 }
00087 
00088 
00089 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
00090 /// Attempt to symbolically evaluate the result of a binary operator merging
00091 /// these together.  If target data info is available, it is provided as TD, 
00092 /// otherwise TD is null.
00093 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
00094                                            Constant *Op1, const TargetData *TD){
00095   // SROA
00096   
00097   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
00098   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
00099   // bits.
00100   
00101   
00102   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
00103   // constant.  This happens frequently when iterating over a global array.
00104   if (Opc == Instruction::Sub && TD) {
00105     GlobalValue *GV1, *GV2;
00106     int64_t Offs1, Offs2;
00107     
00108     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
00109       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
00110           GV1 == GV2) {
00111         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
00112         return ConstantInt::get(Op0->getType(), Offs1-Offs2);
00113       }
00114   }
00115     
00116   return 0;
00117 }
00118 
00119 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
00120 /// constant expression, do so.
00121 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
00122                                          const Type *ResultTy,
00123                                          const TargetData *TD) {
00124   Constant *Ptr = Ops[0];
00125   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
00126     return 0;
00127   
00128   uint64_t BasePtr = 0;
00129   if (!Ptr->isNullValue()) {
00130     // If this is a inttoptr from a constant int, we can fold this as the base,
00131     // otherwise we can't.
00132     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
00133       if (CE->getOpcode() == Instruction::IntToPtr)
00134         if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
00135           BasePtr = Base->getZExtValue();
00136     
00137     if (BasePtr == 0)
00138       return 0;
00139   }
00140 
00141   // If this is a constant expr gep that is effectively computing an
00142   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
00143   for (unsigned i = 1; i != NumOps; ++i)
00144     if (!isa<ConstantInt>(Ops[i]))
00145       return false;
00146   
00147   uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
00148                                          (Value**)Ops+1, NumOps-1);
00149   Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset+BasePtr);
00150   return ConstantExpr::getIntToPtr(C, ResultTy);
00151 }
00152 
00153 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with 
00154 /// targetdata.  Return 0 if unfoldable.
00155 static Constant *FoldBitCast(Constant *C, const Type *DestTy,
00156                              const TargetData &TD) {
00157   // If this is a bitcast from constant vector -> vector, fold it.
00158   if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
00159     if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
00160       // If the element types match, VMCore can fold it.
00161       unsigned NumDstElt = DestVTy->getNumElements();
00162       unsigned NumSrcElt = CV->getNumOperands();
00163       if (NumDstElt == NumSrcElt)
00164         return 0;
00165       
00166       const Type *SrcEltTy = CV->getType()->getElementType();
00167       const Type *DstEltTy = DestVTy->getElementType();
00168       
00169       // Otherwise, we're changing the number of elements in a vector, which 
00170       // requires endianness information to do the right thing.  For example,
00171       //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
00172       // folds to (little endian):
00173       //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
00174       // and to (big endian):
00175       //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
00176       
00177       // First thing is first.  We only want to think about integer here, so if
00178       // we have something in FP form, recast it as integer.
00179       if (DstEltTy->isFloatingPoint()) {
00180         // Fold to an vector of integers with same size as our FP type.
00181         unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
00182         const Type *DestIVTy = VectorType::get(IntegerType::get(FPWidth),
00183                                                NumDstElt);
00184         // Recursively handle this integer conversion, if possible.
00185         C = FoldBitCast(C, DestIVTy, TD);
00186         if (!C) return 0;
00187         
00188         // Finally, VMCore can handle this now that #elts line up.
00189         return ConstantExpr::getBitCast(C, DestTy);
00190       }
00191       
00192       // Okay, we know the destination is integer, if the input is FP, convert
00193       // it to integer first.
00194       if (SrcEltTy->isFloatingPoint()) {
00195         unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
00196         const Type *SrcIVTy = VectorType::get(IntegerType::get(FPWidth),
00197                                               NumSrcElt);
00198         // Ask VMCore to do the conversion now that #elts line up.
00199         C = ConstantExpr::getBitCast(C, SrcIVTy);
00200         CV = dyn_cast<ConstantVector>(C);
00201         if (!CV) return 0;  // If VMCore wasn't able to fold it, bail out.
00202       }
00203       
00204       // Now we know that the input and output vectors are both integer vectors
00205       // of the same size, and that their #elements is not the same.  Do the
00206       // conversion here, which depends on whether the input or output has
00207       // more elements.
00208       bool isLittleEndian = TD.isLittleEndian();
00209       
00210       SmallVector<Constant*, 32> Result;
00211       if (NumDstElt < NumSrcElt) {
00212         // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
00213         Constant *Zero = Constant::getNullValue(DstEltTy);
00214         unsigned Ratio = NumSrcElt/NumDstElt;
00215         unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
00216         unsigned SrcElt = 0;
00217         for (unsigned i = 0; i != NumDstElt; ++i) {
00218           // Build each element of the result.
00219           Constant *Elt = Zero;
00220           unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
00221           for (unsigned j = 0; j != Ratio; ++j) {
00222             Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
00223             if (!Src) return 0;  // Reject constantexpr elements.
00224             
00225             // Zero extend the element to the right size.
00226             Src = ConstantExpr::getZExt(Src, Elt->getType());
00227             
00228             // Shift it to the right place, depending on endianness.
00229             Src = ConstantExpr::getShl(Src, 
00230                                     ConstantInt::get(Src->getType(), ShiftAmt));
00231             ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
00232             
00233             // Mix it in.
00234             Elt = ConstantExpr::getOr(Elt, Src);
00235           }
00236           Result.push_back(Elt);
00237         }
00238       } else {
00239         // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
00240         unsigned Ratio = NumDstElt/NumSrcElt;
00241         unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
00242         
00243         // Loop over each source value, expanding into multiple results.
00244         for (unsigned i = 0; i != NumSrcElt; ++i) {
00245           Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
00246           if (!Src) return 0;  // Reject constantexpr elements.
00247 
00248           unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
00249           for (unsigned j = 0; j != Ratio; ++j) {
00250             // Shift the piece of the value into the right place, depending on
00251             // endianness.
00252             Constant *Elt = ConstantExpr::getLShr(Src, 
00253                                 ConstantInt::get(Src->getType(), ShiftAmt));
00254             ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
00255 
00256             // Truncate and remember this piece.
00257             Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
00258           }
00259         }
00260       }
00261       
00262       return ConstantVector::get(&Result[0], Result.size());
00263     }
00264   }
00265   
00266   return 0;
00267 }
00268 
00269 
00270 //===----------------------------------------------------------------------===//
00271 // Constant Folding public APIs
00272 //===----------------------------------------------------------------------===//
00273 
00274 
00275 /// ConstantFoldInstruction - Attempt to constant fold the specified
00276 /// instruction.  If successful, the constant result is returned, if not, null
00277 /// is returned.  Note that this function can only fail when attempting to fold
00278 /// instructions like loads and stores, which have no constant expression form.
00279 ///
00280 Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
00281   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00282     if (PN->getNumIncomingValues() == 0)
00283       return UndefValue::get(PN->getType());
00284 
00285     Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
00286     if (Result == 0) return 0;
00287 
00288     // Handle PHI nodes specially here...
00289     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
00290       if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
00291         return 0;   // Not all the same incoming constants...
00292 
00293     // If we reach here, all incoming values are the same constant.
00294     return Result;
00295   }
00296 
00297   // Scan the operand list, checking to see if they are all constants, if so,
00298   // hand off to ConstantFoldInstOperands.
00299   SmallVector<Constant*, 8> Ops;
00300   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
00301     if (Constant *Op = dyn_cast<Constant>(*i))
00302       Ops.push_back(Op);
00303     else
00304       return 0;  // All operands not constant!
00305 
00306   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
00307     return ConstantFoldCompareInstOperands(CI->getPredicate(),
00308                                            &Ops[0], Ops.size(), TD);
00309   else
00310     return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
00311                                     &Ops[0], Ops.size(), TD);
00312 }
00313 
00314 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
00315 /// using the specified TargetData.  If successful, the constant result is
00316 /// result is returned, if not, null is returned.
00317 Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
00318                                                const TargetData *TD) {
00319   assert(TD && "ConstantFoldConstantExpression requires a valid TargetData.");
00320 
00321   SmallVector<Constant*, 8> Ops;
00322   for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
00323     Ops.push_back(cast<Constant>(*i));
00324 
00325   if (CE->isCompare())
00326     return ConstantFoldCompareInstOperands(CE->getPredicate(),
00327                                            &Ops[0], Ops.size(), TD);
00328   else 
00329     return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
00330                                     &Ops[0], Ops.size(), TD);
00331 }
00332 
00333 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
00334 /// specified opcode and operands.  If successful, the constant result is
00335 /// returned, if not, null is returned.  Note that this function can fail when
00336 /// attempting to fold instructions like loads and stores, which have no
00337 /// constant expression form.
00338 ///
00339 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy, 
00340                                          Constant* const* Ops, unsigned NumOps,
00341                                          const TargetData *TD) {
00342   // Handle easy binops first.
00343   if (Instruction::isBinaryOp(Opcode)) {
00344     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
00345       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
00346         return C;
00347     
00348     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
00349   }
00350   
00351   switch (Opcode) {
00352   default: return 0;
00353   case Instruction::Call:
00354     if (Function *F = dyn_cast<Function>(Ops[0]))
00355       if (canConstantFoldCallTo(F))
00356         return ConstantFoldCall(F, Ops+1, NumOps-1);
00357     return 0;
00358   case Instruction::ICmp:
00359   case Instruction::FCmp:
00360   case Instruction::VICmp:
00361   case Instruction::VFCmp:
00362     assert(0 &&"This function is invalid for compares: no predicate specified");
00363   case Instruction::PtrToInt:
00364     // If the input is a inttoptr, eliminate the pair.  This requires knowing
00365     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
00366     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
00367       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
00368         Constant *Input = CE->getOperand(0);
00369         unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
00370         if (TD->getPointerSizeInBits() < InWidth) {
00371           Constant *Mask = 
00372             ConstantInt::get(APInt::getLowBitsSet(InWidth,
00373                                                   TD->getPointerSizeInBits()));
00374           Input = ConstantExpr::getAnd(Input, Mask);
00375         }
00376         // Do a zext or trunc to get to the dest size.
00377         return ConstantExpr::getIntegerCast(Input, DestTy, false);
00378       }
00379     }
00380     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
00381   case Instruction::IntToPtr:
00382     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
00383     // the int size is >= the ptr size.  This requires knowing the width of a
00384     // pointer, so it can't be done in ConstantExpr::getCast.
00385     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
00386       if (TD && CE->getOpcode() == Instruction::PtrToInt &&
00387           TD->getPointerSizeInBits() <=
00388           CE->getType()->getPrimitiveSizeInBits()) {
00389         Constant *Input = CE->getOperand(0);
00390         Constant *C = FoldBitCast(Input, DestTy, *TD);
00391         return C ? C : ConstantExpr::getBitCast(Input, DestTy);
00392       }
00393     }
00394     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
00395   case Instruction::Trunc:
00396   case Instruction::ZExt:
00397   case Instruction::SExt:
00398   case Instruction::FPTrunc:
00399   case Instruction::FPExt:
00400   case Instruction::UIToFP:
00401   case Instruction::SIToFP:
00402   case Instruction::FPToUI:
00403   case Instruction::FPToSI:
00404       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
00405   case Instruction::BitCast:
00406     if (TD)
00407       if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD))
00408         return C;
00409     return ConstantExpr::getBitCast(Ops[0], DestTy);
00410   case Instruction::Select:
00411     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
00412   case Instruction::ExtractElement:
00413     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
00414   case Instruction::InsertElement:
00415     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
00416   case Instruction::ShuffleVector:
00417     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
00418   case Instruction::GetElementPtr:
00419     if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
00420       return C;
00421     
00422     return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
00423   }
00424 }
00425 
00426 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
00427 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
00428 /// returns a constant expression of the specified operands.
00429 ///
00430 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
00431                                                 Constant*const * Ops, 
00432                                                 unsigned NumOps,
00433                                                 const TargetData *TD) {
00434   // fold: icmp (inttoptr x), null         -> icmp x, 0
00435   // fold: icmp (ptrtoint x), 0            -> icmp x, null
00436   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
00437   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
00438   //
00439   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
00440   // around to know if bit truncation is happening.
00441   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
00442     if (TD && Ops[1]->isNullValue()) {
00443       const Type *IntPtrTy = TD->getIntPtrType();
00444       if (CE0->getOpcode() == Instruction::IntToPtr) {
00445         // Convert the integer value to the right size to ensure we get the
00446         // proper extension or truncation.
00447         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
00448                                                    IntPtrTy, false);
00449         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
00450         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
00451       }
00452       
00453       // Only do this transformation if the int is intptrty in size, otherwise
00454       // there is a truncation or extension that we aren't modeling.
00455       if (CE0->getOpcode() == Instruction::PtrToInt && 
00456           CE0->getType() == IntPtrTy) {
00457         Constant *C = CE0->getOperand(0);
00458         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
00459         // FIXME!
00460         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
00461       }
00462     }
00463     
00464     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
00465       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
00466         const Type *IntPtrTy = TD->getIntPtrType();
00467 
00468         if (CE0->getOpcode() == Instruction::IntToPtr) {
00469           // Convert the integer value to the right size to ensure we get the
00470           // proper extension or truncation.
00471           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
00472                                                       IntPtrTy, false);
00473           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
00474                                                       IntPtrTy, false);
00475           Constant *NewOps[] = { C0, C1 };
00476           return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
00477         }
00478 
00479         // Only do this transformation if the int is intptrty in size, otherwise
00480         // there is a truncation or extension that we aren't modeling.
00481         if ((CE0->getOpcode() == Instruction::PtrToInt &&
00482              CE0->getType() == IntPtrTy &&
00483              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
00484           Constant *NewOps[] = { 
00485             CE0->getOperand(0), CE1->getOperand(0) 
00486           };
00487           return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
00488         }
00489       }
00490     }
00491   }
00492   return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
00493 }
00494 
00495 
00496 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
00497 /// getelementptr constantexpr, return the constant value being addressed by the
00498 /// constant expression, or null if something is funny and we can't decide.
00499 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
00500                                                        ConstantExpr *CE) {
00501   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
00502     return 0;  // Do not allow stepping over the value!
00503   
00504   // Loop over all of the operands, tracking down which value we are
00505   // addressing...
00506   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
00507   for (++I; I != E; ++I)
00508     if (const StructType *STy = dyn_cast<StructType>(*I)) {
00509       ConstantInt *CU = cast<ConstantInt>(I.getOperand());
00510       assert(CU->getZExtValue() < STy->getNumElements() &&
00511              "Struct index out of range!");
00512       unsigned El = (unsigned)CU->getZExtValue();
00513       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
00514         C = CS->getOperand(El);
00515       } else if (isa<ConstantAggregateZero>(C)) {
00516         C = Constant::getNullValue(STy->getElementType(El));
00517       } else if (isa<UndefValue>(C)) {
00518         C = UndefValue::get(STy->getElementType(El));
00519       } else {
00520         return 0;
00521       }
00522     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
00523       if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
00524         if (CI->getZExtValue() >= ATy->getNumElements())
00525          return 0;
00526         if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
00527           C = CA->getOperand(CI->getZExtValue());
00528         else if (isa<ConstantAggregateZero>(C))
00529           C = Constant::getNullValue(ATy->getElementType());
00530         else if (isa<UndefValue>(C))
00531           C = UndefValue::get(ATy->getElementType());
00532         else
00533           return 0;
00534       } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
00535         if (CI->getZExtValue() >= PTy->getNumElements())
00536           return 0;
00537         if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
00538           C = CP->getOperand(CI->getZExtValue());
00539         else if (isa<ConstantAggregateZero>(C))
00540           C = Constant::getNullValue(PTy->getElementType());
00541         else if (isa<UndefValue>(C))
00542           C = UndefValue::get(PTy->getElementType());
00543         else
00544           return 0;
00545       } else {
00546         return 0;
00547       }
00548     } else {
00549       return 0;
00550     }
00551   return C;
00552 }
00553 
00554 
00555 //===----------------------------------------------------------------------===//
00556 //  Constant Folding for Calls
00557 //
00558 
00559 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
00560 /// the specified function.
00561 bool
00562 llvm::canConstantFoldCallTo(const Function *F) {
00563   switch (F->getIntrinsicID()) {
00564   case Intrinsic::sqrt:
00565   case Intrinsic::powi:
00566   case Intrinsic::bswap:
00567   case Intrinsic::ctpop:
00568   case Intrinsic::ctlz:
00569   case Intrinsic::cttz:
00570     return true;
00571   default: break;
00572   }
00573 
00574   const ValueName *NameVal = F->getValueName();
00575   if (NameVal == 0) return false;
00576   const char *Str = NameVal->getKeyData();
00577   unsigned Len = NameVal->getKeyLength();
00578   
00579   // In these cases, the check of the length is required.  We don't want to
00580   // return true for a name like "cos\0blah" which strcmp would return equal to
00581   // "cos", but has length 8.
00582   switch (Str[0]) {
00583   default: return false;
00584   case 'a':
00585     if (Len == 4)
00586       return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
00587              !strcmp(Str, "atan");
00588     else if (Len == 5)
00589       return !strcmp(Str, "atan2");
00590     return false;
00591   case 'c':
00592     if (Len == 3)
00593       return !strcmp(Str, "cos");
00594     else if (Len == 4)
00595       return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
00596              !strcmp(Str, "cosh");
00597     return false;
00598   case 'e':
00599     if (Len == 3)
00600       return !strcmp(Str, "exp");
00601     return false;
00602   case 'f':
00603     if (Len == 4)
00604       return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
00605     else if (Len == 5)
00606       return !strcmp(Str, "floor");
00607     return false;
00608     break;
00609   case 'l':
00610     if (Len == 3 && !strcmp(Str, "log"))
00611       return true;
00612     if (Len == 5 && !strcmp(Str, "log10"))
00613       return true;
00614     return false;
00615   case 'p':
00616     if (Len == 3 && !strcmp(Str, "pow"))
00617       return true;
00618     return false;
00619   case 's':
00620     if (Len == 3)
00621       return !strcmp(Str, "sin");
00622     if (Len == 4)
00623       return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
00624              !strcmp(Str, "sinf");
00625     if (Len == 5)
00626       return !strcmp(Str, "sqrtf");
00627     return false;
00628   case 't':
00629     if (Len == 3 && !strcmp(Str, "tan"))
00630       return true;
00631     else if (Len == 4 && !strcmp(Str, "tanh"))
00632       return true;
00633     return false;
00634   }
00635 }
00636 
00637 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, 
00638                                 const Type *Ty) {
00639   errno = 0;
00640   V = NativeFP(V);
00641   if (errno != 0) {
00642     errno = 0;
00643     return 0;
00644   }
00645   
00646   if (Ty == Type::FloatTy)
00647     return ConstantFP::get(APFloat((float)V));
00648   if (Ty == Type::DoubleTy)
00649     return ConstantFP::get(APFloat(V));
00650   assert(0 && "Can only constant fold float/double");
00651   return 0; // dummy return to suppress warning
00652 }
00653 
00654 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
00655                                       double V, double W,
00656                                       const Type *Ty) {
00657   errno = 0;
00658   V = NativeFP(V, W);
00659   if (errno != 0) {
00660     errno = 0;
00661     return 0;
00662   }
00663   
00664   if (Ty == Type::FloatTy)
00665     return ConstantFP::get(APFloat((float)V));
00666   if (Ty == Type::DoubleTy)
00667     return ConstantFP::get(APFloat(V));
00668   assert(0 && "Can only constant fold float/double");
00669   return 0; // dummy return to suppress warning
00670 }
00671 
00672 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
00673 /// with the specified arguments, returning null if unsuccessful.
00674 
00675 Constant *
00676 llvm::ConstantFoldCall(Function *F, 
00677                        Constant* const* Operands, unsigned NumOperands) {
00678   const ValueName *NameVal = F->getValueName();
00679   if (NameVal == 0) return 0;
00680   const char *Str = NameVal->getKeyData();
00681   unsigned Len = NameVal->getKeyLength();
00682   
00683   const Type *Ty = F->getReturnType();
00684   if (NumOperands == 1) {
00685     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
00686       if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
00687         return 0;
00688       /// Currently APFloat versions of these functions do not exist, so we use
00689       /// the host native double versions.  Float versions are not called
00690       /// directly but for all these it is true (float)(f((double)arg)) ==
00691       /// f(arg).  Long double not supported yet.
00692       double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
00693                                      Op->getValueAPF().convertToDouble();
00694       switch (Str[0]) {
00695       case 'a':
00696         if (Len == 4 && !strcmp(Str, "acos"))
00697           return ConstantFoldFP(acos, V, Ty);
00698         else if (Len == 4 && !strcmp(Str, "asin"))
00699           return ConstantFoldFP(asin, V, Ty);
00700         else if (Len == 4 && !strcmp(Str, "atan"))
00701           return ConstantFoldFP(atan, V, Ty);
00702         break;
00703       case 'c':
00704         if (Len == 4 && !strcmp(Str, "ceil"))
00705           return ConstantFoldFP(ceil, V, Ty);
00706         else if (Len == 3 && !strcmp(Str, "cos"))
00707           return ConstantFoldFP(cos, V, Ty);
00708         else if (Len == 4 && !strcmp(Str, "cosh"))
00709           return ConstantFoldFP(cosh, V, Ty);
00710         else if (Len == 4 && !strcmp(Str, "cosf"))
00711           return ConstantFoldFP(cos, V, Ty);
00712         break;
00713       case 'e':
00714         if (Len == 3 && !strcmp(Str, "exp"))
00715           return ConstantFoldFP(exp, V, Ty);
00716         break;
00717       case 'f':
00718         if (Len == 4 && !strcmp(Str, "fabs"))
00719           return ConstantFoldFP(fabs, V, Ty);
00720         else if (Len == 5 && !strcmp(Str, "floor"))
00721           return ConstantFoldFP(floor, V, Ty);
00722         break;
00723       case 'l':
00724         if (Len == 3 && !strcmp(Str, "log") && V > 0)
00725           return ConstantFoldFP(log, V, Ty);
00726         else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
00727           return ConstantFoldFP(log10, V, Ty);
00728         else if (!strcmp(Str, "llvm.sqrt.f32") ||
00729                  !strcmp(Str, "llvm.sqrt.f64")) {
00730           if (V >= -0.0)
00731             return ConstantFoldFP(sqrt, V, Ty);
00732           else // Undefined
00733             return Constant::getNullValue(Ty);
00734         }
00735         break;
00736       case 's':
00737         if (Len == 3 && !strcmp(Str, "sin"))
00738           return ConstantFoldFP(sin, V, Ty);
00739         else if (Len == 4 && !strcmp(Str, "sinh"))
00740           return ConstantFoldFP(sinh, V, Ty);
00741         else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
00742           return ConstantFoldFP(sqrt, V, Ty);
00743         else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
00744           return ConstantFoldFP(sqrt, V, Ty);
00745         else if (Len == 4 && !strcmp(Str, "sinf"))
00746           return ConstantFoldFP(sin, V, Ty);
00747         break;
00748       case 't':
00749         if (Len == 3 && !strcmp(Str, "tan"))
00750           return ConstantFoldFP(tan, V, Ty);
00751         else if (Len == 4 && !strcmp(Str, "tanh"))
00752           return ConstantFoldFP(tanh, V, Ty);
00753         break;
00754       default:
00755         break;
00756       }
00757     } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
00758       if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
00759         return ConstantInt::get(Op->getValue().byteSwap());
00760       else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
00761         return ConstantInt::get(Ty, Op->getValue().countPopulation());
00762       else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
00763         return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
00764       else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
00765         return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
00766     }
00767   } else if (NumOperands == 2) {
00768     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
00769       if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
00770         return 0;
00771       double Op1V = Ty==Type::FloatTy ? 
00772                       (double)Op1->getValueAPF().convertToFloat():
00773                       Op1->getValueAPF().convertToDouble();
00774       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
00775         double Op2V = Ty==Type::FloatTy ? 
00776                       (double)Op2->getValueAPF().convertToFloat():
00777                       Op2->getValueAPF().convertToDouble();
00778 
00779         if (Len == 3 && !strcmp(Str, "pow")) {
00780           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
00781         } else if (Len == 4 && !strcmp(Str, "fmod")) {
00782           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
00783         } else if (Len == 5 && !strcmp(Str, "atan2")) {
00784           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
00785         }
00786       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
00787         if (!strcmp(Str, "llvm.powi.f32")) {
00788           return ConstantFP::get(APFloat((float)std::pow((float)Op1V,
00789                                                  (int)Op2C->getZExtValue())));
00790         } else if (!strcmp(Str, "llvm.powi.f64")) {
00791           return ConstantFP::get(APFloat((double)std::pow((double)Op1V,
00792                                                  (int)Op2C->getZExtValue())));
00793         }
00794       }
00795     }
00796   }
00797   return 0;
00798 }
00799