Add a Constant version of stripPointerCasts.
[oota-llvm.git] / lib / Analysis / ConstantFolding.cpp
1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic IR ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // DataLayout information. These functions cannot go in IR due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FEnv.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Target/TargetLibraryInfo.h"
37 #include <cerrno>
38 #include <cmath>
39 using namespace llvm;
40
41 //===----------------------------------------------------------------------===//
42 // Constant Folding internal helper functions
43 //===----------------------------------------------------------------------===//
44
45 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
46 /// DataLayout.  This always returns a non-null constant, but it may be a
47 /// ConstantExpr if unfoldable.
48 static Constant *FoldBitCast(Constant *C, Type *DestTy,
49                              const DataLayout &TD) {
50   // Catch the obvious splat cases.
51   if (C->isNullValue() && !DestTy->isX86_MMXTy())
52     return Constant::getNullValue(DestTy);
53   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
54     return Constant::getAllOnesValue(DestTy);
55
56   // Handle a vector->integer cast.
57   if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
58     VectorType *VTy = dyn_cast<VectorType>(C->getType());
59     if (!VTy)
60       return ConstantExpr::getBitCast(C, DestTy);
61
62     unsigned NumSrcElts = VTy->getNumElements();
63     Type *SrcEltTy = VTy->getElementType();
64
65     // If the vector is a vector of floating point, convert it to vector of int
66     // to simplify things.
67     if (SrcEltTy->isFloatingPointTy()) {
68       unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
69       Type *SrcIVTy =
70         VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
71       // Ask IR to do the conversion now that #elts line up.
72       C = ConstantExpr::getBitCast(C, SrcIVTy);
73     }
74
75     ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
76     if (!CDV)
77       return ConstantExpr::getBitCast(C, DestTy);
78
79     // Now that we know that the input value is a vector of integers, just shift
80     // and insert them into our result.
81     unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
82     APInt Result(IT->getBitWidth(), 0);
83     for (unsigned i = 0; i != NumSrcElts; ++i) {
84       Result <<= BitShift;
85       if (TD.isLittleEndian())
86         Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
87       else
88         Result |= CDV->getElementAsInteger(i);
89     }
90
91     return ConstantInt::get(IT, Result);
92   }
93
94   // The code below only handles casts to vectors currently.
95   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
96   if (!DestVTy)
97     return ConstantExpr::getBitCast(C, DestTy);
98
99   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
100   // vector so the code below can handle it uniformly.
101   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
102     Constant *Ops = C; // don't take the address of C!
103     return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
104   }
105
106   // If this is a bitcast from constant vector -> vector, fold it.
107   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
108     return ConstantExpr::getBitCast(C, DestTy);
109
110   // If the element types match, IR can fold it.
111   unsigned NumDstElt = DestVTy->getNumElements();
112   unsigned NumSrcElt = C->getType()->getVectorNumElements();
113   if (NumDstElt == NumSrcElt)
114     return ConstantExpr::getBitCast(C, DestTy);
115
116   Type *SrcEltTy = C->getType()->getVectorElementType();
117   Type *DstEltTy = DestVTy->getElementType();
118
119   // Otherwise, we're changing the number of elements in a vector, which
120   // requires endianness information to do the right thing.  For example,
121   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
122   // folds to (little endian):
123   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
124   // and to (big endian):
125   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
126
127   // First thing is first.  We only want to think about integer here, so if
128   // we have something in FP form, recast it as integer.
129   if (DstEltTy->isFloatingPointTy()) {
130     // Fold to an vector of integers with same size as our FP type.
131     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
132     Type *DestIVTy =
133       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
134     // Recursively handle this integer conversion, if possible.
135     C = FoldBitCast(C, DestIVTy, TD);
136
137     // Finally, IR can handle this now that #elts line up.
138     return ConstantExpr::getBitCast(C, DestTy);
139   }
140
141   // Okay, we know the destination is integer, if the input is FP, convert
142   // it to integer first.
143   if (SrcEltTy->isFloatingPointTy()) {
144     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
145     Type *SrcIVTy =
146       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
147     // Ask IR to do the conversion now that #elts line up.
148     C = ConstantExpr::getBitCast(C, SrcIVTy);
149     // If IR wasn't able to fold it, bail out.
150     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
151         !isa<ConstantDataVector>(C))
152       return C;
153   }
154
155   // Now we know that the input and output vectors are both integer vectors
156   // of the same size, and that their #elements is not the same.  Do the
157   // conversion here, which depends on whether the input or output has
158   // more elements.
159   bool isLittleEndian = TD.isLittleEndian();
160
161   SmallVector<Constant*, 32> Result;
162   if (NumDstElt < NumSrcElt) {
163     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
164     Constant *Zero = Constant::getNullValue(DstEltTy);
165     unsigned Ratio = NumSrcElt/NumDstElt;
166     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
167     unsigned SrcElt = 0;
168     for (unsigned i = 0; i != NumDstElt; ++i) {
169       // Build each element of the result.
170       Constant *Elt = Zero;
171       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
172       for (unsigned j = 0; j != Ratio; ++j) {
173         Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
174         if (!Src)  // Reject constantexpr elements.
175           return ConstantExpr::getBitCast(C, DestTy);
176
177         // Zero extend the element to the right size.
178         Src = ConstantExpr::getZExt(Src, Elt->getType());
179
180         // Shift it to the right place, depending on endianness.
181         Src = ConstantExpr::getShl(Src,
182                                    ConstantInt::get(Src->getType(), ShiftAmt));
183         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
184
185         // Mix it in.
186         Elt = ConstantExpr::getOr(Elt, Src);
187       }
188       Result.push_back(Elt);
189     }
190     return ConstantVector::get(Result);
191   }
192
193   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
194   unsigned Ratio = NumDstElt/NumSrcElt;
195   unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
196
197   // Loop over each source value, expanding into multiple results.
198   for (unsigned i = 0; i != NumSrcElt; ++i) {
199     Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
200     if (!Src)  // Reject constantexpr elements.
201       return ConstantExpr::getBitCast(C, DestTy);
202
203     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
204     for (unsigned j = 0; j != Ratio; ++j) {
205       // Shift the piece of the value into the right place, depending on
206       // endianness.
207       Constant *Elt = ConstantExpr::getLShr(Src,
208                                   ConstantInt::get(Src->getType(), ShiftAmt));
209       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
210
211       // Truncate and remember this piece.
212       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
213     }
214   }
215
216   return ConstantVector::get(Result);
217 }
218
219
220 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
221 /// from a global, return the global and the constant.  Because of
222 /// constantexprs, this function is recursive.
223 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
224                                        APInt &Offset, const DataLayout &TD) {
225   // Trivial case, constant is the global.
226   if ((GV = dyn_cast<GlobalValue>(C))) {
227     unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
228     Offset = APInt(BitWidth, 0);
229     return true;
230   }
231
232   // Otherwise, if this isn't a constant expr, bail out.
233   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
234   if (!CE) return false;
235
236   // Look through ptr->int and ptr->ptr casts.
237   if (CE->getOpcode() == Instruction::PtrToInt ||
238       CE->getOpcode() == Instruction::BitCast)
239     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
240
241   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
242   GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
243   if (!GEP)
244     return false;
245
246   unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
247   APInt TmpOffset(BitWidth, 0);
248
249   // If the base isn't a global+constant, we aren't either.
250   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
251     return false;
252
253   // Otherwise, add any offset that our operands provide.
254   if (!GEP->accumulateConstantOffset(TD, TmpOffset))
255     return false;
256
257   Offset = TmpOffset;
258   return true;
259 }
260
261 /// ReadDataFromGlobal - Recursive helper to read bits out of global.  C is the
262 /// constant being copied out of. ByteOffset is an offset into C.  CurPtr is the
263 /// pointer to copy results into and BytesLeft is the number of bytes left in
264 /// the CurPtr buffer.  TD is the target data.
265 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
266                                unsigned char *CurPtr, unsigned BytesLeft,
267                                const DataLayout &TD) {
268   assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
269          "Out of range access");
270
271   // If this element is zero or undefined, we can just return since *CurPtr is
272   // zero initialized.
273   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
274     return true;
275
276   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
277     if (CI->getBitWidth() > 64 ||
278         (CI->getBitWidth() & 7) != 0)
279       return false;
280
281     uint64_t Val = CI->getZExtValue();
282     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
283
284     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
285       int n = ByteOffset;
286       if (!TD.isLittleEndian())
287         n = IntBytes - n - 1;
288       CurPtr[i] = (unsigned char)(Val >> (n * 8));
289       ++ByteOffset;
290     }
291     return true;
292   }
293
294   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
295     if (CFP->getType()->isDoubleTy()) {
296       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
297       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
298     }
299     if (CFP->getType()->isFloatTy()){
300       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
301       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
302     }
303     if (CFP->getType()->isHalfTy()){
304       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
305       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
306     }
307     return false;
308   }
309
310   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
311     const StructLayout *SL = TD.getStructLayout(CS->getType());
312     unsigned Index = SL->getElementContainingOffset(ByteOffset);
313     uint64_t CurEltOffset = SL->getElementOffset(Index);
314     ByteOffset -= CurEltOffset;
315
316     while (1) {
317       // If the element access is to the element itself and not to tail padding,
318       // read the bytes from the element.
319       uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
320
321       if (ByteOffset < EltSize &&
322           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
323                               BytesLeft, TD))
324         return false;
325
326       ++Index;
327
328       // Check to see if we read from the last struct element, if so we're done.
329       if (Index == CS->getType()->getNumElements())
330         return true;
331
332       // If we read all of the bytes we needed from this element we're done.
333       uint64_t NextEltOffset = SL->getElementOffset(Index);
334
335       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
336         return true;
337
338       // Move to the next element of the struct.
339       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
340       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
341       ByteOffset = 0;
342       CurEltOffset = NextEltOffset;
343     }
344     // not reached.
345   }
346
347   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
348       isa<ConstantDataSequential>(C)) {
349     Type *EltTy = C->getType()->getSequentialElementType();
350     uint64_t EltSize = TD.getTypeAllocSize(EltTy);
351     uint64_t Index = ByteOffset / EltSize;
352     uint64_t Offset = ByteOffset - Index * EltSize;
353     uint64_t NumElts;
354     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
355       NumElts = AT->getNumElements();
356     else
357       NumElts = C->getType()->getVectorNumElements();
358
359     for (; Index != NumElts; ++Index) {
360       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
361                               BytesLeft, TD))
362         return false;
363
364       uint64_t BytesWritten = EltSize - Offset;
365       assert(BytesWritten <= EltSize && "Not indexing into this element?");
366       if (BytesWritten >= BytesLeft)
367         return true;
368
369       Offset = 0;
370       BytesLeft -= BytesWritten;
371       CurPtr += BytesWritten;
372     }
373     return true;
374   }
375
376   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
377     if (CE->getOpcode() == Instruction::IntToPtr &&
378         CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
379       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
380                                 BytesLeft, TD);
381     }
382   }
383
384   // Otherwise, unknown initializer type.
385   return false;
386 }
387
388 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
389                                                  const DataLayout &TD) {
390   PointerType *PTy = cast<PointerType>(C->getType());
391   Type *LoadTy = PTy->getElementType();
392   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
393
394   // If this isn't an integer load we can't fold it directly.
395   if (!IntType) {
396     unsigned AS = PTy->getAddressSpace();
397
398     // If this is a float/double load, we can try folding it as an int32/64 load
399     // and then bitcast the result.  This can be useful for union cases.  Note
400     // that address spaces don't matter here since we're not going to result in
401     // an actual new load.
402     Type *MapTy;
403     if (LoadTy->isHalfTy())
404       MapTy = Type::getInt16PtrTy(C->getContext(), AS);
405     else if (LoadTy->isFloatTy())
406       MapTy = Type::getInt32PtrTy(C->getContext(), AS);
407     else if (LoadTy->isDoubleTy())
408       MapTy = Type::getInt64PtrTy(C->getContext(), AS);
409     else if (LoadTy->isVectorTy()) {
410       MapTy = PointerType::getIntNPtrTy(C->getContext(),
411                                         TD.getTypeAllocSizeInBits(LoadTy),
412                                         AS);
413     } else
414       return nullptr;
415
416     C = FoldBitCast(C, MapTy, TD);
417     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
418       return FoldBitCast(Res, LoadTy, TD);
419     return nullptr;
420   }
421
422   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
423   if (BytesLoaded > 32 || BytesLoaded == 0)
424     return nullptr;
425
426   GlobalValue *GVal;
427   APInt Offset;
428   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
429     return nullptr;
430
431   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
432   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
433       !GV->getInitializer()->getType()->isSized())
434     return nullptr;
435
436   // If we're loading off the beginning of the global, some bytes may be valid,
437   // but we don't try to handle this.
438   if (Offset.isNegative())
439     return nullptr;
440
441   // If we're not accessing anything in this constant, the result is undefined.
442   if (Offset.getZExtValue() >=
443       TD.getTypeAllocSize(GV->getInitializer()->getType()))
444     return UndefValue::get(IntType);
445
446   unsigned char RawBytes[32] = {0};
447   if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
448                           BytesLoaded, TD))
449     return nullptr;
450
451   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
452   if (TD.isLittleEndian()) {
453     ResultVal = RawBytes[BytesLoaded - 1];
454     for (unsigned i = 1; i != BytesLoaded; ++i) {
455       ResultVal <<= 8;
456       ResultVal |= RawBytes[BytesLoaded - 1 - i];
457     }
458   } else {
459     ResultVal = RawBytes[0];
460     for (unsigned i = 1; i != BytesLoaded; ++i) {
461       ResultVal <<= 8;
462       ResultVal |= RawBytes[i];
463     }
464   }
465
466   return ConstantInt::get(IntType->getContext(), ResultVal);
467 }
468
469 static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
470                                                 const DataLayout *DL) {
471   if (!DL)
472     return nullptr;
473   auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
474   if (!DestPtrTy)
475     return nullptr;
476   Type *DestTy = DestPtrTy->getElementType();
477
478   Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
479   if (!C)
480     return nullptr;
481
482   do {
483     Type *SrcTy = C->getType();
484
485     // If the type sizes are the same and a cast is legal, just directly
486     // cast the constant.
487     if (DL->getTypeSizeInBits(DestTy) == DL->getTypeSizeInBits(SrcTy)) {
488       Instruction::CastOps Cast = Instruction::BitCast;
489       // If we are going from a pointer to int or vice versa, we spell the cast
490       // differently.
491       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
492         Cast = Instruction::IntToPtr;
493       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
494         Cast = Instruction::PtrToInt;
495
496       if (CastInst::castIsValid(Cast, C, DestTy))
497         return ConstantExpr::getCast(Cast, C, DestTy);
498     }
499
500     // If this isn't an aggregate type, there is nothing we can do to drill down
501     // and find a bitcastable constant.
502     if (!SrcTy->isAggregateType())
503       return nullptr;
504
505     // We're simulating a load through a pointer that was bitcast to point to
506     // a different type, so we can try to walk down through the initial
507     // elements of an aggregate to see if some part of th e aggregate is
508     // castable to implement the "load" semantic model.
509     C = C->getAggregateElement(0u);
510   } while (C);
511
512   return nullptr;
513 }
514
515 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
516 /// produce if it is constant and determinable.  If this is not determinable,
517 /// return null.
518 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
519                                              const DataLayout *TD) {
520   // First, try the easy cases:
521   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
522     if (GV->isConstant() && GV->hasDefinitiveInitializer())
523       return GV->getInitializer();
524
525   // If the loaded value isn't a constant expr, we can't handle it.
526   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
527   if (!CE)
528     return nullptr;
529
530   if (CE->getOpcode() == Instruction::GetElementPtr) {
531     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
532       if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
533         if (Constant *V =
534              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
535           return V;
536       }
537     }
538   }
539
540   if (CE->getOpcode() == Instruction::BitCast)
541     if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, TD))
542       return LoadedC;
543
544   // Instead of loading constant c string, use corresponding integer value
545   // directly if string length is small enough.
546   StringRef Str;
547   if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
548     unsigned StrLen = Str.size();
549     Type *Ty = cast<PointerType>(CE->getType())->getElementType();
550     unsigned NumBits = Ty->getPrimitiveSizeInBits();
551     // Replace load with immediate integer if the result is an integer or fp
552     // value.
553     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
554         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
555       APInt StrVal(NumBits, 0);
556       APInt SingleChar(NumBits, 0);
557       if (TD->isLittleEndian()) {
558         for (signed i = StrLen-1; i >= 0; i--) {
559           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
560           StrVal = (StrVal << 8) | SingleChar;
561         }
562       } else {
563         for (unsigned i = 0; i < StrLen; i++) {
564           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
565           StrVal = (StrVal << 8) | SingleChar;
566         }
567         // Append NULL at the end.
568         SingleChar = 0;
569         StrVal = (StrVal << 8) | SingleChar;
570       }
571
572       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
573       if (Ty->isFloatingPointTy())
574         Res = ConstantExpr::getBitCast(Res, Ty);
575       return Res;
576     }
577   }
578
579   // If this load comes from anywhere in a constant global, and if the global
580   // is all undef or zero, we know what it loads.
581   if (GlobalVariable *GV =
582         dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
583     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
584       Type *ResTy = cast<PointerType>(C->getType())->getElementType();
585       if (GV->getInitializer()->isNullValue())
586         return Constant::getNullValue(ResTy);
587       if (isa<UndefValue>(GV->getInitializer()))
588         return UndefValue::get(ResTy);
589     }
590   }
591
592   // Try hard to fold loads from bitcasted strange and non-type-safe things.
593   if (TD)
594     return FoldReinterpretLoadFromConstPtr(CE, *TD);
595   return nullptr;
596 }
597
598 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
599   if (LI->isVolatile()) return nullptr;
600
601   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
602     return ConstantFoldLoadFromConstPtr(C, TD);
603
604   return nullptr;
605 }
606
607 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
608 /// Attempt to symbolically evaluate the result of a binary operator merging
609 /// these together.  If target data info is available, it is provided as DL,
610 /// otherwise DL is null.
611 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
612                                            Constant *Op1, const DataLayout *DL){
613   // SROA
614
615   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
616   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
617   // bits.
618
619
620   if (Opc == Instruction::And && DL) {
621     unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
622     APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
623     APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
624     computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
625     computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
626     if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
627       // All the bits of Op0 that the 'and' could be masking are already zero.
628       return Op0;
629     }
630     if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
631       // All the bits of Op1 that the 'and' could be masking are already zero.
632       return Op1;
633     }
634
635     APInt KnownZero = KnownZero0 | KnownZero1;
636     APInt KnownOne = KnownOne0 & KnownOne1;
637     if ((KnownZero | KnownOne).isAllOnesValue()) {
638       return ConstantInt::get(Op0->getType(), KnownOne);
639     }
640   }
641
642   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
643   // constant.  This happens frequently when iterating over a global array.
644   if (Opc == Instruction::Sub && DL) {
645     GlobalValue *GV1, *GV2;
646     APInt Offs1, Offs2;
647
648     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
649       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
650           GV1 == GV2) {
651         unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
652
653         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
654         // PtrToInt may change the bitwidth so we have convert to the right size
655         // first.
656         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
657                                                 Offs2.zextOrTrunc(OpSize));
658       }
659   }
660
661   return nullptr;
662 }
663
664 /// CastGEPIndices - If array indices are not pointer-sized integers,
665 /// explicitly cast them so that they aren't implicitly casted by the
666 /// getelementptr.
667 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
668                                 Type *ResultTy, const DataLayout *TD,
669                                 const TargetLibraryInfo *TLI) {
670   if (!TD)
671     return nullptr;
672
673   Type *IntPtrTy = TD->getIntPtrType(ResultTy);
674
675   bool Any = false;
676   SmallVector<Constant*, 32> NewIdxs;
677   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
678     if ((i == 1 ||
679          !isa<StructType>(GetElementPtrInst::getIndexedType(
680                             Ops[0]->getType(),
681                             Ops.slice(1, i - 1)))) &&
682         Ops[i]->getType() != IntPtrTy) {
683       Any = true;
684       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
685                                                                       true,
686                                                                       IntPtrTy,
687                                                                       true),
688                                               Ops[i], IntPtrTy));
689     } else
690       NewIdxs.push_back(Ops[i]);
691   }
692
693   if (!Any)
694     return nullptr;
695
696   Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
697   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
698     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
699       C = Folded;
700   }
701
702   return C;
703 }
704
705 /// Strip the pointer casts, but preserve the address space information.
706 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
707   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
708   PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
709   Ptr = Ptr->stripPointerCasts();
710   PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
711
712   // Preserve the address space number of the pointer.
713   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
714     NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
715       OldPtrTy->getAddressSpace());
716     Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
717   }
718   return Ptr;
719 }
720
721 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
722 /// constant expression, do so.
723 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
724                                          Type *ResultTy, const DataLayout *TD,
725                                          const TargetLibraryInfo *TLI) {
726   Constant *Ptr = Ops[0];
727   if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
728       !Ptr->getType()->isPointerTy())
729     return nullptr;
730
731   Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
732   Type *ResultElementTy = ResultTy->getPointerElementType();
733
734   // If this is a constant expr gep that is effectively computing an
735   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
736   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
737     if (!isa<ConstantInt>(Ops[i])) {
738
739       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
740       // "inttoptr (sub (ptrtoint Ptr), V)"
741       if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
742         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
743         assert((!CE || CE->getType() == IntPtrTy) &&
744                "CastGEPIndices didn't canonicalize index types!");
745         if (CE && CE->getOpcode() == Instruction::Sub &&
746             CE->getOperand(0)->isNullValue()) {
747           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
748           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
749           Res = ConstantExpr::getIntToPtr(Res, ResultTy);
750           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
751             Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
752           return Res;
753         }
754       }
755       return nullptr;
756     }
757
758   unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
759   APInt Offset =
760     APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
761                                          makeArrayRef((Value *const*)
762                                                         Ops.data() + 1,
763                                                       Ops.size() - 1)));
764   Ptr = StripPtrCastKeepAS(Ptr);
765
766   // If this is a GEP of a GEP, fold it all into a single GEP.
767   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
768     SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
769
770     // Do not try the incorporate the sub-GEP if some index is not a number.
771     bool AllConstantInt = true;
772     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
773       if (!isa<ConstantInt>(NestedOps[i])) {
774         AllConstantInt = false;
775         break;
776       }
777     if (!AllConstantInt)
778       break;
779
780     Ptr = cast<Constant>(GEP->getOperand(0));
781     Offset += APInt(BitWidth,
782                     TD->getIndexedOffset(Ptr->getType(), NestedOps));
783     Ptr = StripPtrCastKeepAS(Ptr);
784   }
785
786   // If the base value for this address is a literal integer value, fold the
787   // getelementptr to the resulting integer value casted to the pointer type.
788   APInt BasePtr(BitWidth, 0);
789   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
790     if (CE->getOpcode() == Instruction::IntToPtr) {
791       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
792         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
793     }
794   }
795
796   if (Ptr->isNullValue() || BasePtr != 0) {
797     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
798     return ConstantExpr::getIntToPtr(C, ResultTy);
799   }
800
801   // Otherwise form a regular getelementptr. Recompute the indices so that
802   // we eliminate over-indexing of the notional static type array bounds.
803   // This makes it easy to determine if the getelementptr is "inbounds".
804   // Also, this helps GlobalOpt do SROA on GlobalVariables.
805   Type *Ty = Ptr->getType();
806   assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
807   SmallVector<Constant *, 32> NewIdxs;
808
809   do {
810     if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
811       if (ATy->isPointerTy()) {
812         // The only pointer indexing we'll do is on the first index of the GEP.
813         if (!NewIdxs.empty())
814           break;
815
816         // Only handle pointers to sized types, not pointers to functions.
817         if (!ATy->getElementType()->isSized())
818           return nullptr;
819       }
820
821       // Determine which element of the array the offset points into.
822       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
823       if (ElemSize == 0)
824         // The element size is 0. This may be [0 x Ty]*, so just use a zero
825         // index for this level and proceed to the next level to see if it can
826         // accommodate the offset.
827         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
828       else {
829         // The element size is non-zero divide the offset by the element
830         // size (rounding down), to compute the index at this level.
831         APInt NewIdx = Offset.udiv(ElemSize);
832         Offset -= NewIdx * ElemSize;
833         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
834       }
835       Ty = ATy->getElementType();
836     } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
837       // If we end up with an offset that isn't valid for this struct type, we
838       // can't re-form this GEP in a regular form, so bail out. The pointer
839       // operand likely went through casts that are necessary to make the GEP
840       // sensible.
841       const StructLayout &SL = *TD->getStructLayout(STy);
842       if (Offset.uge(SL.getSizeInBytes()))
843         break;
844
845       // Determine which field of the struct the offset points into. The
846       // getZExtValue is fine as we've already ensured that the offset is
847       // within the range representable by the StructLayout API.
848       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
849       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
850                                          ElIdx));
851       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
852       Ty = STy->getTypeAtIndex(ElIdx);
853     } else {
854       // We've reached some non-indexable type.
855       break;
856     }
857   } while (Ty != ResultElementTy);
858
859   // If we haven't used up the entire offset by descending the static
860   // type, then the offset is pointing into the middle of an indivisible
861   // member, so we can't simplify it.
862   if (Offset != 0)
863     return nullptr;
864
865   // Create a GEP.
866   Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
867   assert(C->getType()->getPointerElementType() == Ty &&
868          "Computed GetElementPtr has unexpected type!");
869
870   // If we ended up indexing a member with a type that doesn't match
871   // the type of what the original indices indexed, add a cast.
872   if (Ty != ResultElementTy)
873     C = FoldBitCast(C, ResultTy, *TD);
874
875   return C;
876 }
877
878
879
880 //===----------------------------------------------------------------------===//
881 // Constant Folding public APIs
882 //===----------------------------------------------------------------------===//
883
884 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
885 /// If successful, the constant result is returned, if not, null is returned.
886 /// Note that this fails if not all of the operands are constant.  Otherwise,
887 /// this function can only fail when attempting to fold instructions like loads
888 /// and stores, which have no constant expression form.
889 Constant *llvm::ConstantFoldInstruction(Instruction *I,
890                                         const DataLayout *TD,
891                                         const TargetLibraryInfo *TLI) {
892   // Handle PHI nodes quickly here...
893   if (PHINode *PN = dyn_cast<PHINode>(I)) {
894     Constant *CommonValue = nullptr;
895
896     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
897       Value *Incoming = PN->getIncomingValue(i);
898       // If the incoming value is undef then skip it.  Note that while we could
899       // skip the value if it is equal to the phi node itself we choose not to
900       // because that would break the rule that constant folding only applies if
901       // all operands are constants.
902       if (isa<UndefValue>(Incoming))
903         continue;
904       // If the incoming value is not a constant, then give up.
905       Constant *C = dyn_cast<Constant>(Incoming);
906       if (!C)
907         return nullptr;
908       // Fold the PHI's operands.
909       if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
910         C = ConstantFoldConstantExpression(NewC, TD, TLI);
911       // If the incoming value is a different constant to
912       // the one we saw previously, then give up.
913       if (CommonValue && C != CommonValue)
914         return nullptr;
915       CommonValue = C;
916     }
917
918
919     // If we reach here, all incoming values are the same constant or undef.
920     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
921   }
922
923   // Scan the operand list, checking to see if they are all constants, if so,
924   // hand off to ConstantFoldInstOperands.
925   SmallVector<Constant*, 8> Ops;
926   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
927     Constant *Op = dyn_cast<Constant>(*i);
928     if (!Op)
929       return nullptr;  // All operands not constant!
930
931     // Fold the Instruction's operands.
932     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
933       Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
934
935     Ops.push_back(Op);
936   }
937
938   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
939     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
940                                            TD, TLI);
941
942   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
943     return ConstantFoldLoadInst(LI, TD);
944
945   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
946     return ConstantExpr::getInsertValue(
947                                 cast<Constant>(IVI->getAggregateOperand()),
948                                 cast<Constant>(IVI->getInsertedValueOperand()),
949                                 IVI->getIndices());
950   }
951
952   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
953     return ConstantExpr::getExtractValue(
954                                     cast<Constant>(EVI->getAggregateOperand()),
955                                     EVI->getIndices());
956   }
957
958   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
959 }
960
961 static Constant *
962 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
963                                    const TargetLibraryInfo *TLI,
964                                    SmallPtrSet<ConstantExpr *, 4> &FoldedOps) {
965   SmallVector<Constant *, 8> Ops;
966   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
967        ++i) {
968     Constant *NewC = cast<Constant>(*i);
969     // Recursively fold the ConstantExpr's operands. If we have already folded
970     // a ConstantExpr, we don't have to process it again.
971     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
972       if (FoldedOps.insert(NewCE))
973         NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
974     }
975     Ops.push_back(NewC);
976   }
977
978   if (CE->isCompare())
979     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
980                                            TD, TLI);
981   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
982 }
983
984 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
985 /// using the specified DataLayout.  If successful, the constant result is
986 /// result is returned, if not, null is returned.
987 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
988                                                const DataLayout *TD,
989                                                const TargetLibraryInfo *TLI) {
990   SmallPtrSet<ConstantExpr *, 4> FoldedOps;
991   return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
992 }
993
994 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
995 /// specified opcode and operands.  If successful, the constant result is
996 /// returned, if not, null is returned.  Note that this function can fail when
997 /// attempting to fold instructions like loads and stores, which have no
998 /// constant expression form.
999 ///
1000 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
1001 /// information, due to only being passed an opcode and operands. Constant
1002 /// folding using this function strips this information.
1003 ///
1004 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
1005                                          ArrayRef<Constant *> Ops,
1006                                          const DataLayout *TD,
1007                                          const TargetLibraryInfo *TLI) {
1008   // Handle easy binops first.
1009   if (Instruction::isBinaryOp(Opcode)) {
1010     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
1011       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
1012         return C;
1013     }
1014
1015     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
1016   }
1017
1018   switch (Opcode) {
1019   default: return nullptr;
1020   case Instruction::ICmp:
1021   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1022   case Instruction::Call:
1023     if (Function *F = dyn_cast<Function>(Ops.back()))
1024       if (canConstantFoldCallTo(F))
1025         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
1026     return nullptr;
1027   case Instruction::PtrToInt:
1028     // If the input is a inttoptr, eliminate the pair.  This requires knowing
1029     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1030     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1031       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
1032         Constant *Input = CE->getOperand(0);
1033         unsigned InWidth = Input->getType()->getScalarSizeInBits();
1034         unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
1035         if (PtrWidth < InWidth) {
1036           Constant *Mask =
1037             ConstantInt::get(CE->getContext(),
1038                              APInt::getLowBitsSet(InWidth, PtrWidth));
1039           Input = ConstantExpr::getAnd(Input, Mask);
1040         }
1041         // Do a zext or trunc to get to the dest size.
1042         return ConstantExpr::getIntegerCast(Input, DestTy, false);
1043       }
1044     }
1045     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1046   case Instruction::IntToPtr:
1047     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1048     // the int size is >= the ptr size and the address spaces are the same.
1049     // This requires knowing the width of a pointer, so it can't be done in
1050     // ConstantExpr::getCast.
1051     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1052       if (TD && CE->getOpcode() == Instruction::PtrToInt) {
1053         Constant *SrcPtr = CE->getOperand(0);
1054         unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
1055         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1056
1057         if (MidIntSize >= SrcPtrSize) {
1058           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1059           if (SrcAS == DestTy->getPointerAddressSpace())
1060             return FoldBitCast(CE->getOperand(0), DestTy, *TD);
1061         }
1062       }
1063     }
1064
1065     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1066   case Instruction::Trunc:
1067   case Instruction::ZExt:
1068   case Instruction::SExt:
1069   case Instruction::FPTrunc:
1070   case Instruction::FPExt:
1071   case Instruction::UIToFP:
1072   case Instruction::SIToFP:
1073   case Instruction::FPToUI:
1074   case Instruction::FPToSI:
1075   case Instruction::AddrSpaceCast:
1076       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1077   case Instruction::BitCast:
1078     if (TD)
1079       return FoldBitCast(Ops[0], DestTy, *TD);
1080     return ConstantExpr::getBitCast(Ops[0], DestTy);
1081   case Instruction::Select:
1082     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1083   case Instruction::ExtractElement:
1084     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1085   case Instruction::InsertElement:
1086     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1087   case Instruction::ShuffleVector:
1088     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1089   case Instruction::GetElementPtr:
1090     if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
1091       return C;
1092     if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
1093       return C;
1094
1095     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
1096   }
1097 }
1098
1099 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
1100 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
1101 /// returns a constant expression of the specified operands.
1102 ///
1103 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1104                                                 Constant *Ops0, Constant *Ops1,
1105                                                 const DataLayout *TD,
1106                                                 const TargetLibraryInfo *TLI) {
1107   // fold: icmp (inttoptr x), null         -> icmp x, 0
1108   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1109   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1110   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1111   //
1112   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1113   // around to know if bit truncation is happening.
1114   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1115     if (TD && Ops1->isNullValue()) {
1116       if (CE0->getOpcode() == Instruction::IntToPtr) {
1117         Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1118         // Convert the integer value to the right size to ensure we get the
1119         // proper extension or truncation.
1120         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1121                                                    IntPtrTy, false);
1122         Constant *Null = Constant::getNullValue(C->getType());
1123         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1124       }
1125
1126       // Only do this transformation if the int is intptrty in size, otherwise
1127       // there is a truncation or extension that we aren't modeling.
1128       if (CE0->getOpcode() == Instruction::PtrToInt) {
1129         Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1130         if (CE0->getType() == IntPtrTy) {
1131           Constant *C = CE0->getOperand(0);
1132           Constant *Null = Constant::getNullValue(C->getType());
1133           return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1134         }
1135       }
1136     }
1137
1138     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1139       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
1140         if (CE0->getOpcode() == Instruction::IntToPtr) {
1141           Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1142
1143           // Convert the integer value to the right size to ensure we get the
1144           // proper extension or truncation.
1145           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1146                                                       IntPtrTy, false);
1147           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1148                                                       IntPtrTy, false);
1149           return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
1150         }
1151
1152         // Only do this transformation if the int is intptrty in size, otherwise
1153         // there is a truncation or extension that we aren't modeling.
1154         if (CE0->getOpcode() == Instruction::PtrToInt) {
1155           Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1156           if (CE0->getType() == IntPtrTy &&
1157               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1158             return ConstantFoldCompareInstOperands(Predicate,
1159                                                    CE0->getOperand(0),
1160                                                    CE1->getOperand(0),
1161                                                    TD,
1162                                                    TLI);
1163           }
1164         }
1165       }
1166     }
1167
1168     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1169     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1170     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1171         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1172       Constant *LHS =
1173         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1174                                         TD, TLI);
1175       Constant *RHS =
1176         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1177                                         TD, TLI);
1178       unsigned OpC =
1179         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1180       Constant *Ops[] = { LHS, RHS };
1181       return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
1182     }
1183   }
1184
1185   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1186 }
1187
1188
1189 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1190 /// getelementptr constantexpr, return the constant value being addressed by the
1191 /// constant expression, or null if something is funny and we can't decide.
1192 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1193                                                        ConstantExpr *CE) {
1194   if (!CE->getOperand(1)->isNullValue())
1195     return nullptr;  // Do not allow stepping over the value!
1196
1197   // Loop over all of the operands, tracking down which value we are
1198   // addressing.
1199   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1200     C = C->getAggregateElement(CE->getOperand(i));
1201     if (!C)
1202       return nullptr;
1203   }
1204   return C;
1205 }
1206
1207 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1208 /// indices (with an *implied* zero pointer index that is not in the list),
1209 /// return the constant value being addressed by a virtual load, or null if
1210 /// something is funny and we can't decide.
1211 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1212                                                   ArrayRef<Constant*> Indices) {
1213   // Loop over all of the operands, tracking down which value we are
1214   // addressing.
1215   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1216     C = C->getAggregateElement(Indices[i]);
1217     if (!C)
1218       return nullptr;
1219   }
1220   return C;
1221 }
1222
1223
1224 //===----------------------------------------------------------------------===//
1225 //  Constant Folding for Calls
1226 //
1227
1228 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1229 /// the specified function.
1230 bool llvm::canConstantFoldCallTo(const Function *F) {
1231   switch (F->getIntrinsicID()) {
1232   case Intrinsic::fabs:
1233   case Intrinsic::log:
1234   case Intrinsic::log2:
1235   case Intrinsic::log10:
1236   case Intrinsic::exp:
1237   case Intrinsic::exp2:
1238   case Intrinsic::floor:
1239   case Intrinsic::ceil:
1240   case Intrinsic::sqrt:
1241   case Intrinsic::pow:
1242   case Intrinsic::powi:
1243   case Intrinsic::bswap:
1244   case Intrinsic::ctpop:
1245   case Intrinsic::ctlz:
1246   case Intrinsic::cttz:
1247   case Intrinsic::fma:
1248   case Intrinsic::fmuladd:
1249   case Intrinsic::copysign:
1250   case Intrinsic::round:
1251   case Intrinsic::sadd_with_overflow:
1252   case Intrinsic::uadd_with_overflow:
1253   case Intrinsic::ssub_with_overflow:
1254   case Intrinsic::usub_with_overflow:
1255   case Intrinsic::smul_with_overflow:
1256   case Intrinsic::umul_with_overflow:
1257   case Intrinsic::convert_from_fp16:
1258   case Intrinsic::convert_to_fp16:
1259   case Intrinsic::x86_sse_cvtss2si:
1260   case Intrinsic::x86_sse_cvtss2si64:
1261   case Intrinsic::x86_sse_cvttss2si:
1262   case Intrinsic::x86_sse_cvttss2si64:
1263   case Intrinsic::x86_sse2_cvtsd2si:
1264   case Intrinsic::x86_sse2_cvtsd2si64:
1265   case Intrinsic::x86_sse2_cvttsd2si:
1266   case Intrinsic::x86_sse2_cvttsd2si64:
1267     return true;
1268   default:
1269     return false;
1270   case 0: break;
1271   }
1272
1273   if (!F->hasName())
1274     return false;
1275   StringRef Name = F->getName();
1276
1277   // In these cases, the check of the length is required.  We don't want to
1278   // return true for a name like "cos\0blah" which strcmp would return equal to
1279   // "cos", but has length 8.
1280   switch (Name[0]) {
1281   default: return false;
1282   case 'a':
1283     return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
1284   case 'c':
1285     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1286   case 'e':
1287     return Name == "exp" || Name == "exp2";
1288   case 'f':
1289     return Name == "fabs" || Name == "fmod" || Name == "floor";
1290   case 'l':
1291     return Name == "log" || Name == "log10";
1292   case 'p':
1293     return Name == "pow";
1294   case 's':
1295     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1296       Name == "sinf" || Name == "sqrtf";
1297   case 't':
1298     return Name == "tan" || Name == "tanh";
1299   }
1300 }
1301
1302 static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1303   if (Ty->isHalfTy()) {
1304     APFloat APF(V);
1305     bool unused;
1306     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1307     return ConstantFP::get(Ty->getContext(), APF);
1308   }
1309   if (Ty->isFloatTy())
1310     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1311   if (Ty->isDoubleTy())
1312     return ConstantFP::get(Ty->getContext(), APFloat(V));
1313   llvm_unreachable("Can only constant fold half/float/double");
1314
1315 }
1316
1317 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1318                                 Type *Ty) {
1319   sys::llvm_fenv_clearexcept();
1320   V = NativeFP(V);
1321   if (sys::llvm_fenv_testexcept()) {
1322     sys::llvm_fenv_clearexcept();
1323     return nullptr;
1324   }
1325
1326   return GetConstantFoldFPValue(V, Ty);
1327 }
1328
1329 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1330                                       double V, double W, Type *Ty) {
1331   sys::llvm_fenv_clearexcept();
1332   V = NativeFP(V, W);
1333   if (sys::llvm_fenv_testexcept()) {
1334     sys::llvm_fenv_clearexcept();
1335     return nullptr;
1336   }
1337
1338   return GetConstantFoldFPValue(V, Ty);
1339 }
1340
1341 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1342 /// conversion of a constant floating point. If roundTowardZero is false, the
1343 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1344 /// the behavior of the non-truncating SSE instructions in the default rounding
1345 /// mode. The desired integer type Ty is used to select how many bits are
1346 /// available for the result. Returns null if the conversion cannot be
1347 /// performed, otherwise returns the Constant value resulting from the
1348 /// conversion.
1349 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1350                                           bool roundTowardZero, Type *Ty) {
1351   // All of these conversion intrinsics form an integer of at most 64bits.
1352   unsigned ResultWidth = Ty->getIntegerBitWidth();
1353   assert(ResultWidth <= 64 &&
1354          "Can only constant fold conversions to 64 and 32 bit ints");
1355
1356   uint64_t UIntVal;
1357   bool isExact = false;
1358   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1359                                               : APFloat::rmNearestTiesToEven;
1360   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1361                                                   /*isSigned=*/true, mode,
1362                                                   &isExact);
1363   if (status != APFloat::opOK && status != APFloat::opInexact)
1364     return nullptr;
1365   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1366 }
1367
1368 static double getValueAsDouble(ConstantFP *Op) {
1369   Type *Ty = Op->getType();
1370
1371   if (Ty->isFloatTy())
1372     return Op->getValueAPF().convertToFloat();
1373
1374   if (Ty->isDoubleTy())
1375     return Op->getValueAPF().convertToDouble();
1376
1377   bool unused;
1378   APFloat APF = Op->getValueAPF();
1379   APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1380   return APF.convertToDouble();
1381 }
1382
1383 static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1384                                         Type *Ty, ArrayRef<Constant *> Operands,
1385                                         const TargetLibraryInfo *TLI) {
1386   if (Operands.size() == 1) {
1387     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1388       if (IntrinsicID == Intrinsic::convert_to_fp16) {
1389         APFloat Val(Op->getValueAPF());
1390
1391         bool lost = false;
1392         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1393
1394         return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1395       }
1396
1397       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1398         return nullptr;
1399
1400       if (IntrinsicID == Intrinsic::round) {
1401         APFloat V = Op->getValueAPF();
1402         V.roundToIntegral(APFloat::rmNearestTiesToAway);
1403         return ConstantFP::get(Ty->getContext(), V);
1404       }
1405
1406       /// We only fold functions with finite arguments. Folding NaN and inf is
1407       /// likely to be aborted with an exception anyway, and some host libms
1408       /// have known errors raising exceptions.
1409       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1410         return nullptr;
1411
1412       /// Currently APFloat versions of these functions do not exist, so we use
1413       /// the host native double versions.  Float versions are not called
1414       /// directly but for all these it is true (float)(f((double)arg)) ==
1415       /// f(arg).  Long double not supported yet.
1416       double V = getValueAsDouble(Op);
1417
1418       switch (IntrinsicID) {
1419         default: break;
1420         case Intrinsic::fabs:
1421           return ConstantFoldFP(fabs, V, Ty);
1422 #if HAVE_LOG2
1423         case Intrinsic::log2:
1424           return ConstantFoldFP(log2, V, Ty);
1425 #endif
1426 #if HAVE_LOG
1427         case Intrinsic::log:
1428           return ConstantFoldFP(log, V, Ty);
1429 #endif
1430 #if HAVE_LOG10
1431         case Intrinsic::log10:
1432           return ConstantFoldFP(log10, V, Ty);
1433 #endif
1434 #if HAVE_EXP
1435         case Intrinsic::exp:
1436           return ConstantFoldFP(exp, V, Ty);
1437 #endif
1438 #if HAVE_EXP2
1439         case Intrinsic::exp2:
1440           return ConstantFoldFP(exp2, V, Ty);
1441 #endif
1442         case Intrinsic::floor:
1443           return ConstantFoldFP(floor, V, Ty);
1444         case Intrinsic::ceil:
1445           return ConstantFoldFP(ceil, V, Ty);
1446       }
1447
1448       if (!TLI)
1449         return nullptr;
1450
1451       switch (Name[0]) {
1452       case 'a':
1453         if (Name == "acos" && TLI->has(LibFunc::acos))
1454           return ConstantFoldFP(acos, V, Ty);
1455         else if (Name == "asin" && TLI->has(LibFunc::asin))
1456           return ConstantFoldFP(asin, V, Ty);
1457         else if (Name == "atan" && TLI->has(LibFunc::atan))
1458           return ConstantFoldFP(atan, V, Ty);
1459         break;
1460       case 'c':
1461         if (Name == "ceil" && TLI->has(LibFunc::ceil))
1462           return ConstantFoldFP(ceil, V, Ty);
1463         else if (Name == "cos" && TLI->has(LibFunc::cos))
1464           return ConstantFoldFP(cos, V, Ty);
1465         else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1466           return ConstantFoldFP(cosh, V, Ty);
1467         else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1468           return ConstantFoldFP(cos, V, Ty);
1469         break;
1470       case 'e':
1471         if (Name == "exp" && TLI->has(LibFunc::exp))
1472           return ConstantFoldFP(exp, V, Ty);
1473
1474         if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1475           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1476           // C99 library.
1477           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1478         }
1479         break;
1480       case 'f':
1481         if (Name == "fabs" && TLI->has(LibFunc::fabs))
1482           return ConstantFoldFP(fabs, V, Ty);
1483         else if (Name == "floor" && TLI->has(LibFunc::floor))
1484           return ConstantFoldFP(floor, V, Ty);
1485         break;
1486       case 'l':
1487         if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1488           return ConstantFoldFP(log, V, Ty);
1489         else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1490           return ConstantFoldFP(log10, V, Ty);
1491         else if (IntrinsicID == Intrinsic::sqrt &&
1492                  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1493           if (V >= -0.0)
1494             return ConstantFoldFP(sqrt, V, Ty);
1495           else // Undefined
1496             return Constant::getNullValue(Ty);
1497         }
1498         break;
1499       case 's':
1500         if (Name == "sin" && TLI->has(LibFunc::sin))
1501           return ConstantFoldFP(sin, V, Ty);
1502         else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1503           return ConstantFoldFP(sinh, V, Ty);
1504         else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1505           return ConstantFoldFP(sqrt, V, Ty);
1506         else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1507           return ConstantFoldFP(sqrt, V, Ty);
1508         else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1509           return ConstantFoldFP(sin, V, Ty);
1510         break;
1511       case 't':
1512         if (Name == "tan" && TLI->has(LibFunc::tan))
1513           return ConstantFoldFP(tan, V, Ty);
1514         else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1515           return ConstantFoldFP(tanh, V, Ty);
1516         break;
1517       default:
1518         break;
1519       }
1520       return nullptr;
1521     }
1522
1523     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1524       switch (IntrinsicID) {
1525       case Intrinsic::bswap:
1526         return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1527       case Intrinsic::ctpop:
1528         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1529       case Intrinsic::convert_from_fp16: {
1530         APFloat Val(APFloat::IEEEhalf, Op->getValue());
1531
1532         bool lost = false;
1533         APFloat::opStatus status =
1534           Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1535
1536         // Conversion is always precise.
1537         (void)status;
1538         assert(status == APFloat::opOK && !lost &&
1539                "Precision lost during fp16 constfolding");
1540
1541         return ConstantFP::get(Ty->getContext(), Val);
1542       }
1543       default:
1544         return nullptr;
1545       }
1546     }
1547
1548     // Support ConstantVector in case we have an Undef in the top.
1549     if (isa<ConstantVector>(Operands[0]) ||
1550         isa<ConstantDataVector>(Operands[0])) {
1551       Constant *Op = cast<Constant>(Operands[0]);
1552       switch (IntrinsicID) {
1553       default: break;
1554       case Intrinsic::x86_sse_cvtss2si:
1555       case Intrinsic::x86_sse_cvtss2si64:
1556       case Intrinsic::x86_sse2_cvtsd2si:
1557       case Intrinsic::x86_sse2_cvtsd2si64:
1558         if (ConstantFP *FPOp =
1559               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1560           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1561                                           /*roundTowardZero=*/false, Ty);
1562       case Intrinsic::x86_sse_cvttss2si:
1563       case Intrinsic::x86_sse_cvttss2si64:
1564       case Intrinsic::x86_sse2_cvttsd2si:
1565       case Intrinsic::x86_sse2_cvttsd2si64:
1566         if (ConstantFP *FPOp =
1567               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1568           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1569                                           /*roundTowardZero=*/true, Ty);
1570       }
1571     }
1572
1573     if (isa<UndefValue>(Operands[0])) {
1574       if (IntrinsicID == Intrinsic::bswap)
1575         return Operands[0];
1576       return nullptr;
1577     }
1578
1579     return nullptr;
1580   }
1581
1582   if (Operands.size() == 2) {
1583     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1584       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1585         return nullptr;
1586       double Op1V = getValueAsDouble(Op1);
1587
1588       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1589         if (Op2->getType() != Op1->getType())
1590           return nullptr;
1591
1592         double Op2V = getValueAsDouble(Op2);
1593         if (IntrinsicID == Intrinsic::pow) {
1594           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1595         }
1596         if (IntrinsicID == Intrinsic::copysign) {
1597           APFloat V1 = Op1->getValueAPF();
1598           APFloat V2 = Op2->getValueAPF();
1599           V1.copySign(V2);
1600           return ConstantFP::get(Ty->getContext(), V1);
1601         }
1602         if (!TLI)
1603           return nullptr;
1604         if (Name == "pow" && TLI->has(LibFunc::pow))
1605           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1606         if (Name == "fmod" && TLI->has(LibFunc::fmod))
1607           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1608         if (Name == "atan2" && TLI->has(LibFunc::atan2))
1609           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1610       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1611         if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1612           return ConstantFP::get(Ty->getContext(),
1613                                  APFloat((float)std::pow((float)Op1V,
1614                                                  (int)Op2C->getZExtValue())));
1615         if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1616           return ConstantFP::get(Ty->getContext(),
1617                                  APFloat((float)std::pow((float)Op1V,
1618                                                  (int)Op2C->getZExtValue())));
1619         if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1620           return ConstantFP::get(Ty->getContext(),
1621                                  APFloat((double)std::pow((double)Op1V,
1622                                                    (int)Op2C->getZExtValue())));
1623       }
1624       return nullptr;
1625     }
1626
1627     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1628       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1629         switch (IntrinsicID) {
1630         default: break;
1631         case Intrinsic::sadd_with_overflow:
1632         case Intrinsic::uadd_with_overflow:
1633         case Intrinsic::ssub_with_overflow:
1634         case Intrinsic::usub_with_overflow:
1635         case Intrinsic::smul_with_overflow:
1636         case Intrinsic::umul_with_overflow: {
1637           APInt Res;
1638           bool Overflow;
1639           switch (IntrinsicID) {
1640           default: llvm_unreachable("Invalid case");
1641           case Intrinsic::sadd_with_overflow:
1642             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1643             break;
1644           case Intrinsic::uadd_with_overflow:
1645             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1646             break;
1647           case Intrinsic::ssub_with_overflow:
1648             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1649             break;
1650           case Intrinsic::usub_with_overflow:
1651             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1652             break;
1653           case Intrinsic::smul_with_overflow:
1654             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1655             break;
1656           case Intrinsic::umul_with_overflow:
1657             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1658             break;
1659           }
1660           Constant *Ops[] = {
1661             ConstantInt::get(Ty->getContext(), Res),
1662             ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1663           };
1664           return ConstantStruct::get(cast<StructType>(Ty), Ops);
1665         }
1666         case Intrinsic::cttz:
1667           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1668             return UndefValue::get(Ty);
1669           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1670         case Intrinsic::ctlz:
1671           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1672             return UndefValue::get(Ty);
1673           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1674         }
1675       }
1676
1677       return nullptr;
1678     }
1679     return nullptr;
1680   }
1681
1682   if (Operands.size() != 3)
1683     return nullptr;
1684
1685   if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1686     if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1687       if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1688         switch (IntrinsicID) {
1689         default: break;
1690         case Intrinsic::fma:
1691         case Intrinsic::fmuladd: {
1692           APFloat V = Op1->getValueAPF();
1693           APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1694                                                    Op3->getValueAPF(),
1695                                                    APFloat::rmNearestTiesToEven);
1696           if (s != APFloat::opInvalidOp)
1697             return ConstantFP::get(Ty->getContext(), V);
1698
1699           return nullptr;
1700         }
1701         }
1702       }
1703     }
1704   }
1705
1706   return nullptr;
1707 }
1708
1709 static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1710                                         VectorType *VTy,
1711                                         ArrayRef<Constant *> Operands,
1712                                         const TargetLibraryInfo *TLI) {
1713   SmallVector<Constant *, 4> Result(VTy->getNumElements());
1714   SmallVector<Constant *, 4> Lane(Operands.size());
1715   Type *Ty = VTy->getElementType();
1716
1717   for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1718     // Gather a column of constants.
1719     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1720       Constant *Agg = Operands[J]->getAggregateElement(I);
1721       if (!Agg)
1722         return nullptr;
1723
1724       Lane[J] = Agg;
1725     }
1726
1727     // Use the regular scalar folding to simplify this column.
1728     Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1729     if (!Folded)
1730       return nullptr;
1731     Result[I] = Folded;
1732   }
1733
1734   return ConstantVector::get(Result);
1735 }
1736
1737 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1738 /// with the specified arguments, returning null if unsuccessful.
1739 Constant *
1740 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1741                        const TargetLibraryInfo *TLI) {
1742   if (!F->hasName())
1743     return nullptr;
1744   StringRef Name = F->getName();
1745
1746   Type *Ty = F->getReturnType();
1747
1748   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1749     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1750
1751   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1752 }