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