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