]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Analysis/ConstantFolding.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/APFloat.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/KnownBits.h"
46 #include "llvm/Support/MathExtras.h"
47 #include <cassert>
48 #include <cerrno>
49 #include <cfenv>
50 #include <cmath>
51 #include <cstddef>
52 #include <cstdint>
53
54 using namespace llvm;
55
56 namespace {
57
58 //===----------------------------------------------------------------------===//
59 // Constant Folding internal helper functions
60 //===----------------------------------------------------------------------===//
61
62 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
63                                         Constant *C, Type *SrcEltTy,
64                                         unsigned NumSrcElts,
65                                         const DataLayout &DL) {
66   // Now that we know that the input value is a vector of integers, just shift
67   // and insert them into our result.
68   unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
69   for (unsigned i = 0; i != NumSrcElts; ++i) {
70     Constant *Element;
71     if (DL.isLittleEndian())
72       Element = C->getAggregateElement(NumSrcElts - i - 1);
73     else
74       Element = C->getAggregateElement(i);
75
76     if (Element && isa<UndefValue>(Element)) {
77       Result <<= BitShift;
78       continue;
79     }
80
81     auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
82     if (!ElementCI)
83       return ConstantExpr::getBitCast(C, DestTy);
84
85     Result <<= BitShift;
86     Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
87   }
88
89   return nullptr;
90 }
91
92 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
93 /// This always returns a non-null constant, but it may be a
94 /// ConstantExpr if unfoldable.
95 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
96   // Catch the obvious splat cases.
97   if (C->isNullValue() && !DestTy->isX86_MMXTy())
98     return Constant::getNullValue(DestTy);
99   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
100       !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
101     return Constant::getAllOnesValue(DestTy);
102
103   if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
104     // Handle a vector->scalar integer/fp cast.
105     if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
106       unsigned NumSrcElts = VTy->getNumElements();
107       Type *SrcEltTy = VTy->getElementType();
108
109       // If the vector is a vector of floating point, convert it to vector of int
110       // to simplify things.
111       if (SrcEltTy->isFloatingPointTy()) {
112         unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
113         Type *SrcIVTy =
114           VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
115         // Ask IR to do the conversion now that #elts line up.
116         C = ConstantExpr::getBitCast(C, SrcIVTy);
117       }
118
119       APInt Result(DL.getTypeSizeInBits(DestTy), 0);
120       if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
121                                                 SrcEltTy, NumSrcElts, DL))
122         return CE;
123
124       if (isa<IntegerType>(DestTy))
125         return ConstantInt::get(DestTy, Result);
126
127       APFloat FP(DestTy->getFltSemantics(), Result);
128       return ConstantFP::get(DestTy->getContext(), FP);
129     }
130   }
131
132   // The code below only handles casts to vectors currently.
133   auto *DestVTy = dyn_cast<VectorType>(DestTy);
134   if (!DestVTy)
135     return ConstantExpr::getBitCast(C, DestTy);
136
137   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
138   // vector so the code below can handle it uniformly.
139   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
140     Constant *Ops = C; // don't take the address of C!
141     return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
142   }
143
144   // If this is a bitcast from constant vector -> vector, fold it.
145   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
146     return ConstantExpr::getBitCast(C, DestTy);
147
148   // If the element types match, IR can fold it.
149   unsigned NumDstElt = DestVTy->getNumElements();
150   unsigned NumSrcElt = C->getType()->getVectorNumElements();
151   if (NumDstElt == NumSrcElt)
152     return ConstantExpr::getBitCast(C, DestTy);
153
154   Type *SrcEltTy = C->getType()->getVectorElementType();
155   Type *DstEltTy = DestVTy->getElementType();
156
157   // Otherwise, we're changing the number of elements in a vector, which
158   // requires endianness information to do the right thing.  For example,
159   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
160   // folds to (little endian):
161   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
162   // and to (big endian):
163   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
164
165   // First thing is first.  We only want to think about integer here, so if
166   // we have something in FP form, recast it as integer.
167   if (DstEltTy->isFloatingPointTy()) {
168     // Fold to an vector of integers with same size as our FP type.
169     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
170     Type *DestIVTy =
171       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
172     // Recursively handle this integer conversion, if possible.
173     C = FoldBitCast(C, DestIVTy, DL);
174
175     // Finally, IR can handle this now that #elts line up.
176     return ConstantExpr::getBitCast(C, DestTy);
177   }
178
179   // Okay, we know the destination is integer, if the input is FP, convert
180   // it to integer first.
181   if (SrcEltTy->isFloatingPointTy()) {
182     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
183     Type *SrcIVTy =
184       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
185     // Ask IR to do the conversion now that #elts line up.
186     C = ConstantExpr::getBitCast(C, SrcIVTy);
187     // If IR wasn't able to fold it, bail out.
188     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
189         !isa<ConstantDataVector>(C))
190       return C;
191   }
192
193   // Now we know that the input and output vectors are both integer vectors
194   // of the same size, and that their #elements is not the same.  Do the
195   // conversion here, which depends on whether the input or output has
196   // more elements.
197   bool isLittleEndian = DL.isLittleEndian();
198
199   SmallVector<Constant*, 32> Result;
200   if (NumDstElt < NumSrcElt) {
201     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
202     Constant *Zero = Constant::getNullValue(DstEltTy);
203     unsigned Ratio = NumSrcElt/NumDstElt;
204     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
205     unsigned SrcElt = 0;
206     for (unsigned i = 0; i != NumDstElt; ++i) {
207       // Build each element of the result.
208       Constant *Elt = Zero;
209       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
210       for (unsigned j = 0; j != Ratio; ++j) {
211         Constant *Src = C->getAggregateElement(SrcElt++);
212         if (Src && isa<UndefValue>(Src))
213           Src = Constant::getNullValue(C->getType()->getVectorElementType());
214         else
215           Src = dyn_cast_or_null<ConstantInt>(Src);
216         if (!Src)  // Reject constantexpr elements.
217           return ConstantExpr::getBitCast(C, DestTy);
218
219         // Zero extend the element to the right size.
220         Src = ConstantExpr::getZExt(Src, Elt->getType());
221
222         // Shift it to the right place, depending on endianness.
223         Src = ConstantExpr::getShl(Src,
224                                    ConstantInt::get(Src->getType(), ShiftAmt));
225         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
226
227         // Mix it in.
228         Elt = ConstantExpr::getOr(Elt, Src);
229       }
230       Result.push_back(Elt);
231     }
232     return ConstantVector::get(Result);
233   }
234
235   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
236   unsigned Ratio = NumDstElt/NumSrcElt;
237   unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
238
239   // Loop over each source value, expanding into multiple results.
240   for (unsigned i = 0; i != NumSrcElt; ++i) {
241     auto *Element = C->getAggregateElement(i);
242
243     if (!Element) // Reject constantexpr elements.
244       return ConstantExpr::getBitCast(C, DestTy);
245
246     if (isa<UndefValue>(Element)) {
247       // Correctly Propagate undef values.
248       Result.append(Ratio, UndefValue::get(DstEltTy));
249       continue;
250     }
251
252     auto *Src = dyn_cast<ConstantInt>(Element);
253     if (!Src)
254       return ConstantExpr::getBitCast(C, DestTy);
255
256     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
257     for (unsigned j = 0; j != Ratio; ++j) {
258       // Shift the piece of the value into the right place, depending on
259       // endianness.
260       Constant *Elt = ConstantExpr::getLShr(Src,
261                                   ConstantInt::get(Src->getType(), ShiftAmt));
262       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
263
264       // Truncate the element to an integer with the same pointer size and
265       // convert the element back to a pointer using a inttoptr.
266       if (DstEltTy->isPointerTy()) {
267         IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
268         Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
269         Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
270         continue;
271       }
272
273       // Truncate and remember this piece.
274       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
275     }
276   }
277
278   return ConstantVector::get(Result);
279 }
280
281 } // end anonymous namespace
282
283 /// If this constant is a constant offset from a global, return the global and
284 /// the constant. Because of constantexprs, this function is recursive.
285 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
286                                       APInt &Offset, const DataLayout &DL) {
287   // Trivial case, constant is the global.
288   if ((GV = dyn_cast<GlobalValue>(C))) {
289     unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
290     Offset = APInt(BitWidth, 0);
291     return true;
292   }
293
294   // Otherwise, if this isn't a constant expr, bail out.
295   auto *CE = dyn_cast<ConstantExpr>(C);
296   if (!CE) return false;
297
298   // Look through ptr->int and ptr->ptr casts.
299   if (CE->getOpcode() == Instruction::PtrToInt ||
300       CE->getOpcode() == Instruction::BitCast)
301     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
302
303   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
304   auto *GEP = dyn_cast<GEPOperator>(CE);
305   if (!GEP)
306     return false;
307
308   unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
309   APInt TmpOffset(BitWidth, 0);
310
311   // If the base isn't a global+constant, we aren't either.
312   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
313     return false;
314
315   // Otherwise, add any offset that our operands provide.
316   if (!GEP->accumulateConstantOffset(DL, TmpOffset))
317     return false;
318
319   Offset = TmpOffset;
320   return true;
321 }
322
323 namespace {
324
325 /// Recursive helper to read bits out of global. C is the constant being copied
326 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
327 /// results into and BytesLeft is the number of bytes left in
328 /// the CurPtr buffer. DL is the DataLayout.
329 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
330                         unsigned BytesLeft, const DataLayout &DL) {
331   assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
332          "Out of range access");
333
334   // If this element is zero or undefined, we can just return since *CurPtr is
335   // zero initialized.
336   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
337     return true;
338
339   if (auto *CI = dyn_cast<ConstantInt>(C)) {
340     if (CI->getBitWidth() > 64 ||
341         (CI->getBitWidth() & 7) != 0)
342       return false;
343
344     uint64_t Val = CI->getZExtValue();
345     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
346
347     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
348       int n = ByteOffset;
349       if (!DL.isLittleEndian())
350         n = IntBytes - n - 1;
351       CurPtr[i] = (unsigned char)(Val >> (n * 8));
352       ++ByteOffset;
353     }
354     return true;
355   }
356
357   if (auto *CFP = dyn_cast<ConstantFP>(C)) {
358     if (CFP->getType()->isDoubleTy()) {
359       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
360       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
361     }
362     if (CFP->getType()->isFloatTy()){
363       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
364       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
365     }
366     if (CFP->getType()->isHalfTy()){
367       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
368       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
369     }
370     return false;
371   }
372
373   if (auto *CS = dyn_cast<ConstantStruct>(C)) {
374     const StructLayout *SL = DL.getStructLayout(CS->getType());
375     unsigned Index = SL->getElementContainingOffset(ByteOffset);
376     uint64_t CurEltOffset = SL->getElementOffset(Index);
377     ByteOffset -= CurEltOffset;
378
379     while (true) {
380       // If the element access is to the element itself and not to tail padding,
381       // read the bytes from the element.
382       uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
383
384       if (ByteOffset < EltSize &&
385           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
386                               BytesLeft, DL))
387         return false;
388
389       ++Index;
390
391       // Check to see if we read from the last struct element, if so we're done.
392       if (Index == CS->getType()->getNumElements())
393         return true;
394
395       // If we read all of the bytes we needed from this element we're done.
396       uint64_t NextEltOffset = SL->getElementOffset(Index);
397
398       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
399         return true;
400
401       // Move to the next element of the struct.
402       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
403       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
404       ByteOffset = 0;
405       CurEltOffset = NextEltOffset;
406     }
407     // not reached.
408   }
409
410   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
411       isa<ConstantDataSequential>(C)) {
412     Type *EltTy = C->getType()->getSequentialElementType();
413     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
414     uint64_t Index = ByteOffset / EltSize;
415     uint64_t Offset = ByteOffset - Index * EltSize;
416     uint64_t NumElts;
417     if (auto *AT = dyn_cast<ArrayType>(C->getType()))
418       NumElts = AT->getNumElements();
419     else
420       NumElts = C->getType()->getVectorNumElements();
421
422     for (; Index != NumElts; ++Index) {
423       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
424                               BytesLeft, DL))
425         return false;
426
427       uint64_t BytesWritten = EltSize - Offset;
428       assert(BytesWritten <= EltSize && "Not indexing into this element?");
429       if (BytesWritten >= BytesLeft)
430         return true;
431
432       Offset = 0;
433       BytesLeft -= BytesWritten;
434       CurPtr += BytesWritten;
435     }
436     return true;
437   }
438
439   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
440     if (CE->getOpcode() == Instruction::IntToPtr &&
441         CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
442       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
443                                 BytesLeft, DL);
444     }
445   }
446
447   // Otherwise, unknown initializer type.
448   return false;
449 }
450
451 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
452                                           const DataLayout &DL) {
453   auto *PTy = cast<PointerType>(C->getType());
454   auto *IntType = dyn_cast<IntegerType>(LoadTy);
455
456   // If this isn't an integer load we can't fold it directly.
457   if (!IntType) {
458     unsigned AS = PTy->getAddressSpace();
459
460     // If this is a float/double load, we can try folding it as an int32/64 load
461     // and then bitcast the result.  This can be useful for union cases.  Note
462     // that address spaces don't matter here since we're not going to result in
463     // an actual new load.
464     Type *MapTy;
465     if (LoadTy->isHalfTy())
466       MapTy = Type::getInt16Ty(C->getContext());
467     else if (LoadTy->isFloatTy())
468       MapTy = Type::getInt32Ty(C->getContext());
469     else if (LoadTy->isDoubleTy())
470       MapTy = Type::getInt64Ty(C->getContext());
471     else if (LoadTy->isVectorTy()) {
472       MapTy = PointerType::getIntNTy(C->getContext(),
473                                      DL.getTypeAllocSizeInBits(LoadTy));
474     } else
475       return nullptr;
476
477     C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
478     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
479       return FoldBitCast(Res, LoadTy, DL);
480     return nullptr;
481   }
482
483   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
484   if (BytesLoaded > 32 || BytesLoaded == 0)
485     return nullptr;
486
487   GlobalValue *GVal;
488   APInt OffsetAI;
489   if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
490     return nullptr;
491
492   auto *GV = dyn_cast<GlobalVariable>(GVal);
493   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
494       !GV->getInitializer()->getType()->isSized())
495     return nullptr;
496
497   int64_t Offset = OffsetAI.getSExtValue();
498   int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
499
500   // If we're not accessing anything in this constant, the result is undefined.
501   if (Offset + BytesLoaded <= 0)
502     return UndefValue::get(IntType);
503
504   // If we're not accessing anything in this constant, the result is undefined.
505   if (Offset >= InitializerSize)
506     return UndefValue::get(IntType);
507
508   unsigned char RawBytes[32] = {0};
509   unsigned char *CurPtr = RawBytes;
510   unsigned BytesLeft = BytesLoaded;
511
512   // If we're loading off the beginning of the global, some bytes may be valid.
513   if (Offset < 0) {
514     CurPtr += -Offset;
515     BytesLeft += Offset;
516     Offset = 0;
517   }
518
519   if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
520     return nullptr;
521
522   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
523   if (DL.isLittleEndian()) {
524     ResultVal = RawBytes[BytesLoaded - 1];
525     for (unsigned i = 1; i != BytesLoaded; ++i) {
526       ResultVal <<= 8;
527       ResultVal |= RawBytes[BytesLoaded - 1 - i];
528     }
529   } else {
530     ResultVal = RawBytes[0];
531     for (unsigned i = 1; i != BytesLoaded; ++i) {
532       ResultVal <<= 8;
533       ResultVal |= RawBytes[i];
534     }
535   }
536
537   return ConstantInt::get(IntType->getContext(), ResultVal);
538 }
539
540 Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
541                                          const DataLayout &DL) {
542   auto *SrcPtr = CE->getOperand(0);
543   auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
544   if (!SrcPtrTy)
545     return nullptr;
546   Type *SrcTy = SrcPtrTy->getPointerElementType();
547
548   Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
549   if (!C)
550     return nullptr;
551
552   do {
553     Type *SrcTy = C->getType();
554
555     // If the type sizes are the same and a cast is legal, just directly
556     // cast the constant.
557     if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
558       Instruction::CastOps Cast = Instruction::BitCast;
559       // If we are going from a pointer to int or vice versa, we spell the cast
560       // differently.
561       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
562         Cast = Instruction::IntToPtr;
563       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
564         Cast = Instruction::PtrToInt;
565
566       if (CastInst::castIsValid(Cast, C, DestTy))
567         return ConstantExpr::getCast(Cast, C, DestTy);
568     }
569
570     // If this isn't an aggregate type, there is nothing we can do to drill down
571     // and find a bitcastable constant.
572     if (!SrcTy->isAggregateType())
573       return nullptr;
574
575     // We're simulating a load through a pointer that was bitcast to point to
576     // a different type, so we can try to walk down through the initial
577     // elements of an aggregate to see if some part of th e aggregate is
578     // castable to implement the "load" semantic model.
579     C = C->getAggregateElement(0u);
580   } while (C);
581
582   return nullptr;
583 }
584
585 } // end anonymous namespace
586
587 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
588                                              const DataLayout &DL) {
589   // First, try the easy cases:
590   if (auto *GV = dyn_cast<GlobalVariable>(C))
591     if (GV->isConstant() && GV->hasDefinitiveInitializer())
592       return GV->getInitializer();
593
594   if (auto *GA = dyn_cast<GlobalAlias>(C))
595     if (GA->getAliasee() && !GA->isInterposable())
596       return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
597
598   // If the loaded value isn't a constant expr, we can't handle it.
599   auto *CE = dyn_cast<ConstantExpr>(C);
600   if (!CE)
601     return nullptr;
602
603   if (CE->getOpcode() == Instruction::GetElementPtr) {
604     if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
605       if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
606         if (Constant *V =
607              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
608           return V;
609       }
610     }
611   }
612
613   if (CE->getOpcode() == Instruction::BitCast)
614     if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
615       return LoadedC;
616
617   // Instead of loading constant c string, use corresponding integer value
618   // directly if string length is small enough.
619   StringRef Str;
620   if (getConstantStringInfo(CE, Str) && !Str.empty()) {
621     size_t StrLen = Str.size();
622     unsigned NumBits = Ty->getPrimitiveSizeInBits();
623     // Replace load with immediate integer if the result is an integer or fp
624     // value.
625     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
626         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
627       APInt StrVal(NumBits, 0);
628       APInt SingleChar(NumBits, 0);
629       if (DL.isLittleEndian()) {
630         for (unsigned char C : reverse(Str.bytes())) {
631           SingleChar = static_cast<uint64_t>(C);
632           StrVal = (StrVal << 8) | SingleChar;
633         }
634       } else {
635         for (unsigned char C : Str.bytes()) {
636           SingleChar = static_cast<uint64_t>(C);
637           StrVal = (StrVal << 8) | SingleChar;
638         }
639         // Append NULL at the end.
640         SingleChar = 0;
641         StrVal = (StrVal << 8) | SingleChar;
642       }
643
644       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
645       if (Ty->isFloatingPointTy())
646         Res = ConstantExpr::getBitCast(Res, Ty);
647       return Res;
648     }
649   }
650
651   // If this load comes from anywhere in a constant global, and if the global
652   // is all undef or zero, we know what it loads.
653   if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
654     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
655       if (GV->getInitializer()->isNullValue())
656         return Constant::getNullValue(Ty);
657       if (isa<UndefValue>(GV->getInitializer()))
658         return UndefValue::get(Ty);
659     }
660   }
661
662   // Try hard to fold loads from bitcasted strange and non-type-safe things.
663   return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
664 }
665
666 namespace {
667
668 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
669   if (LI->isVolatile()) return nullptr;
670
671   if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
672     return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
673
674   return nullptr;
675 }
676
677 /// One of Op0/Op1 is a constant expression.
678 /// Attempt to symbolically evaluate the result of a binary operator merging
679 /// these together.  If target data info is available, it is provided as DL,
680 /// otherwise DL is null.
681 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
682                                     const DataLayout &DL) {
683   // SROA
684
685   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
686   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
687   // bits.
688
689   if (Opc == Instruction::And) {
690     unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
691     KnownBits Known0(BitWidth);
692     KnownBits Known1(BitWidth);
693     computeKnownBits(Op0, Known0, DL);
694     computeKnownBits(Op1, Known1, DL);
695     if ((Known1.One | Known0.Zero).isAllOnesValue()) {
696       // All the bits of Op0 that the 'and' could be masking are already zero.
697       return Op0;
698     }
699     if ((Known0.One | Known1.Zero).isAllOnesValue()) {
700       // All the bits of Op1 that the 'and' could be masking are already zero.
701       return Op1;
702     }
703
704     APInt KnownZero = Known0.Zero | Known1.Zero;
705     APInt KnownOne = Known0.One & Known1.One;
706     if ((KnownZero | KnownOne).isAllOnesValue()) {
707       return ConstantInt::get(Op0->getType(), KnownOne);
708     }
709   }
710
711   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
712   // constant.  This happens frequently when iterating over a global array.
713   if (Opc == Instruction::Sub) {
714     GlobalValue *GV1, *GV2;
715     APInt Offs1, Offs2;
716
717     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
718       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
719         unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
720
721         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
722         // PtrToInt may change the bitwidth so we have convert to the right size
723         // first.
724         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
725                                                 Offs2.zextOrTrunc(OpSize));
726       }
727   }
728
729   return nullptr;
730 }
731
732 /// If array indices are not pointer-sized integers, explicitly cast them so
733 /// that they aren't implicitly casted by the getelementptr.
734 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
735                          Type *ResultTy, Optional<unsigned> InRangeIndex,
736                          const DataLayout &DL, const TargetLibraryInfo *TLI) {
737   Type *IntPtrTy = DL.getIntPtrType(ResultTy);
738   Type *IntPtrScalarTy = IntPtrTy->getScalarType();
739
740   bool Any = false;
741   SmallVector<Constant*, 32> NewIdxs;
742   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
743     if ((i == 1 ||
744          !isa<StructType>(GetElementPtrInst::getIndexedType(
745              SrcElemTy, Ops.slice(1, i - 1)))) &&
746         Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
747       Any = true;
748       Type *NewType = Ops[i]->getType()->isVectorTy()
749                           ? IntPtrTy
750                           : IntPtrTy->getScalarType();
751       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
752                                                                       true,
753                                                                       NewType,
754                                                                       true),
755                                               Ops[i], NewType));
756     } else
757       NewIdxs.push_back(Ops[i]);
758   }
759
760   if (!Any)
761     return nullptr;
762
763   Constant *C = ConstantExpr::getGetElementPtr(
764       SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
765   if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
766     C = Folded;
767
768   return C;
769 }
770
771 /// Strip the pointer casts, but preserve the address space information.
772 Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
773   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
774   auto *OldPtrTy = cast<PointerType>(Ptr->getType());
775   Ptr = Ptr->stripPointerCasts();
776   auto *NewPtrTy = cast<PointerType>(Ptr->getType());
777
778   ElemTy = NewPtrTy->getPointerElementType();
779
780   // Preserve the address space number of the pointer.
781   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
782     NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
783     Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
784   }
785   return Ptr;
786 }
787
788 /// If we can symbolically evaluate the GEP constant expression, do so.
789 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
790                                   ArrayRef<Constant *> Ops,
791                                   const DataLayout &DL,
792                                   const TargetLibraryInfo *TLI) {
793   const GEPOperator *InnermostGEP = GEP;
794   bool InBounds = GEP->isInBounds();
795
796   Type *SrcElemTy = GEP->getSourceElementType();
797   Type *ResElemTy = GEP->getResultElementType();
798   Type *ResTy = GEP->getType();
799   if (!SrcElemTy->isSized())
800     return nullptr;
801
802   if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
803                                    GEP->getInRangeIndex(), DL, TLI))
804     return C;
805
806   Constant *Ptr = Ops[0];
807   if (!Ptr->getType()->isPointerTy())
808     return nullptr;
809
810   Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
811
812   // If this is a constant expr gep that is effectively computing an
813   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
814   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
815     if (!isa<ConstantInt>(Ops[i])) {
816
817       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
818       // "inttoptr (sub (ptrtoint Ptr), V)"
819       if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
820         auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
821         assert((!CE || CE->getType() == IntPtrTy) &&
822                "CastGEPIndices didn't canonicalize index types!");
823         if (CE && CE->getOpcode() == Instruction::Sub &&
824             CE->getOperand(0)->isNullValue()) {
825           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
826           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
827           Res = ConstantExpr::getIntToPtr(Res, ResTy);
828           if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
829             Res = FoldedRes;
830           return Res;
831         }
832       }
833       return nullptr;
834     }
835
836   unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
837   APInt Offset =
838       APInt(BitWidth,
839             DL.getIndexedOffsetInType(
840                 SrcElemTy,
841                 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
842   Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
843
844   // If this is a GEP of a GEP, fold it all into a single GEP.
845   while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
846     InnermostGEP = GEP;
847     InBounds &= GEP->isInBounds();
848
849     SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
850
851     // Do not try the incorporate the sub-GEP if some index is not a number.
852     bool AllConstantInt = true;
853     for (Value *NestedOp : NestedOps)
854       if (!isa<ConstantInt>(NestedOp)) {
855         AllConstantInt = false;
856         break;
857       }
858     if (!AllConstantInt)
859       break;
860
861     Ptr = cast<Constant>(GEP->getOperand(0));
862     SrcElemTy = GEP->getSourceElementType();
863     Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
864     Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
865   }
866
867   // If the base value for this address is a literal integer value, fold the
868   // getelementptr to the resulting integer value casted to the pointer type.
869   APInt BasePtr(BitWidth, 0);
870   if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
871     if (CE->getOpcode() == Instruction::IntToPtr) {
872       if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
873         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
874     }
875   }
876
877   auto *PTy = cast<PointerType>(Ptr->getType());
878   if ((Ptr->isNullValue() || BasePtr != 0) &&
879       !DL.isNonIntegralPointerType(PTy)) {
880     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
881     return ConstantExpr::getIntToPtr(C, ResTy);
882   }
883
884   // Otherwise form a regular getelementptr. Recompute the indices so that
885   // we eliminate over-indexing of the notional static type array bounds.
886   // This makes it easy to determine if the getelementptr is "inbounds".
887   // Also, this helps GlobalOpt do SROA on GlobalVariables.
888   Type *Ty = PTy;
889   SmallVector<Constant *, 32> NewIdxs;
890
891   do {
892     if (!Ty->isStructTy()) {
893       if (Ty->isPointerTy()) {
894         // The only pointer indexing we'll do is on the first index of the GEP.
895         if (!NewIdxs.empty())
896           break;
897
898         Ty = SrcElemTy;
899
900         // Only handle pointers to sized types, not pointers to functions.
901         if (!Ty->isSized())
902           return nullptr;
903       } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
904         Ty = ATy->getElementType();
905       } else {
906         // We've reached some non-indexable type.
907         break;
908       }
909
910       // Determine which element of the array the offset points into.
911       APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
912       if (ElemSize == 0) {
913         // The element size is 0. This may be [0 x Ty]*, so just use a zero
914         // index for this level and proceed to the next level to see if it can
915         // accommodate the offset.
916         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
917       } else {
918         // The element size is non-zero divide the offset by the element
919         // size (rounding down), to compute the index at this level.
920         bool Overflow;
921         APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
922         if (Overflow)
923           break;
924         Offset -= NewIdx * ElemSize;
925         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
926       }
927     } else {
928       auto *STy = cast<StructType>(Ty);
929       // If we end up with an offset that isn't valid for this struct type, we
930       // can't re-form this GEP in a regular form, so bail out. The pointer
931       // operand likely went through casts that are necessary to make the GEP
932       // sensible.
933       const StructLayout &SL = *DL.getStructLayout(STy);
934       if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
935         break;
936
937       // Determine which field of the struct the offset points into. The
938       // getZExtValue is fine as we've already ensured that the offset is
939       // within the range representable by the StructLayout API.
940       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
941       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
942                                          ElIdx));
943       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
944       Ty = STy->getTypeAtIndex(ElIdx);
945     }
946   } while (Ty != ResElemTy);
947
948   // If we haven't used up the entire offset by descending the static
949   // type, then the offset is pointing into the middle of an indivisible
950   // member, so we can't simplify it.
951   if (Offset != 0)
952     return nullptr;
953
954   // Preserve the inrange index from the innermost GEP if possible. We must
955   // have calculated the same indices up to and including the inrange index.
956   Optional<unsigned> InRangeIndex;
957   if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
958     if (SrcElemTy == InnermostGEP->getSourceElementType() &&
959         NewIdxs.size() > *LastIRIndex) {
960       InRangeIndex = LastIRIndex;
961       for (unsigned I = 0; I <= *LastIRIndex; ++I)
962         if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) {
963           InRangeIndex = None;
964           break;
965         }
966     }
967
968   // Create a GEP.
969   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
970                                                InBounds, InRangeIndex);
971   assert(C->getType()->getPointerElementType() == Ty &&
972          "Computed GetElementPtr has unexpected type!");
973
974   // If we ended up indexing a member with a type that doesn't match
975   // the type of what the original indices indexed, add a cast.
976   if (Ty != ResElemTy)
977     C = FoldBitCast(C, ResTy, DL);
978
979   return C;
980 }
981
982 /// Attempt to constant fold an instruction with the
983 /// specified opcode and operands.  If successful, the constant result is
984 /// returned, if not, null is returned.  Note that this function can fail when
985 /// attempting to fold instructions like loads and stores, which have no
986 /// constant expression form.
987 ///
988 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/inrange
989 /// etc information, due to only being passed an opcode and operands. Constant
990 /// folding using this function strips this information.
991 ///
992 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
993                                        ArrayRef<Constant *> Ops,
994                                        const DataLayout &DL,
995                                        const TargetLibraryInfo *TLI) {
996   Type *DestTy = InstOrCE->getType();
997
998   // Handle easy binops first.
999   if (Instruction::isBinaryOp(Opcode))
1000     return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1001
1002   if (Instruction::isCast(Opcode))
1003     return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1004
1005   if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1006     if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1007       return C;
1008
1009     return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1010                                           Ops.slice(1), GEP->isInBounds(),
1011                                           GEP->getInRangeIndex());
1012   }
1013
1014   if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1015     return CE->getWithOperands(Ops);
1016
1017   switch (Opcode) {
1018   default: return nullptr;
1019   case Instruction::ICmp:
1020   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1021   case Instruction::Call:
1022     if (auto *F = dyn_cast<Function>(Ops.back()))
1023       if (canConstantFoldCallTo(F))
1024         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
1025     return nullptr;
1026   case Instruction::Select:
1027     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1028   case Instruction::ExtractElement:
1029     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1030   case Instruction::InsertElement:
1031     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1032   case Instruction::ShuffleVector:
1033     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1034   }
1035 }
1036
1037 } // end anonymous namespace
1038
1039 //===----------------------------------------------------------------------===//
1040 // Constant Folding public APIs
1041 //===----------------------------------------------------------------------===//
1042
1043 namespace {
1044
1045 Constant *
1046 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1047                          const TargetLibraryInfo *TLI,
1048                          SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1049   if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1050     return nullptr;
1051
1052   SmallVector<Constant *, 8> Ops;
1053   for (const Use &NewU : C->operands()) {
1054     auto *NewC = cast<Constant>(&NewU);
1055     // Recursively fold the ConstantExpr's operands. If we have already folded
1056     // a ConstantExpr, we don't have to process it again.
1057     if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1058       auto It = FoldedOps.find(NewC);
1059       if (It == FoldedOps.end()) {
1060         if (auto *FoldedC =
1061                 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
1062           FoldedOps.insert({NewC, FoldedC});
1063           NewC = FoldedC;
1064         } else {
1065           FoldedOps.insert({NewC, NewC});
1066         }
1067       } else {
1068         NewC = It->second;
1069       }
1070     }
1071     Ops.push_back(NewC);
1072   }
1073
1074   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1075     if (CE->isCompare())
1076       return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1077                                              DL, TLI);
1078
1079     return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
1080   }
1081
1082   assert(isa<ConstantVector>(C));
1083   return ConstantVector::get(Ops);
1084 }
1085
1086 } // end anonymous namespace
1087
1088 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1089                                         const TargetLibraryInfo *TLI) {
1090   // Handle PHI nodes quickly here...
1091   if (auto *PN = dyn_cast<PHINode>(I)) {
1092     Constant *CommonValue = nullptr;
1093
1094     SmallDenseMap<Constant *, Constant *> FoldedOps;
1095     for (Value *Incoming : PN->incoming_values()) {
1096       // If the incoming value is undef then skip it.  Note that while we could
1097       // skip the value if it is equal to the phi node itself we choose not to
1098       // because that would break the rule that constant folding only applies if
1099       // all operands are constants.
1100       if (isa<UndefValue>(Incoming))
1101         continue;
1102       // If the incoming value is not a constant, then give up.
1103       auto *C = dyn_cast<Constant>(Incoming);
1104       if (!C)
1105         return nullptr;
1106       // Fold the PHI's operands.
1107       if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1108         C = FoldedC;
1109       // If the incoming value is a different constant to
1110       // the one we saw previously, then give up.
1111       if (CommonValue && C != CommonValue)
1112         return nullptr;
1113       CommonValue = C;
1114     }
1115
1116     // If we reach here, all incoming values are the same constant or undef.
1117     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1118   }
1119
1120   // Scan the operand list, checking to see if they are all constants, if so,
1121   // hand off to ConstantFoldInstOperandsImpl.
1122   if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1123     return nullptr;
1124
1125   SmallDenseMap<Constant *, Constant *> FoldedOps;
1126   SmallVector<Constant *, 8> Ops;
1127   for (const Use &OpU : I->operands()) {
1128     auto *Op = cast<Constant>(&OpU);
1129     // Fold the Instruction's operands.
1130     if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1131       Op = FoldedOp;
1132
1133     Ops.push_back(Op);
1134   }
1135
1136   if (const auto *CI = dyn_cast<CmpInst>(I))
1137     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1138                                            DL, TLI);
1139
1140   if (const auto *LI = dyn_cast<LoadInst>(I))
1141     return ConstantFoldLoadInst(LI, DL);
1142
1143   if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
1144     return ConstantExpr::getInsertValue(
1145                                 cast<Constant>(IVI->getAggregateOperand()),
1146                                 cast<Constant>(IVI->getInsertedValueOperand()),
1147                                 IVI->getIndices());
1148   }
1149
1150   if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
1151     return ConstantExpr::getExtractValue(
1152                                     cast<Constant>(EVI->getAggregateOperand()),
1153                                     EVI->getIndices());
1154   }
1155
1156   return ConstantFoldInstOperands(I, Ops, DL, TLI);
1157 }
1158
1159 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1160                                      const TargetLibraryInfo *TLI) {
1161   SmallDenseMap<Constant *, Constant *> FoldedOps;
1162   return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1163 }
1164
1165 Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1166                                          ArrayRef<Constant *> Ops,
1167                                          const DataLayout &DL,
1168                                          const TargetLibraryInfo *TLI) {
1169   return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1170 }
1171
1172 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1173                                                 Constant *Ops0, Constant *Ops1,
1174                                                 const DataLayout &DL,
1175                                                 const TargetLibraryInfo *TLI) {
1176   // fold: icmp (inttoptr x), null         -> icmp x, 0
1177   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1178   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1179   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1180   //
1181   // FIXME: The following comment is out of data and the DataLayout is here now.
1182   // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1183   // around to know if bit truncation is happening.
1184   if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1185     if (Ops1->isNullValue()) {
1186       if (CE0->getOpcode() == Instruction::IntToPtr) {
1187         Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1188         // Convert the integer value to the right size to ensure we get the
1189         // proper extension or truncation.
1190         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1191                                                    IntPtrTy, false);
1192         Constant *Null = Constant::getNullValue(C->getType());
1193         return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1194       }
1195
1196       // Only do this transformation if the int is intptrty in size, otherwise
1197       // there is a truncation or extension that we aren't modeling.
1198       if (CE0->getOpcode() == Instruction::PtrToInt) {
1199         Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1200         if (CE0->getType() == IntPtrTy) {
1201           Constant *C = CE0->getOperand(0);
1202           Constant *Null = Constant::getNullValue(C->getType());
1203           return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1204         }
1205       }
1206     }
1207
1208     if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1209       if (CE0->getOpcode() == CE1->getOpcode()) {
1210         if (CE0->getOpcode() == Instruction::IntToPtr) {
1211           Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1212
1213           // Convert the integer value to the right size to ensure we get the
1214           // proper extension or truncation.
1215           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1216                                                       IntPtrTy, false);
1217           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1218                                                       IntPtrTy, false);
1219           return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1220         }
1221
1222         // Only do this transformation if the int is intptrty in size, otherwise
1223         // there is a truncation or extension that we aren't modeling.
1224         if (CE0->getOpcode() == Instruction::PtrToInt) {
1225           Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1226           if (CE0->getType() == IntPtrTy &&
1227               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1228             return ConstantFoldCompareInstOperands(
1229                 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1230           }
1231         }
1232       }
1233     }
1234
1235     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1236     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1237     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1238         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1239       Constant *LHS = ConstantFoldCompareInstOperands(
1240           Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1241       Constant *RHS = ConstantFoldCompareInstOperands(
1242           Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1243       unsigned OpC =
1244         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1245       return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1246     }
1247   }
1248
1249   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1250 }
1251
1252 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1253                                              Constant *RHS,
1254                                              const DataLayout &DL) {
1255   assert(Instruction::isBinaryOp(Opcode));
1256   if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1257     if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1258       return C;
1259
1260   return ConstantExpr::get(Opcode, LHS, RHS);
1261 }
1262
1263 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1264                                         Type *DestTy, const DataLayout &DL) {
1265   assert(Instruction::isCast(Opcode));
1266   switch (Opcode) {
1267   default:
1268     llvm_unreachable("Missing case");
1269   case Instruction::PtrToInt:
1270     // If the input is a inttoptr, eliminate the pair.  This requires knowing
1271     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1272     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1273       if (CE->getOpcode() == Instruction::IntToPtr) {
1274         Constant *Input = CE->getOperand(0);
1275         unsigned InWidth = Input->getType()->getScalarSizeInBits();
1276         unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1277         if (PtrWidth < InWidth) {
1278           Constant *Mask =
1279             ConstantInt::get(CE->getContext(),
1280                              APInt::getLowBitsSet(InWidth, PtrWidth));
1281           Input = ConstantExpr::getAnd(Input, Mask);
1282         }
1283         // Do a zext or trunc to get to the dest size.
1284         return ConstantExpr::getIntegerCast(Input, DestTy, false);
1285       }
1286     }
1287     return ConstantExpr::getCast(Opcode, C, DestTy);
1288   case Instruction::IntToPtr:
1289     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1290     // the int size is >= the ptr size and the address spaces are the same.
1291     // This requires knowing the width of a pointer, so it can't be done in
1292     // ConstantExpr::getCast.
1293     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1294       if (CE->getOpcode() == Instruction::PtrToInt) {
1295         Constant *SrcPtr = CE->getOperand(0);
1296         unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1297         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1298
1299         if (MidIntSize >= SrcPtrSize) {
1300           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1301           if (SrcAS == DestTy->getPointerAddressSpace())
1302             return FoldBitCast(CE->getOperand(0), DestTy, DL);
1303         }
1304       }
1305     }
1306
1307     return ConstantExpr::getCast(Opcode, C, DestTy);
1308   case Instruction::Trunc:
1309   case Instruction::ZExt:
1310   case Instruction::SExt:
1311   case Instruction::FPTrunc:
1312   case Instruction::FPExt:
1313   case Instruction::UIToFP:
1314   case Instruction::SIToFP:
1315   case Instruction::FPToUI:
1316   case Instruction::FPToSI:
1317   case Instruction::AddrSpaceCast:
1318       return ConstantExpr::getCast(Opcode, C, DestTy);
1319   case Instruction::BitCast:
1320     return FoldBitCast(C, DestTy, DL);
1321   }
1322 }
1323
1324 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1325                                                        ConstantExpr *CE) {
1326   if (!CE->getOperand(1)->isNullValue())
1327     return nullptr;  // Do not allow stepping over the value!
1328
1329   // Loop over all of the operands, tracking down which value we are
1330   // addressing.
1331   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1332     C = C->getAggregateElement(CE->getOperand(i));
1333     if (!C)
1334       return nullptr;
1335   }
1336   return C;
1337 }
1338
1339 Constant *
1340 llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1341                                         ArrayRef<Constant *> Indices) {
1342   // Loop over all of the operands, tracking down which value we are
1343   // addressing.
1344   for (Constant *Index : Indices) {
1345     C = C->getAggregateElement(Index);
1346     if (!C)
1347       return nullptr;
1348   }
1349   return C;
1350 }
1351
1352 //===----------------------------------------------------------------------===//
1353 //  Constant Folding for Calls
1354 //
1355
1356 bool llvm::canConstantFoldCallTo(const Function *F) {
1357   switch (F->getIntrinsicID()) {
1358   case Intrinsic::fabs:
1359   case Intrinsic::minnum:
1360   case Intrinsic::maxnum:
1361   case Intrinsic::log:
1362   case Intrinsic::log2:
1363   case Intrinsic::log10:
1364   case Intrinsic::exp:
1365   case Intrinsic::exp2:
1366   case Intrinsic::floor:
1367   case Intrinsic::ceil:
1368   case Intrinsic::sqrt:
1369   case Intrinsic::sin:
1370   case Intrinsic::cos:
1371   case Intrinsic::trunc:
1372   case Intrinsic::rint:
1373   case Intrinsic::nearbyint:
1374   case Intrinsic::pow:
1375   case Intrinsic::powi:
1376   case Intrinsic::bswap:
1377   case Intrinsic::ctpop:
1378   case Intrinsic::ctlz:
1379   case Intrinsic::cttz:
1380   case Intrinsic::fma:
1381   case Intrinsic::fmuladd:
1382   case Intrinsic::copysign:
1383   case Intrinsic::round:
1384   case Intrinsic::masked_load:
1385   case Intrinsic::sadd_with_overflow:
1386   case Intrinsic::uadd_with_overflow:
1387   case Intrinsic::ssub_with_overflow:
1388   case Intrinsic::usub_with_overflow:
1389   case Intrinsic::smul_with_overflow:
1390   case Intrinsic::umul_with_overflow:
1391   case Intrinsic::convert_from_fp16:
1392   case Intrinsic::convert_to_fp16:
1393   case Intrinsic::bitreverse:
1394   case Intrinsic::x86_sse_cvtss2si:
1395   case Intrinsic::x86_sse_cvtss2si64:
1396   case Intrinsic::x86_sse_cvttss2si:
1397   case Intrinsic::x86_sse_cvttss2si64:
1398   case Intrinsic::x86_sse2_cvtsd2si:
1399   case Intrinsic::x86_sse2_cvtsd2si64:
1400   case Intrinsic::x86_sse2_cvttsd2si:
1401   case Intrinsic::x86_sse2_cvttsd2si64:
1402     return true;
1403   default:
1404     return false;
1405   case Intrinsic::not_intrinsic: break;
1406   }
1407
1408   if (!F->hasName())
1409     return false;
1410   StringRef Name = F->getName();
1411
1412   // In these cases, the check of the length is required.  We don't want to
1413   // return true for a name like "cos\0blah" which strcmp would return equal to
1414   // "cos", but has length 8.
1415   switch (Name[0]) {
1416   default:
1417     return false;
1418   case 'a':
1419     return Name == "acos" || Name == "asin" || Name == "atan" ||
1420            Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1421            Name == "atanf" || Name == "atan2f";
1422   case 'c':
1423     return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1424            Name == "ceilf" || Name == "cosf" || Name == "coshf";
1425   case 'e':
1426     return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
1427   case 'f':
1428     return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1429            Name == "fabsf" || Name == "floorf" || Name == "fmodf";
1430   case 'l':
1431     return Name == "log" || Name == "log10" || Name == "logf" ||
1432            Name == "log10f";
1433   case 'p':
1434     return Name == "pow" || Name == "powf";
1435   case 'r':
1436     return Name == "round" || Name == "roundf";
1437   case 's':
1438     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1439            Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
1440   case 't':
1441     return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
1442   }
1443 }
1444
1445 namespace {
1446
1447 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1448   if (Ty->isHalfTy()) {
1449     APFloat APF(V);
1450     bool unused;
1451     APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
1452     return ConstantFP::get(Ty->getContext(), APF);
1453   }
1454   if (Ty->isFloatTy())
1455     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1456   if (Ty->isDoubleTy())
1457     return ConstantFP::get(Ty->getContext(), APFloat(V));
1458   llvm_unreachable("Can only constant fold half/float/double");
1459 }
1460
1461 /// Clear the floating-point exception state.
1462 inline void llvm_fenv_clearexcept() {
1463 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1464   feclearexcept(FE_ALL_EXCEPT);
1465 #endif
1466   errno = 0;
1467 }
1468
1469 /// Test if a floating-point exception was raised.
1470 inline bool llvm_fenv_testexcept() {
1471   int errno_val = errno;
1472   if (errno_val == ERANGE || errno_val == EDOM)
1473     return true;
1474 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1475   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1476     return true;
1477 #endif
1478   return false;
1479 }
1480
1481 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1482   llvm_fenv_clearexcept();
1483   V = NativeFP(V);
1484   if (llvm_fenv_testexcept()) {
1485     llvm_fenv_clearexcept();
1486     return nullptr;
1487   }
1488
1489   return GetConstantFoldFPValue(V, Ty);
1490 }
1491
1492 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1493                                double W, Type *Ty) {
1494   llvm_fenv_clearexcept();
1495   V = NativeFP(V, W);
1496   if (llvm_fenv_testexcept()) {
1497     llvm_fenv_clearexcept();
1498     return nullptr;
1499   }
1500
1501   return GetConstantFoldFPValue(V, Ty);
1502 }
1503
1504 /// Attempt to fold an SSE floating point to integer conversion of a constant
1505 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1506 /// used (toward nearest, ties to even). This matches the behavior of the
1507 /// non-truncating SSE instructions in the default rounding mode. The desired
1508 /// integer type Ty is used to select how many bits are available for the
1509 /// result. Returns null if the conversion cannot be performed, otherwise
1510 /// returns the Constant value resulting from the conversion.
1511 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1512                                       Type *Ty) {
1513   // All of these conversion intrinsics form an integer of at most 64bits.
1514   unsigned ResultWidth = Ty->getIntegerBitWidth();
1515   assert(ResultWidth <= 64 &&
1516          "Can only constant fold conversions to 64 and 32 bit ints");
1517
1518   uint64_t UIntVal;
1519   bool isExact = false;
1520   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1521                                               : APFloat::rmNearestTiesToEven;
1522   APFloat::opStatus status =
1523       Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1524                            /*isSigned=*/true, mode, &isExact);
1525   if (status != APFloat::opOK &&
1526       (!roundTowardZero || status != APFloat::opInexact))
1527     return nullptr;
1528   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1529 }
1530
1531 double getValueAsDouble(ConstantFP *Op) {
1532   Type *Ty = Op->getType();
1533
1534   if (Ty->isFloatTy())
1535     return Op->getValueAPF().convertToFloat();
1536
1537   if (Ty->isDoubleTy())
1538     return Op->getValueAPF().convertToDouble();
1539
1540   bool unused;
1541   APFloat APF = Op->getValueAPF();
1542   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1543   return APF.convertToDouble();
1544 }
1545
1546 Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1547                                  ArrayRef<Constant *> Operands,
1548                                  const TargetLibraryInfo *TLI) {
1549   if (Operands.size() == 1) {
1550     if (isa<UndefValue>(Operands[0])) {
1551       // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1552       if (IntrinsicID == Intrinsic::cos)
1553         return Constant::getNullValue(Ty);
1554     }
1555     if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1556       if (IntrinsicID == Intrinsic::convert_to_fp16) {
1557         APFloat Val(Op->getValueAPF());
1558
1559         bool lost = false;
1560         Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1561
1562         return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1563       }
1564
1565       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1566         return nullptr;
1567
1568       if (IntrinsicID == Intrinsic::round) {
1569         APFloat V = Op->getValueAPF();
1570         V.roundToIntegral(APFloat::rmNearestTiesToAway);
1571         return ConstantFP::get(Ty->getContext(), V);
1572       }
1573
1574       if (IntrinsicID == Intrinsic::floor) {
1575         APFloat V = Op->getValueAPF();
1576         V.roundToIntegral(APFloat::rmTowardNegative);
1577         return ConstantFP::get(Ty->getContext(), V);
1578       }
1579
1580       if (IntrinsicID == Intrinsic::ceil) {
1581         APFloat V = Op->getValueAPF();
1582         V.roundToIntegral(APFloat::rmTowardPositive);
1583         return ConstantFP::get(Ty->getContext(), V);
1584       }
1585
1586       if (IntrinsicID == Intrinsic::trunc) {
1587         APFloat V = Op->getValueAPF();
1588         V.roundToIntegral(APFloat::rmTowardZero);
1589         return ConstantFP::get(Ty->getContext(), V);
1590       }
1591
1592       if (IntrinsicID == Intrinsic::rint) {
1593         APFloat V = Op->getValueAPF();
1594         V.roundToIntegral(APFloat::rmNearestTiesToEven);
1595         return ConstantFP::get(Ty->getContext(), V);
1596       }
1597
1598       if (IntrinsicID == Intrinsic::nearbyint) {
1599         APFloat V = Op->getValueAPF();
1600         V.roundToIntegral(APFloat::rmNearestTiesToEven);
1601         return ConstantFP::get(Ty->getContext(), V);
1602       }
1603
1604       /// We only fold functions with finite arguments. Folding NaN and inf is
1605       /// likely to be aborted with an exception anyway, and some host libms
1606       /// have known errors raising exceptions.
1607       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1608         return nullptr;
1609
1610       /// Currently APFloat versions of these functions do not exist, so we use
1611       /// the host native double versions.  Float versions are not called
1612       /// directly but for all these it is true (float)(f((double)arg)) ==
1613       /// f(arg).  Long double not supported yet.
1614       double V = getValueAsDouble(Op);
1615
1616       switch (IntrinsicID) {
1617         default: break;
1618         case Intrinsic::fabs:
1619           return ConstantFoldFP(fabs, V, Ty);
1620         case Intrinsic::log2:
1621           return ConstantFoldFP(Log2, V, Ty);
1622         case Intrinsic::log:
1623           return ConstantFoldFP(log, V, Ty);
1624         case Intrinsic::log10:
1625           return ConstantFoldFP(log10, V, Ty);
1626         case Intrinsic::exp:
1627           return ConstantFoldFP(exp, V, Ty);
1628         case Intrinsic::exp2:
1629           return ConstantFoldFP(exp2, V, Ty);
1630         case Intrinsic::sin:
1631           return ConstantFoldFP(sin, V, Ty);
1632         case Intrinsic::cos:
1633           return ConstantFoldFP(cos, V, Ty);
1634         case Intrinsic::sqrt:
1635           return ConstantFoldFP(sqrt, V, Ty);
1636       }
1637
1638       if (!TLI)
1639         return nullptr;
1640
1641       switch (Name[0]) {
1642       case 'a':
1643         if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
1644             (Name == "acosf" && TLI->has(LibFunc_acosf)))
1645           return ConstantFoldFP(acos, V, Ty);
1646         else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
1647                  (Name == "asinf" && TLI->has(LibFunc_asinf)))
1648           return ConstantFoldFP(asin, V, Ty);
1649         else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1650                  (Name == "atanf" && TLI->has(LibFunc_atanf)))
1651           return ConstantFoldFP(atan, V, Ty);
1652         break;
1653       case 'c':
1654         if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1655             (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
1656           return ConstantFoldFP(ceil, V, Ty);
1657         else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1658                  (Name == "cosf" && TLI->has(LibFunc_cosf)))
1659           return ConstantFoldFP(cos, V, Ty);
1660         else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
1661                  (Name == "coshf" && TLI->has(LibFunc_coshf)))
1662           return ConstantFoldFP(cosh, V, Ty);
1663         break;
1664       case 'e':
1665         if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
1666             (Name == "expf" && TLI->has(LibFunc_expf)))
1667           return ConstantFoldFP(exp, V, Ty);
1668         if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
1669             (Name == "exp2f" && TLI->has(LibFunc_exp2f)))
1670           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1671           // C99 library.
1672           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1673         break;
1674       case 'f':
1675         if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1676             (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
1677           return ConstantFoldFP(fabs, V, Ty);
1678         else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1679                  (Name == "floorf" && TLI->has(LibFunc_floorf)))
1680           return ConstantFoldFP(floor, V, Ty);
1681         break;
1682       case 'l':
1683         if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
1684             (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)))
1685           return ConstantFoldFP(log, V, Ty);
1686         else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
1687                  (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)))
1688           return ConstantFoldFP(log10, V, Ty);
1689         break;
1690       case 'r':
1691         if ((Name == "round" && TLI->has(LibFunc_round)) ||
1692             (Name == "roundf" && TLI->has(LibFunc_roundf)))
1693           return ConstantFoldFP(round, V, Ty);
1694       case 's':
1695         if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1696             (Name == "sinf" && TLI->has(LibFunc_sinf)))
1697           return ConstantFoldFP(sin, V, Ty);
1698         else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
1699                  (Name == "sinhf" && TLI->has(LibFunc_sinhf)))
1700           return ConstantFoldFP(sinh, V, Ty);
1701         else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1702                  (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
1703           return ConstantFoldFP(sqrt, V, Ty);
1704         break;
1705       case 't':
1706         if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1707             (Name == "tanf" && TLI->has(LibFunc_tanf)))
1708           return ConstantFoldFP(tan, V, Ty);
1709         else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1710                  (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
1711           return ConstantFoldFP(tanh, V, Ty);
1712         break;
1713       default:
1714         break;
1715       }
1716       return nullptr;
1717     }
1718
1719     if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
1720       switch (IntrinsicID) {
1721       case Intrinsic::bswap:
1722         return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1723       case Intrinsic::ctpop:
1724         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1725       case Intrinsic::bitreverse:
1726         return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1727       case Intrinsic::convert_from_fp16: {
1728         APFloat Val(APFloat::IEEEhalf(), Op->getValue());
1729
1730         bool lost = false;
1731         APFloat::opStatus status = Val.convert(
1732             Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
1733
1734         // Conversion is always precise.
1735         (void)status;
1736         assert(status == APFloat::opOK && !lost &&
1737                "Precision lost during fp16 constfolding");
1738
1739         return ConstantFP::get(Ty->getContext(), Val);
1740       }
1741       default:
1742         return nullptr;
1743       }
1744     }
1745
1746     // Support ConstantVector in case we have an Undef in the top.
1747     if (isa<ConstantVector>(Operands[0]) ||
1748         isa<ConstantDataVector>(Operands[0])) {
1749       auto *Op = cast<Constant>(Operands[0]);
1750       switch (IntrinsicID) {
1751       default: break;
1752       case Intrinsic::x86_sse_cvtss2si:
1753       case Intrinsic::x86_sse_cvtss2si64:
1754       case Intrinsic::x86_sse2_cvtsd2si:
1755       case Intrinsic::x86_sse2_cvtsd2si64:
1756         if (ConstantFP *FPOp =
1757                 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1758           return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1759                                              /*roundTowardZero=*/false, Ty);
1760       case Intrinsic::x86_sse_cvttss2si:
1761       case Intrinsic::x86_sse_cvttss2si64:
1762       case Intrinsic::x86_sse2_cvttsd2si:
1763       case Intrinsic::x86_sse2_cvttsd2si64:
1764         if (ConstantFP *FPOp =
1765                 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1766           return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1767                                              /*roundTowardZero=*/true, Ty);
1768       }
1769     }
1770
1771     if (isa<UndefValue>(Operands[0])) {
1772       if (IntrinsicID == Intrinsic::bswap ||
1773           IntrinsicID == Intrinsic::bitreverse)
1774         return Operands[0];
1775       return nullptr;
1776     }
1777
1778     return nullptr;
1779   }
1780
1781   if (Operands.size() == 2) {
1782     if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1783       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1784         return nullptr;
1785       double Op1V = getValueAsDouble(Op1);
1786
1787       if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1788         if (Op2->getType() != Op1->getType())
1789           return nullptr;
1790
1791         double Op2V = getValueAsDouble(Op2);
1792         if (IntrinsicID == Intrinsic::pow) {
1793           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1794         }
1795         if (IntrinsicID == Intrinsic::copysign) {
1796           APFloat V1 = Op1->getValueAPF();
1797           const APFloat &V2 = Op2->getValueAPF();
1798           V1.copySign(V2);
1799           return ConstantFP::get(Ty->getContext(), V1);
1800         }
1801
1802         if (IntrinsicID == Intrinsic::minnum) {
1803           const APFloat &C1 = Op1->getValueAPF();
1804           const APFloat &C2 = Op2->getValueAPF();
1805           return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1806         }
1807
1808         if (IntrinsicID == Intrinsic::maxnum) {
1809           const APFloat &C1 = Op1->getValueAPF();
1810           const APFloat &C2 = Op2->getValueAPF();
1811           return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1812         }
1813
1814         if (!TLI)
1815           return nullptr;
1816         if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
1817             (Name == "powf" && TLI->has(LibFunc_powf)))
1818           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1819         if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1820             (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
1821           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1822         if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
1823             (Name == "atan2f" && TLI->has(LibFunc_atan2f)))
1824           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1825       } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1826         if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1827           return ConstantFP::get(Ty->getContext(),
1828                                  APFloat((float)std::pow((float)Op1V,
1829                                                  (int)Op2C->getZExtValue())));
1830         if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1831           return ConstantFP::get(Ty->getContext(),
1832                                  APFloat((float)std::pow((float)Op1V,
1833                                                  (int)Op2C->getZExtValue())));
1834         if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1835           return ConstantFP::get(Ty->getContext(),
1836                                  APFloat((double)std::pow((double)Op1V,
1837                                                    (int)Op2C->getZExtValue())));
1838       }
1839       return nullptr;
1840     }
1841
1842     if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1843       if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1844         switch (IntrinsicID) {
1845         default: break;
1846         case Intrinsic::sadd_with_overflow:
1847         case Intrinsic::uadd_with_overflow:
1848         case Intrinsic::ssub_with_overflow:
1849         case Intrinsic::usub_with_overflow:
1850         case Intrinsic::smul_with_overflow:
1851         case Intrinsic::umul_with_overflow: {
1852           APInt Res;
1853           bool Overflow;
1854           switch (IntrinsicID) {
1855           default: llvm_unreachable("Invalid case");
1856           case Intrinsic::sadd_with_overflow:
1857             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1858             break;
1859           case Intrinsic::uadd_with_overflow:
1860             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1861             break;
1862           case Intrinsic::ssub_with_overflow:
1863             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1864             break;
1865           case Intrinsic::usub_with_overflow:
1866             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1867             break;
1868           case Intrinsic::smul_with_overflow:
1869             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1870             break;
1871           case Intrinsic::umul_with_overflow:
1872             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1873             break;
1874           }
1875           Constant *Ops[] = {
1876             ConstantInt::get(Ty->getContext(), Res),
1877             ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1878           };
1879           return ConstantStruct::get(cast<StructType>(Ty), Ops);
1880         }
1881         case Intrinsic::cttz:
1882           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1883             return UndefValue::get(Ty);
1884           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1885         case Intrinsic::ctlz:
1886           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1887             return UndefValue::get(Ty);
1888           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1889         }
1890       }
1891
1892       return nullptr;
1893     }
1894     return nullptr;
1895   }
1896
1897   if (Operands.size() != 3)
1898     return nullptr;
1899
1900   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1901     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1902       if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1903         switch (IntrinsicID) {
1904         default: break;
1905         case Intrinsic::fma:
1906         case Intrinsic::fmuladd: {
1907           APFloat V = Op1->getValueAPF();
1908           APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1909                                                    Op3->getValueAPF(),
1910                                                    APFloat::rmNearestTiesToEven);
1911           if (s != APFloat::opInvalidOp)
1912             return ConstantFP::get(Ty->getContext(), V);
1913
1914           return nullptr;
1915         }
1916         }
1917       }
1918     }
1919   }
1920
1921   return nullptr;
1922 }
1923
1924 Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1925                                  VectorType *VTy, ArrayRef<Constant *> Operands,
1926                                  const DataLayout &DL,
1927                                  const TargetLibraryInfo *TLI) {
1928   SmallVector<Constant *, 4> Result(VTy->getNumElements());
1929   SmallVector<Constant *, 4> Lane(Operands.size());
1930   Type *Ty = VTy->getElementType();
1931
1932   if (IntrinsicID == Intrinsic::masked_load) {
1933     auto *SrcPtr = Operands[0];
1934     auto *Mask = Operands[2];
1935     auto *Passthru = Operands[3];
1936
1937     Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
1938
1939     SmallVector<Constant *, 32> NewElements;
1940     for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1941       auto *MaskElt = Mask->getAggregateElement(I);
1942       if (!MaskElt)
1943         break;
1944       auto *PassthruElt = Passthru->getAggregateElement(I);
1945       auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
1946       if (isa<UndefValue>(MaskElt)) {
1947         if (PassthruElt)
1948           NewElements.push_back(PassthruElt);
1949         else if (VecElt)
1950           NewElements.push_back(VecElt);
1951         else
1952           return nullptr;
1953       }
1954       if (MaskElt->isNullValue()) {
1955         if (!PassthruElt)
1956           return nullptr;
1957         NewElements.push_back(PassthruElt);
1958       } else if (MaskElt->isOneValue()) {
1959         if (!VecElt)
1960           return nullptr;
1961         NewElements.push_back(VecElt);
1962       } else {
1963         return nullptr;
1964       }
1965     }
1966     if (NewElements.size() != VTy->getNumElements())
1967       return nullptr;
1968     return ConstantVector::get(NewElements);
1969   }
1970
1971   for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1972     // Gather a column of constants.
1973     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1974       Constant *Agg = Operands[J]->getAggregateElement(I);
1975       if (!Agg)
1976         return nullptr;
1977
1978       Lane[J] = Agg;
1979     }
1980
1981     // Use the regular scalar folding to simplify this column.
1982     Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1983     if (!Folded)
1984       return nullptr;
1985     Result[I] = Folded;
1986   }
1987
1988   return ConstantVector::get(Result);
1989 }
1990
1991 } // end anonymous namespace
1992
1993 Constant *
1994 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1995                        const TargetLibraryInfo *TLI) {
1996   if (!F->hasName())
1997     return nullptr;
1998   StringRef Name = F->getName();
1999
2000   Type *Ty = F->getReturnType();
2001
2002   if (auto *VTy = dyn_cast<VectorType>(Ty))
2003     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2004                                   F->getParent()->getDataLayout(), TLI);
2005
2006   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
2007 }
2008
2009 bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
2010   // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2011   // (and to some extent ConstantFoldScalarCall).
2012   Function *F = CS.getCalledFunction();
2013   if (!F)
2014     return false;
2015
2016   LibFunc Func;
2017   if (!TLI || !TLI->getLibFunc(*F, Func))
2018     return false;
2019
2020   if (CS.getNumArgOperands() == 1) {
2021     if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2022       const APFloat &Op = OpC->getValueAPF();
2023       switch (Func) {
2024       case LibFunc_logl:
2025       case LibFunc_log:
2026       case LibFunc_logf:
2027       case LibFunc_log2l:
2028       case LibFunc_log2:
2029       case LibFunc_log2f:
2030       case LibFunc_log10l:
2031       case LibFunc_log10:
2032       case LibFunc_log10f:
2033         return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2034
2035       case LibFunc_expl:
2036       case LibFunc_exp:
2037       case LibFunc_expf:
2038         // FIXME: These boundaries are slightly conservative.
2039         if (OpC->getType()->isDoubleTy())
2040           return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2041                  Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2042         if (OpC->getType()->isFloatTy())
2043           return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2044                  Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2045         break;
2046
2047       case LibFunc_exp2l:
2048       case LibFunc_exp2:
2049       case LibFunc_exp2f:
2050         // FIXME: These boundaries are slightly conservative.
2051         if (OpC->getType()->isDoubleTy())
2052           return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2053                  Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2054         if (OpC->getType()->isFloatTy())
2055           return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2056                  Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2057         break;
2058
2059       case LibFunc_sinl:
2060       case LibFunc_sin:
2061       case LibFunc_sinf:
2062       case LibFunc_cosl:
2063       case LibFunc_cos:
2064       case LibFunc_cosf:
2065         return !Op.isInfinity();
2066
2067       case LibFunc_tanl:
2068       case LibFunc_tan:
2069       case LibFunc_tanf: {
2070         // FIXME: Stop using the host math library.
2071         // FIXME: The computation isn't done in the right precision.
2072         Type *Ty = OpC->getType();
2073         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2074           double OpV = getValueAsDouble(OpC);
2075           return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2076         }
2077         break;
2078       }
2079
2080       case LibFunc_asinl:
2081       case LibFunc_asin:
2082       case LibFunc_asinf:
2083       case LibFunc_acosl:
2084       case LibFunc_acos:
2085       case LibFunc_acosf:
2086         return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2087                    APFloat::cmpLessThan &&
2088                Op.compare(APFloat(Op.getSemantics(), "1")) !=
2089                    APFloat::cmpGreaterThan;
2090
2091       case LibFunc_sinh:
2092       case LibFunc_cosh:
2093       case LibFunc_sinhf:
2094       case LibFunc_coshf:
2095       case LibFunc_sinhl:
2096       case LibFunc_coshl:
2097         // FIXME: These boundaries are slightly conservative.
2098         if (OpC->getType()->isDoubleTy())
2099           return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2100                  Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2101         if (OpC->getType()->isFloatTy())
2102           return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2103                  Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2104         break;
2105
2106       case LibFunc_sqrtl:
2107       case LibFunc_sqrt:
2108       case LibFunc_sqrtf:
2109         return Op.isNaN() || Op.isZero() || !Op.isNegative();
2110
2111       // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2112       // maybe others?
2113       default:
2114         break;
2115       }
2116     }
2117   }
2118
2119   if (CS.getNumArgOperands() == 2) {
2120     ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2121     ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2122     if (Op0C && Op1C) {
2123       const APFloat &Op0 = Op0C->getValueAPF();
2124       const APFloat &Op1 = Op1C->getValueAPF();
2125
2126       switch (Func) {
2127       case LibFunc_powl:
2128       case LibFunc_pow:
2129       case LibFunc_powf: {
2130         // FIXME: Stop using the host math library.
2131         // FIXME: The computation isn't done in the right precision.
2132         Type *Ty = Op0C->getType();
2133         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2134           if (Ty == Op1C->getType()) {
2135             double Op0V = getValueAsDouble(Op0C);
2136             double Op1V = getValueAsDouble(Op1C);
2137             return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2138           }
2139         }
2140         break;
2141       }
2142
2143       case LibFunc_fmodl:
2144       case LibFunc_fmod:
2145       case LibFunc_fmodf:
2146         return Op0.isNaN() || Op1.isNaN() ||
2147                (!Op0.isInfinity() && !Op1.isZero());
2148
2149       default:
2150         break;
2151       }
2152     }
2153   }
2154
2155   return false;
2156 }