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