LLVM API Documentation

ConstantFolding.cpp
Go to the documentation of this file.
00001 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
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 file defines routines for folding instructions into constants.
00011 //
00012 // Also, to supplement the basic IR ConstantExpr simplifications,
00013 // this file defines some additional folding routines that can make use of
00014 // DataLayout information. These functions cannot go in IR due to library
00015 // dependency issues.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/Analysis/ConstantFolding.h"
00020 #include "llvm/ADT/SmallPtrSet.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/Analysis/ValueTracking.h"
00024 #include "llvm/Config/config.h"
00025 #include "llvm/IR/Constants.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/DerivedTypes.h"
00028 #include "llvm/IR/Function.h"
00029 #include "llvm/IR/GetElementPtrTypeIterator.h"
00030 #include "llvm/IR/GlobalVariable.h"
00031 #include "llvm/IR/Instructions.h"
00032 #include "llvm/IR/Intrinsics.h"
00033 #include "llvm/IR/Operator.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/MathExtras.h"
00036 #include "llvm/Target/TargetLibraryInfo.h"
00037 #include <cerrno>
00038 #include <cmath>
00039 
00040 #ifdef HAVE_FENV_H
00041 #include <fenv.h>
00042 #endif
00043 
00044 using namespace llvm;
00045 
00046 //===----------------------------------------------------------------------===//
00047 // Constant Folding internal helper functions
00048 //===----------------------------------------------------------------------===//
00049 
00050 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
00051 /// This always returns a non-null constant, but it may be a
00052 /// ConstantExpr if unfoldable.
00053 static Constant *FoldBitCast(Constant *C, Type *DestTy,
00054                              const DataLayout &TD) {
00055   // Catch the obvious splat cases.
00056   if (C->isNullValue() && !DestTy->isX86_MMXTy())
00057     return Constant::getNullValue(DestTy);
00058   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
00059     return Constant::getAllOnesValue(DestTy);
00060 
00061   // Handle a vector->integer cast.
00062   if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
00063     VectorType *VTy = dyn_cast<VectorType>(C->getType());
00064     if (!VTy)
00065       return ConstantExpr::getBitCast(C, DestTy);
00066 
00067     unsigned NumSrcElts = VTy->getNumElements();
00068     Type *SrcEltTy = VTy->getElementType();
00069 
00070     // If the vector is a vector of floating point, convert it to vector of int
00071     // to simplify things.
00072     if (SrcEltTy->isFloatingPointTy()) {
00073       unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
00074       Type *SrcIVTy =
00075         VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
00076       // Ask IR to do the conversion now that #elts line up.
00077       C = ConstantExpr::getBitCast(C, SrcIVTy);
00078     }
00079 
00080     ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
00081     if (!CDV)
00082       return ConstantExpr::getBitCast(C, DestTy);
00083 
00084     // Now that we know that the input value is a vector of integers, just shift
00085     // and insert them into our result.
00086     unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
00087     APInt Result(IT->getBitWidth(), 0);
00088     for (unsigned i = 0; i != NumSrcElts; ++i) {
00089       Result <<= BitShift;
00090       if (TD.isLittleEndian())
00091         Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
00092       else
00093         Result |= CDV->getElementAsInteger(i);
00094     }
00095 
00096     return ConstantInt::get(IT, Result);
00097   }
00098 
00099   // The code below only handles casts to vectors currently.
00100   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
00101   if (!DestVTy)
00102     return ConstantExpr::getBitCast(C, DestTy);
00103 
00104   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
00105   // vector so the code below can handle it uniformly.
00106   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
00107     Constant *Ops = C; // don't take the address of C!
00108     return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
00109   }
00110 
00111   // If this is a bitcast from constant vector -> vector, fold it.
00112   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
00113     return ConstantExpr::getBitCast(C, DestTy);
00114 
00115   // If the element types match, IR can fold it.
00116   unsigned NumDstElt = DestVTy->getNumElements();
00117   unsigned NumSrcElt = C->getType()->getVectorNumElements();
00118   if (NumDstElt == NumSrcElt)
00119     return ConstantExpr::getBitCast(C, DestTy);
00120 
00121   Type *SrcEltTy = C->getType()->getVectorElementType();
00122   Type *DstEltTy = DestVTy->getElementType();
00123 
00124   // Otherwise, we're changing the number of elements in a vector, which
00125   // requires endianness information to do the right thing.  For example,
00126   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
00127   // folds to (little endian):
00128   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
00129   // and to (big endian):
00130   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
00131 
00132   // First thing is first.  We only want to think about integer here, so if
00133   // we have something in FP form, recast it as integer.
00134   if (DstEltTy->isFloatingPointTy()) {
00135     // Fold to an vector of integers with same size as our FP type.
00136     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
00137     Type *DestIVTy =
00138       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
00139     // Recursively handle this integer conversion, if possible.
00140     C = FoldBitCast(C, DestIVTy, TD);
00141 
00142     // Finally, IR can handle this now that #elts line up.
00143     return ConstantExpr::getBitCast(C, DestTy);
00144   }
00145 
00146   // Okay, we know the destination is integer, if the input is FP, convert
00147   // it to integer first.
00148   if (SrcEltTy->isFloatingPointTy()) {
00149     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
00150     Type *SrcIVTy =
00151       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
00152     // Ask IR to do the conversion now that #elts line up.
00153     C = ConstantExpr::getBitCast(C, SrcIVTy);
00154     // If IR wasn't able to fold it, bail out.
00155     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
00156         !isa<ConstantDataVector>(C))
00157       return C;
00158   }
00159 
00160   // Now we know that the input and output vectors are both integer vectors
00161   // of the same size, and that their #elements is not the same.  Do the
00162   // conversion here, which depends on whether the input or output has
00163   // more elements.
00164   bool isLittleEndian = TD.isLittleEndian();
00165 
00166   SmallVector<Constant*, 32> Result;
00167   if (NumDstElt < NumSrcElt) {
00168     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
00169     Constant *Zero = Constant::getNullValue(DstEltTy);
00170     unsigned Ratio = NumSrcElt/NumDstElt;
00171     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
00172     unsigned SrcElt = 0;
00173     for (unsigned i = 0; i != NumDstElt; ++i) {
00174       // Build each element of the result.
00175       Constant *Elt = Zero;
00176       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
00177       for (unsigned j = 0; j != Ratio; ++j) {
00178         Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
00179         if (!Src)  // Reject constantexpr elements.
00180           return ConstantExpr::getBitCast(C, DestTy);
00181 
00182         // Zero extend the element to the right size.
00183         Src = ConstantExpr::getZExt(Src, Elt->getType());
00184 
00185         // Shift it to the right place, depending on endianness.
00186         Src = ConstantExpr::getShl(Src,
00187                                    ConstantInt::get(Src->getType(), ShiftAmt));
00188         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
00189 
00190         // Mix it in.
00191         Elt = ConstantExpr::getOr(Elt, Src);
00192       }
00193       Result.push_back(Elt);
00194     }
00195     return ConstantVector::get(Result);
00196   }
00197 
00198   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
00199   unsigned Ratio = NumDstElt/NumSrcElt;
00200   unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
00201 
00202   // Loop over each source value, expanding into multiple results.
00203   for (unsigned i = 0; i != NumSrcElt; ++i) {
00204     Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
00205     if (!Src)  // Reject constantexpr elements.
00206       return ConstantExpr::getBitCast(C, DestTy);
00207 
00208     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
00209     for (unsigned j = 0; j != Ratio; ++j) {
00210       // Shift the piece of the value into the right place, depending on
00211       // endianness.
00212       Constant *Elt = ConstantExpr::getLShr(Src,
00213                                   ConstantInt::get(Src->getType(), ShiftAmt));
00214       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
00215 
00216       // Truncate and remember this piece.
00217       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
00218     }
00219   }
00220 
00221   return ConstantVector::get(Result);
00222 }
00223 
00224 
00225 /// If this constant is a constant offset from a global, return the global and
00226 /// the constant. Because of constantexprs, this function is recursive.
00227 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
00228                                        APInt &Offset, const DataLayout &TD) {
00229   // Trivial case, constant is the global.
00230   if ((GV = dyn_cast<GlobalValue>(C))) {
00231     unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
00232     Offset = APInt(BitWidth, 0);
00233     return true;
00234   }
00235 
00236   // Otherwise, if this isn't a constant expr, bail out.
00237   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00238   if (!CE) return false;
00239 
00240   // Look through ptr->int and ptr->ptr casts.
00241   if (CE->getOpcode() == Instruction::PtrToInt ||
00242       CE->getOpcode() == Instruction::BitCast ||
00243       CE->getOpcode() == Instruction::AddrSpaceCast)
00244     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
00245 
00246   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
00247   GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
00248   if (!GEP)
00249     return false;
00250 
00251   unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
00252   APInt TmpOffset(BitWidth, 0);
00253 
00254   // If the base isn't a global+constant, we aren't either.
00255   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
00256     return false;
00257 
00258   // Otherwise, add any offset that our operands provide.
00259   if (!GEP->accumulateConstantOffset(TD, TmpOffset))
00260     return false;
00261 
00262   Offset = TmpOffset;
00263   return true;
00264 }
00265 
00266 /// Recursive helper to read bits out of global. C is the constant being copied
00267 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
00268 /// results into and BytesLeft is the number of bytes left in
00269 /// the CurPtr buffer. TD is the target data.
00270 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
00271                                unsigned char *CurPtr, unsigned BytesLeft,
00272                                const DataLayout &TD) {
00273   assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
00274          "Out of range access");
00275 
00276   // If this element is zero or undefined, we can just return since *CurPtr is
00277   // zero initialized.
00278   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
00279     return true;
00280 
00281   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
00282     if (CI->getBitWidth() > 64 ||
00283         (CI->getBitWidth() & 7) != 0)
00284       return false;
00285 
00286     uint64_t Val = CI->getZExtValue();
00287     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
00288 
00289     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
00290       int n = ByteOffset;
00291       if (!TD.isLittleEndian())
00292         n = IntBytes - n - 1;
00293       CurPtr[i] = (unsigned char)(Val >> (n * 8));
00294       ++ByteOffset;
00295     }
00296     return true;
00297   }
00298 
00299   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
00300     if (CFP->getType()->isDoubleTy()) {
00301       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
00302       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
00303     }
00304     if (CFP->getType()->isFloatTy()){
00305       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
00306       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
00307     }
00308     if (CFP->getType()->isHalfTy()){
00309       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
00310       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
00311     }
00312     return false;
00313   }
00314 
00315   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
00316     const StructLayout *SL = TD.getStructLayout(CS->getType());
00317     unsigned Index = SL->getElementContainingOffset(ByteOffset);
00318     uint64_t CurEltOffset = SL->getElementOffset(Index);
00319     ByteOffset -= CurEltOffset;
00320 
00321     while (1) {
00322       // If the element access is to the element itself and not to tail padding,
00323       // read the bytes from the element.
00324       uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
00325 
00326       if (ByteOffset < EltSize &&
00327           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
00328                               BytesLeft, TD))
00329         return false;
00330 
00331       ++Index;
00332 
00333       // Check to see if we read from the last struct element, if so we're done.
00334       if (Index == CS->getType()->getNumElements())
00335         return true;
00336 
00337       // If we read all of the bytes we needed from this element we're done.
00338       uint64_t NextEltOffset = SL->getElementOffset(Index);
00339 
00340       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
00341         return true;
00342 
00343       // Move to the next element of the struct.
00344       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
00345       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
00346       ByteOffset = 0;
00347       CurEltOffset = NextEltOffset;
00348     }
00349     // not reached.
00350   }
00351 
00352   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
00353       isa<ConstantDataSequential>(C)) {
00354     Type *EltTy = C->getType()->getSequentialElementType();
00355     uint64_t EltSize = TD.getTypeAllocSize(EltTy);
00356     uint64_t Index = ByteOffset / EltSize;
00357     uint64_t Offset = ByteOffset - Index * EltSize;
00358     uint64_t NumElts;
00359     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
00360       NumElts = AT->getNumElements();
00361     else
00362       NumElts = C->getType()->getVectorNumElements();
00363 
00364     for (; Index != NumElts; ++Index) {
00365       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
00366                               BytesLeft, TD))
00367         return false;
00368 
00369       uint64_t BytesWritten = EltSize - Offset;
00370       assert(BytesWritten <= EltSize && "Not indexing into this element?");
00371       if (BytesWritten >= BytesLeft)
00372         return true;
00373 
00374       Offset = 0;
00375       BytesLeft -= BytesWritten;
00376       CurPtr += BytesWritten;
00377     }
00378     return true;
00379   }
00380 
00381   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00382     if (CE->getOpcode() == Instruction::IntToPtr &&
00383         CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
00384       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
00385                                 BytesLeft, TD);
00386     }
00387   }
00388 
00389   // Otherwise, unknown initializer type.
00390   return false;
00391 }
00392 
00393 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
00394                                                  const DataLayout &TD) {
00395   PointerType *PTy = cast<PointerType>(C->getType());
00396   Type *LoadTy = PTy->getElementType();
00397   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
00398 
00399   // If this isn't an integer load we can't fold it directly.
00400   if (!IntType) {
00401     unsigned AS = PTy->getAddressSpace();
00402 
00403     // If this is a float/double load, we can try folding it as an int32/64 load
00404     // and then bitcast the result.  This can be useful for union cases.  Note
00405     // that address spaces don't matter here since we're not going to result in
00406     // an actual new load.
00407     Type *MapTy;
00408     if (LoadTy->isHalfTy())
00409       MapTy = Type::getInt16PtrTy(C->getContext(), AS);
00410     else if (LoadTy->isFloatTy())
00411       MapTy = Type::getInt32PtrTy(C->getContext(), AS);
00412     else if (LoadTy->isDoubleTy())
00413       MapTy = Type::getInt64PtrTy(C->getContext(), AS);
00414     else if (LoadTy->isVectorTy()) {
00415       MapTy = PointerType::getIntNPtrTy(C->getContext(),
00416                                         TD.getTypeAllocSizeInBits(LoadTy),
00417                                         AS);
00418     } else
00419       return nullptr;
00420 
00421     C = FoldBitCast(C, MapTy, TD);
00422     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
00423       return FoldBitCast(Res, LoadTy, TD);
00424     return nullptr;
00425   }
00426 
00427   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
00428   if (BytesLoaded > 32 || BytesLoaded == 0)
00429     return nullptr;
00430 
00431   GlobalValue *GVal;
00432   APInt Offset;
00433   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
00434     return nullptr;
00435 
00436   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
00437   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
00438       !GV->getInitializer()->getType()->isSized())
00439     return nullptr;
00440 
00441   // If we're loading off the beginning of the global, some bytes may be valid,
00442   // but we don't try to handle this.
00443   if (Offset.isNegative())
00444     return nullptr;
00445 
00446   // If we're not accessing anything in this constant, the result is undefined.
00447   if (Offset.getZExtValue() >=
00448       TD.getTypeAllocSize(GV->getInitializer()->getType()))
00449     return UndefValue::get(IntType);
00450 
00451   unsigned char RawBytes[32] = {0};
00452   if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
00453                           BytesLoaded, TD))
00454     return nullptr;
00455 
00456   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
00457   if (TD.isLittleEndian()) {
00458     ResultVal = RawBytes[BytesLoaded - 1];
00459     for (unsigned i = 1; i != BytesLoaded; ++i) {
00460       ResultVal <<= 8;
00461       ResultVal |= RawBytes[BytesLoaded - 1 - i];
00462     }
00463   } else {
00464     ResultVal = RawBytes[0];
00465     for (unsigned i = 1; i != BytesLoaded; ++i) {
00466       ResultVal <<= 8;
00467       ResultVal |= RawBytes[i];
00468     }
00469   }
00470 
00471   return ConstantInt::get(IntType->getContext(), ResultVal);
00472 }
00473 
00474 static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
00475                                                 const DataLayout *DL) {
00476   if (!DL)
00477     return nullptr;
00478   auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
00479   if (!DestPtrTy)
00480     return nullptr;
00481   Type *DestTy = DestPtrTy->getElementType();
00482 
00483   Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
00484   if (!C)
00485     return nullptr;
00486 
00487   do {
00488     Type *SrcTy = C->getType();
00489 
00490     // If the type sizes are the same and a cast is legal, just directly
00491     // cast the constant.
00492     if (DL->getTypeSizeInBits(DestTy) == DL->getTypeSizeInBits(SrcTy)) {
00493       Instruction::CastOps Cast = Instruction::BitCast;
00494       // If we are going from a pointer to int or vice versa, we spell the cast
00495       // differently.
00496       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
00497         Cast = Instruction::IntToPtr;
00498       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
00499         Cast = Instruction::PtrToInt;
00500 
00501       if (CastInst::castIsValid(Cast, C, DestTy))
00502         return ConstantExpr::getCast(Cast, C, DestTy);
00503     }
00504 
00505     // If this isn't an aggregate type, there is nothing we can do to drill down
00506     // and find a bitcastable constant.
00507     if (!SrcTy->isAggregateType())
00508       return nullptr;
00509 
00510     // We're simulating a load through a pointer that was bitcast to point to
00511     // a different type, so we can try to walk down through the initial
00512     // elements of an aggregate to see if some part of th e aggregate is
00513     // castable to implement the "load" semantic model.
00514     C = C->getAggregateElement(0u);
00515   } while (C);
00516 
00517   return nullptr;
00518 }
00519 
00520 /// Return the value that a load from C would produce if it is constant and
00521 /// determinable. If this is not determinable, return null.
00522 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
00523                                              const DataLayout *TD) {
00524   // First, try the easy cases:
00525   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00526     if (GV->isConstant() && GV->hasDefinitiveInitializer())
00527       return GV->getInitializer();
00528 
00529   // If the loaded value isn't a constant expr, we can't handle it.
00530   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00531   if (!CE)
00532     return nullptr;
00533 
00534   if (CE->getOpcode() == Instruction::GetElementPtr) {
00535     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
00536       if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
00537         if (Constant *V =
00538              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
00539           return V;
00540       }
00541     }
00542   }
00543 
00544   if (CE->getOpcode() == Instruction::BitCast)
00545     if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, TD))
00546       return LoadedC;
00547 
00548   // Instead of loading constant c string, use corresponding integer value
00549   // directly if string length is small enough.
00550   StringRef Str;
00551   if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
00552     unsigned StrLen = Str.size();
00553     Type *Ty = cast<PointerType>(CE->getType())->getElementType();
00554     unsigned NumBits = Ty->getPrimitiveSizeInBits();
00555     // Replace load with immediate integer if the result is an integer or fp
00556     // value.
00557     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
00558         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
00559       APInt StrVal(NumBits, 0);
00560       APInt SingleChar(NumBits, 0);
00561       if (TD->isLittleEndian()) {
00562         for (signed i = StrLen-1; i >= 0; i--) {
00563           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
00564           StrVal = (StrVal << 8) | SingleChar;
00565         }
00566       } else {
00567         for (unsigned i = 0; i < StrLen; i++) {
00568           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
00569           StrVal = (StrVal << 8) | SingleChar;
00570         }
00571         // Append NULL at the end.
00572         SingleChar = 0;
00573         StrVal = (StrVal << 8) | SingleChar;
00574       }
00575 
00576       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
00577       if (Ty->isFloatingPointTy())
00578         Res = ConstantExpr::getBitCast(Res, Ty);
00579       return Res;
00580     }
00581   }
00582 
00583   // If this load comes from anywhere in a constant global, and if the global
00584   // is all undef or zero, we know what it loads.
00585   if (GlobalVariable *GV =
00586         dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
00587     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
00588       Type *ResTy = cast<PointerType>(C->getType())->getElementType();
00589       if (GV->getInitializer()->isNullValue())
00590         return Constant::getNullValue(ResTy);
00591       if (isa<UndefValue>(GV->getInitializer()))
00592         return UndefValue::get(ResTy);
00593     }
00594   }
00595 
00596   // Try hard to fold loads from bitcasted strange and non-type-safe things.
00597   if (TD)
00598     return FoldReinterpretLoadFromConstPtr(CE, *TD);
00599   return nullptr;
00600 }
00601 
00602 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
00603   if (LI->isVolatile()) return nullptr;
00604 
00605   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
00606     return ConstantFoldLoadFromConstPtr(C, TD);
00607 
00608   return nullptr;
00609 }
00610 
00611 /// One of Op0/Op1 is a constant expression.
00612 /// Attempt to symbolically evaluate the result of a binary operator merging
00613 /// these together.  If target data info is available, it is provided as DL,
00614 /// otherwise DL is null.
00615 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
00616                                            Constant *Op1, const DataLayout *DL){
00617   // SROA
00618 
00619   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
00620   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
00621   // bits.
00622 
00623 
00624   if (Opc == Instruction::And && DL) {
00625     unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
00626     APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
00627     APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
00628     computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
00629     computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
00630     if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
00631       // All the bits of Op0 that the 'and' could be masking are already zero.
00632       return Op0;
00633     }
00634     if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
00635       // All the bits of Op1 that the 'and' could be masking are already zero.
00636       return Op1;
00637     }
00638 
00639     APInt KnownZero = KnownZero0 | KnownZero1;
00640     APInt KnownOne = KnownOne0 & KnownOne1;
00641     if ((KnownZero | KnownOne).isAllOnesValue()) {
00642       return ConstantInt::get(Op0->getType(), KnownOne);
00643     }
00644   }
00645 
00646   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
00647   // constant.  This happens frequently when iterating over a global array.
00648   if (Opc == Instruction::Sub && DL) {
00649     GlobalValue *GV1, *GV2;
00650     APInt Offs1, Offs2;
00651 
00652     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
00653       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
00654           GV1 == GV2) {
00655         unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
00656 
00657         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
00658         // PtrToInt may change the bitwidth so we have convert to the right size
00659         // first.
00660         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
00661                                                 Offs2.zextOrTrunc(OpSize));
00662       }
00663   }
00664 
00665   return nullptr;
00666 }
00667 
00668 /// If array indices are not pointer-sized integers, explicitly cast them so
00669 /// that they aren't implicitly casted by the getelementptr.
00670 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
00671                                 Type *ResultTy, const DataLayout *TD,
00672                                 const TargetLibraryInfo *TLI) {
00673   if (!TD)
00674     return nullptr;
00675 
00676   Type *IntPtrTy = TD->getIntPtrType(ResultTy);
00677 
00678   bool Any = false;
00679   SmallVector<Constant*, 32> NewIdxs;
00680   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
00681     if ((i == 1 ||
00682          !isa<StructType>(GetElementPtrInst::getIndexedType(
00683                             Ops[0]->getType(),
00684                             Ops.slice(1, i - 1)))) &&
00685         Ops[i]->getType() != IntPtrTy) {
00686       Any = true;
00687       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
00688                                                                       true,
00689                                                                       IntPtrTy,
00690                                                                       true),
00691                                               Ops[i], IntPtrTy));
00692     } else
00693       NewIdxs.push_back(Ops[i]);
00694   }
00695 
00696   if (!Any)
00697     return nullptr;
00698 
00699   Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
00700   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00701     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
00702       C = Folded;
00703   }
00704 
00705   return C;
00706 }
00707 
00708 /// Strip the pointer casts, but preserve the address space information.
00709 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
00710   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
00711   PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
00712   Ptr = Ptr->stripPointerCasts();
00713   PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
00714 
00715   // Preserve the address space number of the pointer.
00716   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
00717     NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
00718       OldPtrTy->getAddressSpace());
00719     Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
00720   }
00721   return Ptr;
00722 }
00723 
00724 /// If we can symbolically evaluate the GEP constant expression, do so.
00725 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
00726                                          Type *ResultTy, const DataLayout *TD,
00727                                          const TargetLibraryInfo *TLI) {
00728   Constant *Ptr = Ops[0];
00729   if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
00730       !Ptr->getType()->isPointerTy())
00731     return nullptr;
00732 
00733   Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
00734   Type *ResultElementTy = ResultTy->getPointerElementType();
00735 
00736   // If this is a constant expr gep that is effectively computing an
00737   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
00738   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
00739     if (!isa<ConstantInt>(Ops[i])) {
00740 
00741       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
00742       // "inttoptr (sub (ptrtoint Ptr), V)"
00743       if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
00744         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
00745         assert((!CE || CE->getType() == IntPtrTy) &&
00746                "CastGEPIndices didn't canonicalize index types!");
00747         if (CE && CE->getOpcode() == Instruction::Sub &&
00748             CE->getOperand(0)->isNullValue()) {
00749           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
00750           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
00751           Res = ConstantExpr::getIntToPtr(Res, ResultTy);
00752           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
00753             Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
00754           return Res;
00755         }
00756       }
00757       return nullptr;
00758     }
00759 
00760   unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
00761   APInt Offset =
00762     APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
00763                                          makeArrayRef((Value *const*)
00764                                                         Ops.data() + 1,
00765                                                       Ops.size() - 1)));
00766   Ptr = StripPtrCastKeepAS(Ptr);
00767 
00768   // If this is a GEP of a GEP, fold it all into a single GEP.
00769   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
00770     SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
00771 
00772     // Do not try the incorporate the sub-GEP if some index is not a number.
00773     bool AllConstantInt = true;
00774     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
00775       if (!isa<ConstantInt>(NestedOps[i])) {
00776         AllConstantInt = false;
00777         break;
00778       }
00779     if (!AllConstantInt)
00780       break;
00781 
00782     Ptr = cast<Constant>(GEP->getOperand(0));
00783     Offset += APInt(BitWidth,
00784                     TD->getIndexedOffset(Ptr->getType(), NestedOps));
00785     Ptr = StripPtrCastKeepAS(Ptr);
00786   }
00787 
00788   // If the base value for this address is a literal integer value, fold the
00789   // getelementptr to the resulting integer value casted to the pointer type.
00790   APInt BasePtr(BitWidth, 0);
00791   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
00792     if (CE->getOpcode() == Instruction::IntToPtr) {
00793       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
00794         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
00795     }
00796   }
00797 
00798   if (Ptr->isNullValue() || BasePtr != 0) {
00799     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
00800     return ConstantExpr::getIntToPtr(C, ResultTy);
00801   }
00802 
00803   // Otherwise form a regular getelementptr. Recompute the indices so that
00804   // we eliminate over-indexing of the notional static type array bounds.
00805   // This makes it easy to determine if the getelementptr is "inbounds".
00806   // Also, this helps GlobalOpt do SROA on GlobalVariables.
00807   Type *Ty = Ptr->getType();
00808   assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
00809   SmallVector<Constant *, 32> NewIdxs;
00810 
00811   do {
00812     if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
00813       if (ATy->isPointerTy()) {
00814         // The only pointer indexing we'll do is on the first index of the GEP.
00815         if (!NewIdxs.empty())
00816           break;
00817 
00818         // Only handle pointers to sized types, not pointers to functions.
00819         if (!ATy->getElementType()->isSized())
00820           return nullptr;
00821       }
00822 
00823       // Determine which element of the array the offset points into.
00824       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
00825       if (ElemSize == 0)
00826         // The element size is 0. This may be [0 x Ty]*, so just use a zero
00827         // index for this level and proceed to the next level to see if it can
00828         // accommodate the offset.
00829         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
00830       else {
00831         // The element size is non-zero divide the offset by the element
00832         // size (rounding down), to compute the index at this level.
00833         APInt NewIdx = Offset.udiv(ElemSize);
00834         Offset -= NewIdx * ElemSize;
00835         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
00836       }
00837       Ty = ATy->getElementType();
00838     } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
00839       // If we end up with an offset that isn't valid for this struct type, we
00840       // can't re-form this GEP in a regular form, so bail out. The pointer
00841       // operand likely went through casts that are necessary to make the GEP
00842       // sensible.
00843       const StructLayout &SL = *TD->getStructLayout(STy);
00844       if (Offset.uge(SL.getSizeInBytes()))
00845         break;
00846 
00847       // Determine which field of the struct the offset points into. The
00848       // getZExtValue is fine as we've already ensured that the offset is
00849       // within the range representable by the StructLayout API.
00850       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
00851       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
00852                                          ElIdx));
00853       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
00854       Ty = STy->getTypeAtIndex(ElIdx);
00855     } else {
00856       // We've reached some non-indexable type.
00857       break;
00858     }
00859   } while (Ty != ResultElementTy);
00860 
00861   // If we haven't used up the entire offset by descending the static
00862   // type, then the offset is pointing into the middle of an indivisible
00863   // member, so we can't simplify it.
00864   if (Offset != 0)
00865     return nullptr;
00866 
00867   // Create a GEP.
00868   Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
00869   assert(C->getType()->getPointerElementType() == Ty &&
00870          "Computed GetElementPtr has unexpected type!");
00871 
00872   // If we ended up indexing a member with a type that doesn't match
00873   // the type of what the original indices indexed, add a cast.
00874   if (Ty != ResultElementTy)
00875     C = FoldBitCast(C, ResultTy, *TD);
00876 
00877   return C;
00878 }
00879 
00880 
00881 
00882 //===----------------------------------------------------------------------===//
00883 // Constant Folding public APIs
00884 //===----------------------------------------------------------------------===//
00885 
00886 /// Try to constant fold the specified instruction.
00887 /// If successful, the constant result is returned, if not, null is returned.
00888 /// Note that this fails if not all of the operands are constant.  Otherwise,
00889 /// this function can only fail when attempting to fold instructions like loads
00890 /// and stores, which have no constant expression form.
00891 Constant *llvm::ConstantFoldInstruction(Instruction *I,
00892                                         const DataLayout *TD,
00893                                         const TargetLibraryInfo *TLI) {
00894   // Handle PHI nodes quickly here...
00895   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00896     Constant *CommonValue = nullptr;
00897 
00898     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00899       Value *Incoming = PN->getIncomingValue(i);
00900       // If the incoming value is undef then skip it.  Note that while we could
00901       // skip the value if it is equal to the phi node itself we choose not to
00902       // because that would break the rule that constant folding only applies if
00903       // all operands are constants.
00904       if (isa<UndefValue>(Incoming))
00905         continue;
00906       // If the incoming value is not a constant, then give up.
00907       Constant *C = dyn_cast<Constant>(Incoming);
00908       if (!C)
00909         return nullptr;
00910       // Fold the PHI's operands.
00911       if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
00912         C = ConstantFoldConstantExpression(NewC, TD, TLI);
00913       // If the incoming value is a different constant to
00914       // the one we saw previously, then give up.
00915       if (CommonValue && C != CommonValue)
00916         return nullptr;
00917       CommonValue = C;
00918     }
00919 
00920 
00921     // If we reach here, all incoming values are the same constant or undef.
00922     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
00923   }
00924 
00925   // Scan the operand list, checking to see if they are all constants, if so,
00926   // hand off to ConstantFoldInstOperands.
00927   SmallVector<Constant*, 8> Ops;
00928   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
00929     Constant *Op = dyn_cast<Constant>(*i);
00930     if (!Op)
00931       return nullptr;  // All operands not constant!
00932 
00933     // Fold the Instruction's operands.
00934     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
00935       Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
00936 
00937     Ops.push_back(Op);
00938   }
00939 
00940   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
00941     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
00942                                            TD, TLI);
00943 
00944   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
00945     return ConstantFoldLoadInst(LI, TD);
00946 
00947   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
00948     return ConstantExpr::getInsertValue(
00949                                 cast<Constant>(IVI->getAggregateOperand()),
00950                                 cast<Constant>(IVI->getInsertedValueOperand()),
00951                                 IVI->getIndices());
00952   }
00953 
00954   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
00955     return ConstantExpr::getExtractValue(
00956                                     cast<Constant>(EVI->getAggregateOperand()),
00957                                     EVI->getIndices());
00958   }
00959 
00960   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
00961 }
00962 
00963 static Constant *
00964 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
00965                                    const TargetLibraryInfo *TLI,
00966                                    SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
00967   SmallVector<Constant *, 8> Ops;
00968   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
00969        ++i) {
00970     Constant *NewC = cast<Constant>(*i);
00971     // Recursively fold the ConstantExpr's operands. If we have already folded
00972     // a ConstantExpr, we don't have to process it again.
00973     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
00974       if (FoldedOps.insert(NewCE))
00975         NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
00976     }
00977     Ops.push_back(NewC);
00978   }
00979 
00980   if (CE->isCompare())
00981     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
00982                                            TD, TLI);
00983   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
00984 }
00985 
00986 /// Attempt to fold the constant expression
00987 /// using the specified DataLayout.  If successful, the constant result is
00988 /// result is returned, if not, null is returned.
00989 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
00990                                                const DataLayout *TD,
00991                                                const TargetLibraryInfo *TLI) {
00992   SmallPtrSet<ConstantExpr *, 4> FoldedOps;
00993   return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
00994 }
00995 
00996 /// Attempt to constant fold an instruction with the
00997 /// specified opcode and operands.  If successful, the constant result is
00998 /// returned, if not, null is returned.  Note that this function can fail when
00999 /// attempting to fold instructions like loads and stores, which have no
01000 /// constant expression form.
01001 ///
01002 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
01003 /// information, due to only being passed an opcode and operands. Constant
01004 /// folding using this function strips this information.
01005 ///
01006 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
01007                                          ArrayRef<Constant *> Ops,
01008                                          const DataLayout *TD,
01009                                          const TargetLibraryInfo *TLI) {
01010   // Handle easy binops first.
01011   if (Instruction::isBinaryOp(Opcode)) {
01012     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
01013       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
01014         return C;
01015     }
01016 
01017     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
01018   }
01019 
01020   switch (Opcode) {
01021   default: return nullptr;
01022   case Instruction::ICmp:
01023   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
01024   case Instruction::Call:
01025     if (Function *F = dyn_cast<Function>(Ops.back()))
01026       if (canConstantFoldCallTo(F))
01027         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
01028     return nullptr;
01029   case Instruction::PtrToInt:
01030     // If the input is a inttoptr, eliminate the pair.  This requires knowing
01031     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
01032     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
01033       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
01034         Constant *Input = CE->getOperand(0);
01035         unsigned InWidth = Input->getType()->getScalarSizeInBits();
01036         unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
01037         if (PtrWidth < InWidth) {
01038           Constant *Mask =
01039             ConstantInt::get(CE->getContext(),
01040                              APInt::getLowBitsSet(InWidth, PtrWidth));
01041           Input = ConstantExpr::getAnd(Input, Mask);
01042         }
01043         // Do a zext or trunc to get to the dest size.
01044         return ConstantExpr::getIntegerCast(Input, DestTy, false);
01045       }
01046     }
01047     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
01048   case Instruction::IntToPtr:
01049     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
01050     // the int size is >= the ptr size and the address spaces are the same.
01051     // This requires knowing the width of a pointer, so it can't be done in
01052     // ConstantExpr::getCast.
01053     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
01054       if (TD && CE->getOpcode() == Instruction::PtrToInt) {
01055         Constant *SrcPtr = CE->getOperand(0);
01056         unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
01057         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
01058 
01059         if (MidIntSize >= SrcPtrSize) {
01060           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
01061           if (SrcAS == DestTy->getPointerAddressSpace())
01062             return FoldBitCast(CE->getOperand(0), DestTy, *TD);
01063         }
01064       }
01065     }
01066 
01067     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
01068   case Instruction::Trunc:
01069   case Instruction::ZExt:
01070   case Instruction::SExt:
01071   case Instruction::FPTrunc:
01072   case Instruction::FPExt:
01073   case Instruction::UIToFP:
01074   case Instruction::SIToFP:
01075   case Instruction::FPToUI:
01076   case Instruction::FPToSI:
01077   case Instruction::AddrSpaceCast:
01078       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
01079   case Instruction::BitCast:
01080     if (TD)
01081       return FoldBitCast(Ops[0], DestTy, *TD);
01082     return ConstantExpr::getBitCast(Ops[0], DestTy);
01083   case Instruction::Select:
01084     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
01085   case Instruction::ExtractElement:
01086     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
01087   case Instruction::InsertElement:
01088     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
01089   case Instruction::ShuffleVector:
01090     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
01091   case Instruction::GetElementPtr:
01092     if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
01093       return C;
01094     if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
01095       return C;
01096 
01097     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
01098   }
01099 }
01100 
01101 /// Attempt to constant fold a compare
01102 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
01103 /// returns a constant expression of the specified operands.
01104 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
01105                                                 Constant *Ops0, Constant *Ops1,
01106                                                 const DataLayout *TD,
01107                                                 const TargetLibraryInfo *TLI) {
01108   // fold: icmp (inttoptr x), null         -> icmp x, 0
01109   // fold: icmp (ptrtoint x), 0            -> icmp x, null
01110   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
01111   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
01112   //
01113   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
01114   // around to know if bit truncation is happening.
01115   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
01116     if (TD && Ops1->isNullValue()) {
01117       if (CE0->getOpcode() == Instruction::IntToPtr) {
01118         Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
01119         // Convert the integer value to the right size to ensure we get the
01120         // proper extension or truncation.
01121         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
01122                                                    IntPtrTy, false);
01123         Constant *Null = Constant::getNullValue(C->getType());
01124         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
01125       }
01126 
01127       // Only do this transformation if the int is intptrty in size, otherwise
01128       // there is a truncation or extension that we aren't modeling.
01129       if (CE0->getOpcode() == Instruction::PtrToInt) {
01130         Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
01131         if (CE0->getType() == IntPtrTy) {
01132           Constant *C = CE0->getOperand(0);
01133           Constant *Null = Constant::getNullValue(C->getType());
01134           return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
01135         }
01136       }
01137     }
01138 
01139     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
01140       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
01141         if (CE0->getOpcode() == Instruction::IntToPtr) {
01142           Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
01143 
01144           // Convert the integer value to the right size to ensure we get the
01145           // proper extension or truncation.
01146           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
01147                                                       IntPtrTy, false);
01148           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
01149                                                       IntPtrTy, false);
01150           return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
01151         }
01152 
01153         // Only do this transformation if the int is intptrty in size, otherwise
01154         // there is a truncation or extension that we aren't modeling.
01155         if (CE0->getOpcode() == Instruction::PtrToInt) {
01156           Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
01157           if (CE0->getType() == IntPtrTy &&
01158               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
01159             return ConstantFoldCompareInstOperands(Predicate,
01160                                                    CE0->getOperand(0),
01161                                                    CE1->getOperand(0),
01162                                                    TD,
01163                                                    TLI);
01164           }
01165         }
01166       }
01167     }
01168 
01169     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
01170     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
01171     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
01172         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
01173       Constant *LHS =
01174         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
01175                                         TD, TLI);
01176       Constant *RHS =
01177         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
01178                                         TD, TLI);
01179       unsigned OpC =
01180         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
01181       Constant *Ops[] = { LHS, RHS };
01182       return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
01183     }
01184   }
01185 
01186   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
01187 }
01188 
01189 
01190 /// Given a constant and a getelementptr constantexpr, return the constant value
01191 /// being addressed by the constant expression, or null if something is funny
01192 /// and we can't decide.
01193 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
01194                                                        ConstantExpr *CE) {
01195   if (!CE->getOperand(1)->isNullValue())
01196     return nullptr;  // Do not allow stepping over the value!
01197 
01198   // Loop over all of the operands, tracking down which value we are
01199   // addressing.
01200   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
01201     C = C->getAggregateElement(CE->getOperand(i));
01202     if (!C)
01203       return nullptr;
01204   }
01205   return C;
01206 }
01207 
01208 /// Given a constant and getelementptr indices (with an *implied* zero pointer
01209 /// index that is not in the list), return the constant value being addressed by
01210 /// a virtual load, or null if something is funny and we can't decide.
01211 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
01212                                                   ArrayRef<Constant*> Indices) {
01213   // Loop over all of the operands, tracking down which value we are
01214   // addressing.
01215   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
01216     C = C->getAggregateElement(Indices[i]);
01217     if (!C)
01218       return nullptr;
01219   }
01220   return C;
01221 }
01222 
01223 
01224 //===----------------------------------------------------------------------===//
01225 //  Constant Folding for Calls
01226 //
01227 
01228 /// Return true if it's even possible to fold a call to the specified function.
01229 bool llvm::canConstantFoldCallTo(const Function *F) {
01230   switch (F->getIntrinsicID()) {
01231   case Intrinsic::fabs:
01232   case Intrinsic::minnum:
01233   case Intrinsic::maxnum:
01234   case Intrinsic::log:
01235   case Intrinsic::log2:
01236   case Intrinsic::log10:
01237   case Intrinsic::exp:
01238   case Intrinsic::exp2:
01239   case Intrinsic::floor:
01240   case Intrinsic::ceil:
01241   case Intrinsic::sqrt:
01242   case Intrinsic::pow:
01243   case Intrinsic::powi:
01244   case Intrinsic::bswap:
01245   case Intrinsic::ctpop:
01246   case Intrinsic::ctlz:
01247   case Intrinsic::cttz:
01248   case Intrinsic::fma:
01249   case Intrinsic::fmuladd:
01250   case Intrinsic::copysign:
01251   case Intrinsic::round:
01252   case Intrinsic::sadd_with_overflow:
01253   case Intrinsic::uadd_with_overflow:
01254   case Intrinsic::ssub_with_overflow:
01255   case Intrinsic::usub_with_overflow:
01256   case Intrinsic::smul_with_overflow:
01257   case Intrinsic::umul_with_overflow:
01258   case Intrinsic::convert_from_fp16:
01259   case Intrinsic::convert_to_fp16:
01260   case Intrinsic::x86_sse_cvtss2si:
01261   case Intrinsic::x86_sse_cvtss2si64:
01262   case Intrinsic::x86_sse_cvttss2si:
01263   case Intrinsic::x86_sse_cvttss2si64:
01264   case Intrinsic::x86_sse2_cvtsd2si:
01265   case Intrinsic::x86_sse2_cvtsd2si64:
01266   case Intrinsic::x86_sse2_cvttsd2si:
01267   case Intrinsic::x86_sse2_cvttsd2si64:
01268     return true;
01269   default:
01270     return false;
01271   case 0: break;
01272   }
01273 
01274   if (!F->hasName())
01275     return false;
01276   StringRef Name = F->getName();
01277 
01278   // In these cases, the check of the length is required.  We don't want to
01279   // return true for a name like "cos\0blah" which strcmp would return equal to
01280   // "cos", but has length 8.
01281   switch (Name[0]) {
01282   default: return false;
01283   case 'a':
01284     return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
01285   case 'c':
01286     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
01287   case 'e':
01288     return Name == "exp" || Name == "exp2";
01289   case 'f':
01290     return Name == "fabs" || Name == "fmod" || Name == "floor";
01291   case 'l':
01292     return Name == "log" || Name == "log10";
01293   case 'p':
01294     return Name == "pow";
01295   case 's':
01296     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
01297       Name == "sinf" || Name == "sqrtf";
01298   case 't':
01299     return Name == "tan" || Name == "tanh";
01300   }
01301 }
01302 
01303 static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
01304   if (Ty->isHalfTy()) {
01305     APFloat APF(V);
01306     bool unused;
01307     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
01308     return ConstantFP::get(Ty->getContext(), APF);
01309   }
01310   if (Ty->isFloatTy())
01311     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
01312   if (Ty->isDoubleTy())
01313     return ConstantFP::get(Ty->getContext(), APFloat(V));
01314   llvm_unreachable("Can only constant fold half/float/double");
01315 
01316 }
01317 
01318 namespace {
01319 /// Clear the floating-point exception state.
01320 static inline void llvm_fenv_clearexcept() {
01321 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
01322   feclearexcept(FE_ALL_EXCEPT);
01323 #endif
01324   errno = 0;
01325 }
01326 
01327 /// Test if a floating-point exception was raised.
01328 static inline bool llvm_fenv_testexcept() {
01329   int errno_val = errno;
01330   if (errno_val == ERANGE || errno_val == EDOM)
01331     return true;
01332 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
01333   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
01334     return true;
01335 #endif
01336   return false;
01337 }
01338 } // End namespace
01339 
01340 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
01341                                 Type *Ty) {
01342   llvm_fenv_clearexcept();
01343   V = NativeFP(V);
01344   if (llvm_fenv_testexcept()) {
01345     llvm_fenv_clearexcept();
01346     return nullptr;
01347   }
01348 
01349   return GetConstantFoldFPValue(V, Ty);
01350 }
01351 
01352 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
01353                                       double V, double W, Type *Ty) {
01354   llvm_fenv_clearexcept();
01355   V = NativeFP(V, W);
01356   if (llvm_fenv_testexcept()) {
01357     llvm_fenv_clearexcept();
01358     return nullptr;
01359   }
01360 
01361   return GetConstantFoldFPValue(V, Ty);
01362 }
01363 
01364 /// Attempt to fold an SSE floating point to integer conversion of a constant
01365 /// floating point. If roundTowardZero is false, the default IEEE rounding is
01366 /// used (toward nearest, ties to even). This matches the behavior of the
01367 /// non-truncating SSE instructions in the default rounding mode. The desired
01368 /// integer type Ty is used to select how many bits are available for the
01369 /// result. Returns null if the conversion cannot be performed, otherwise
01370 /// returns the Constant value resulting from the conversion.
01371 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
01372                                           bool roundTowardZero, Type *Ty) {
01373   // All of these conversion intrinsics form an integer of at most 64bits.
01374   unsigned ResultWidth = Ty->getIntegerBitWidth();
01375   assert(ResultWidth <= 64 &&
01376          "Can only constant fold conversions to 64 and 32 bit ints");
01377 
01378   uint64_t UIntVal;
01379   bool isExact = false;
01380   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
01381                                               : APFloat::rmNearestTiesToEven;
01382   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
01383                                                   /*isSigned=*/true, mode,
01384                                                   &isExact);
01385   if (status != APFloat::opOK && status != APFloat::opInexact)
01386     return nullptr;
01387   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
01388 }
01389 
01390 static double getValueAsDouble(ConstantFP *Op) {
01391   Type *Ty = Op->getType();
01392 
01393   if (Ty->isFloatTy())
01394     return Op->getValueAPF().convertToFloat();
01395 
01396   if (Ty->isDoubleTy())
01397     return Op->getValueAPF().convertToDouble();
01398 
01399   bool unused;
01400   APFloat APF = Op->getValueAPF();
01401   APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
01402   return APF.convertToDouble();
01403 }
01404 
01405 static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
01406                                         Type *Ty, ArrayRef<Constant *> Operands,
01407                                         const TargetLibraryInfo *TLI) {
01408   if (Operands.size() == 1) {
01409     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
01410       if (IntrinsicID == Intrinsic::convert_to_fp16) {
01411         APFloat Val(Op->getValueAPF());
01412 
01413         bool lost = false;
01414         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
01415 
01416         return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
01417       }
01418 
01419       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
01420         return nullptr;
01421 
01422       if (IntrinsicID == Intrinsic::round) {
01423         APFloat V = Op->getValueAPF();
01424         V.roundToIntegral(APFloat::rmNearestTiesToAway);
01425         return ConstantFP::get(Ty->getContext(), V);
01426       }
01427 
01428       /// We only fold functions with finite arguments. Folding NaN and inf is
01429       /// likely to be aborted with an exception anyway, and some host libms
01430       /// have known errors raising exceptions.
01431       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
01432         return nullptr;
01433 
01434       /// Currently APFloat versions of these functions do not exist, so we use
01435       /// the host native double versions.  Float versions are not called
01436       /// directly but for all these it is true (float)(f((double)arg)) ==
01437       /// f(arg).  Long double not supported yet.
01438       double V = getValueAsDouble(Op);
01439 
01440       switch (IntrinsicID) {
01441         default: break;
01442         case Intrinsic::fabs:
01443           return ConstantFoldFP(fabs, V, Ty);
01444 #if HAVE_LOG2
01445         case Intrinsic::log2:
01446           return ConstantFoldFP(log2, V, Ty);
01447 #endif
01448 #if HAVE_LOG
01449         case Intrinsic::log:
01450           return ConstantFoldFP(log, V, Ty);
01451 #endif
01452 #if HAVE_LOG10
01453         case Intrinsic::log10:
01454           return ConstantFoldFP(log10, V, Ty);
01455 #endif
01456 #if HAVE_EXP
01457         case Intrinsic::exp:
01458           return ConstantFoldFP(exp, V, Ty);
01459 #endif
01460 #if HAVE_EXP2
01461         case Intrinsic::exp2:
01462           return ConstantFoldFP(exp2, V, Ty);
01463 #endif
01464         case Intrinsic::floor:
01465           return ConstantFoldFP(floor, V, Ty);
01466         case Intrinsic::ceil:
01467           return ConstantFoldFP(ceil, V, Ty);
01468       }
01469 
01470       if (!TLI)
01471         return nullptr;
01472 
01473       switch (Name[0]) {
01474       case 'a':
01475         if (Name == "acos" && TLI->has(LibFunc::acos))
01476           return ConstantFoldFP(acos, V, Ty);
01477         else if (Name == "asin" && TLI->has(LibFunc::asin))
01478           return ConstantFoldFP(asin, V, Ty);
01479         else if (Name == "atan" && TLI->has(LibFunc::atan))
01480           return ConstantFoldFP(atan, V, Ty);
01481         break;
01482       case 'c':
01483         if (Name == "ceil" && TLI->has(LibFunc::ceil))
01484           return ConstantFoldFP(ceil, V, Ty);
01485         else if (Name == "cos" && TLI->has(LibFunc::cos))
01486           return ConstantFoldFP(cos, V, Ty);
01487         else if (Name == "cosh" && TLI->has(LibFunc::cosh))
01488           return ConstantFoldFP(cosh, V, Ty);
01489         else if (Name == "cosf" && TLI->has(LibFunc::cosf))
01490           return ConstantFoldFP(cos, V, Ty);
01491         break;
01492       case 'e':
01493         if (Name == "exp" && TLI->has(LibFunc::exp))
01494           return ConstantFoldFP(exp, V, Ty);
01495 
01496         if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
01497           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
01498           // C99 library.
01499           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
01500         }
01501         break;
01502       case 'f':
01503         if (Name == "fabs" && TLI->has(LibFunc::fabs))
01504           return ConstantFoldFP(fabs, V, Ty);
01505         else if (Name == "floor" && TLI->has(LibFunc::floor))
01506           return ConstantFoldFP(floor, V, Ty);
01507         break;
01508       case 'l':
01509         if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
01510           return ConstantFoldFP(log, V, Ty);
01511         else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
01512           return ConstantFoldFP(log10, V, Ty);
01513         else if (IntrinsicID == Intrinsic::sqrt &&
01514                  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
01515           if (V >= -0.0)
01516             return ConstantFoldFP(sqrt, V, Ty);
01517           else {
01518             // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
01519             // all guarantee or favor returning NaN - the square root of a
01520             // negative number is not defined for the LLVM sqrt intrinsic.
01521             // This is because the intrinsic should only be emitted in place of
01522             // libm's sqrt function when using "no-nans-fp-math".
01523             return UndefValue::get(Ty);
01524           }
01525         }
01526         break;
01527       case 's':
01528         if (Name == "sin" && TLI->has(LibFunc::sin))
01529           return ConstantFoldFP(sin, V, Ty);
01530         else if (Name == "sinh" && TLI->has(LibFunc::sinh))
01531           return ConstantFoldFP(sinh, V, Ty);
01532         else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
01533           return ConstantFoldFP(sqrt, V, Ty);
01534         else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
01535           return ConstantFoldFP(sqrt, V, Ty);
01536         else if (Name == "sinf" && TLI->has(LibFunc::sinf))
01537           return ConstantFoldFP(sin, V, Ty);
01538         break;
01539       case 't':
01540         if (Name == "tan" && TLI->has(LibFunc::tan))
01541           return ConstantFoldFP(tan, V, Ty);
01542         else if (Name == "tanh" && TLI->has(LibFunc::tanh))
01543           return ConstantFoldFP(tanh, V, Ty);
01544         break;
01545       default:
01546         break;
01547       }
01548       return nullptr;
01549     }
01550 
01551     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
01552       switch (IntrinsicID) {
01553       case Intrinsic::bswap:
01554         return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
01555       case Intrinsic::ctpop:
01556         return ConstantInt::get(Ty, Op->getValue().countPopulation());
01557       case Intrinsic::convert_from_fp16: {
01558         APFloat Val(APFloat::IEEEhalf, Op->getValue());
01559 
01560         bool lost = false;
01561         APFloat::opStatus status =
01562           Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
01563 
01564         // Conversion is always precise.
01565         (void)status;
01566         assert(status == APFloat::opOK && !lost &&
01567                "Precision lost during fp16 constfolding");
01568 
01569         return ConstantFP::get(Ty->getContext(), Val);
01570       }
01571       default:
01572         return nullptr;
01573       }
01574     }
01575 
01576     // Support ConstantVector in case we have an Undef in the top.
01577     if (isa<ConstantVector>(Operands[0]) ||
01578         isa<ConstantDataVector>(Operands[0])) {
01579       Constant *Op = cast<Constant>(Operands[0]);
01580       switch (IntrinsicID) {
01581       default: break;
01582       case Intrinsic::x86_sse_cvtss2si:
01583       case Intrinsic::x86_sse_cvtss2si64:
01584       case Intrinsic::x86_sse2_cvtsd2si:
01585       case Intrinsic::x86_sse2_cvtsd2si64:
01586         if (ConstantFP *FPOp =
01587               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
01588           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
01589                                           /*roundTowardZero=*/false, Ty);
01590       case Intrinsic::x86_sse_cvttss2si:
01591       case Intrinsic::x86_sse_cvttss2si64:
01592       case Intrinsic::x86_sse2_cvttsd2si:
01593       case Intrinsic::x86_sse2_cvttsd2si64:
01594         if (ConstantFP *FPOp =
01595               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
01596           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
01597                                           /*roundTowardZero=*/true, Ty);
01598       }
01599     }
01600 
01601     if (isa<UndefValue>(Operands[0])) {
01602       if (IntrinsicID == Intrinsic::bswap)
01603         return Operands[0];
01604       return nullptr;
01605     }
01606 
01607     return nullptr;
01608   }
01609 
01610   if (Operands.size() == 2) {
01611     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
01612       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
01613         return nullptr;
01614       double Op1V = getValueAsDouble(Op1);
01615 
01616       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
01617         if (Op2->getType() != Op1->getType())
01618           return nullptr;
01619 
01620         double Op2V = getValueAsDouble(Op2);
01621         if (IntrinsicID == Intrinsic::pow) {
01622           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
01623         }
01624         if (IntrinsicID == Intrinsic::copysign) {
01625           APFloat V1 = Op1->getValueAPF();
01626           APFloat V2 = Op2->getValueAPF();
01627           V1.copySign(V2);
01628           return ConstantFP::get(Ty->getContext(), V1);
01629         }
01630 
01631         if (IntrinsicID == Intrinsic::minnum) {
01632           const APFloat &C1 = Op1->getValueAPF();
01633           const APFloat &C2 = Op2->getValueAPF();
01634           return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
01635         }
01636 
01637         if (IntrinsicID == Intrinsic::maxnum) {
01638           const APFloat &C1 = Op1->getValueAPF();
01639           const APFloat &C2 = Op2->getValueAPF();
01640           return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
01641         }
01642 
01643         if (!TLI)
01644           return nullptr;
01645         if (Name == "pow" && TLI->has(LibFunc::pow))
01646           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
01647         if (Name == "fmod" && TLI->has(LibFunc::fmod))
01648           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
01649         if (Name == "atan2" && TLI->has(LibFunc::atan2))
01650           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
01651       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
01652         if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
01653           return ConstantFP::get(Ty->getContext(),
01654                                  APFloat((float)std::pow((float)Op1V,
01655                                                  (int)Op2C->getZExtValue())));
01656         if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
01657           return ConstantFP::get(Ty->getContext(),
01658                                  APFloat((float)std::pow((float)Op1V,
01659                                                  (int)Op2C->getZExtValue())));
01660         if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
01661           return ConstantFP::get(Ty->getContext(),
01662                                  APFloat((double)std::pow((double)Op1V,
01663                                                    (int)Op2C->getZExtValue())));
01664       }
01665       return nullptr;
01666     }
01667 
01668     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
01669       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
01670         switch (IntrinsicID) {
01671         default: break;
01672         case Intrinsic::sadd_with_overflow:
01673         case Intrinsic::uadd_with_overflow:
01674         case Intrinsic::ssub_with_overflow:
01675         case Intrinsic::usub_with_overflow:
01676         case Intrinsic::smul_with_overflow:
01677         case Intrinsic::umul_with_overflow: {
01678           APInt Res;
01679           bool Overflow;
01680           switch (IntrinsicID) {
01681           default: llvm_unreachable("Invalid case");
01682           case Intrinsic::sadd_with_overflow:
01683             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
01684             break;
01685           case Intrinsic::uadd_with_overflow:
01686             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
01687             break;
01688           case Intrinsic::ssub_with_overflow:
01689             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
01690             break;
01691           case Intrinsic::usub_with_overflow:
01692             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
01693             break;
01694           case Intrinsic::smul_with_overflow:
01695             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
01696             break;
01697           case Intrinsic::umul_with_overflow:
01698             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
01699             break;
01700           }
01701           Constant *Ops[] = {
01702             ConstantInt::get(Ty->getContext(), Res),
01703             ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
01704           };
01705           return ConstantStruct::get(cast<StructType>(Ty), Ops);
01706         }
01707         case Intrinsic::cttz:
01708           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
01709             return UndefValue::get(Ty);
01710           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
01711         case Intrinsic::ctlz:
01712           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
01713             return UndefValue::get(Ty);
01714           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
01715         }
01716       }
01717 
01718       return nullptr;
01719     }
01720     return nullptr;
01721   }
01722 
01723   if (Operands.size() != 3)
01724     return nullptr;
01725 
01726   if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
01727     if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
01728       if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
01729         switch (IntrinsicID) {
01730         default: break;
01731         case Intrinsic::fma:
01732         case Intrinsic::fmuladd: {
01733           APFloat V = Op1->getValueAPF();
01734           APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
01735                                                    Op3->getValueAPF(),
01736                                                    APFloat::rmNearestTiesToEven);
01737           if (s != APFloat::opInvalidOp)
01738             return ConstantFP::get(Ty->getContext(), V);
01739 
01740           return nullptr;
01741         }
01742         }
01743       }
01744     }
01745   }
01746 
01747   return nullptr;
01748 }
01749 
01750 static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
01751                                         VectorType *VTy,
01752                                         ArrayRef<Constant *> Operands,
01753                                         const TargetLibraryInfo *TLI) {
01754   SmallVector<Constant *, 4> Result(VTy->getNumElements());
01755   SmallVector<Constant *, 4> Lane(Operands.size());
01756   Type *Ty = VTy->getElementType();
01757 
01758   for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
01759     // Gather a column of constants.
01760     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
01761       Constant *Agg = Operands[J]->getAggregateElement(I);
01762       if (!Agg)
01763         return nullptr;
01764 
01765       Lane[J] = Agg;
01766     }
01767 
01768     // Use the regular scalar folding to simplify this column.
01769     Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
01770     if (!Folded)
01771       return nullptr;
01772     Result[I] = Folded;
01773   }
01774 
01775   return ConstantVector::get(Result);
01776 }
01777 
01778 /// Attempt to constant fold a call to the specified function
01779 /// with the specified arguments, returning null if unsuccessful.
01780 Constant *
01781 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
01782                        const TargetLibraryInfo *TLI) {
01783   if (!F->hasName())
01784     return nullptr;
01785   StringRef Name = F->getName();
01786 
01787   Type *Ty = F->getReturnType();
01788 
01789   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
01790     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
01791 
01792   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
01793 }