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



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.