1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines routines for folding instructions into constants.
10 //
11 // Also, to supplement the basic IR ConstantExpr simplifications,
12 // this file defines some additional folding routines that can make use of
13 // DataLayout information. These functions cannot go in IR due to library
14 // dependency issues.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/APSInt.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Analysis/TargetFolder.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Analysis/VectorUtils.h"
31 #include "llvm/Config/config.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalValue.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/InstrTypes.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/IntrinsicsAArch64.h"
45 #include "llvm/IR/IntrinsicsAMDGPU.h"
46 #include "llvm/IR/IntrinsicsARM.h"
47 #include "llvm/IR/IntrinsicsWebAssembly.h"
48 #include "llvm/IR/IntrinsicsX86.h"
49 #include "llvm/IR/Operator.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/KnownBits.h"
55 #include "llvm/Support/MathExtras.h"
56 #include <cassert>
57 #include <cerrno>
58 #include <cfenv>
59 #include <cmath>
60 #include <cstdint>
61 
62 using namespace llvm;
63 
64 namespace {
65 
66 //===----------------------------------------------------------------------===//
67 // Constant Folding internal helper functions
68 //===----------------------------------------------------------------------===//
69 
70 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
71                                         Constant *C, Type *SrcEltTy,
72                                         unsigned NumSrcElts,
73                                         const DataLayout &DL) {
74   // Now that we know that the input value is a vector of integers, just shift
75   // and insert them into our result.
76   unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
77   for (unsigned i = 0; i != NumSrcElts; ++i) {
78     Constant *Element;
79     if (DL.isLittleEndian())
80       Element = C->getAggregateElement(NumSrcElts - i - 1);
81     else
82       Element = C->getAggregateElement(i);
83 
84     if (Element && isa<UndefValue>(Element)) {
85       Result <<= BitShift;
86       continue;
87     }
88 
89     auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
90     if (!ElementCI)
91       return ConstantExpr::getBitCast(C, DestTy);
92 
93     Result <<= BitShift;
94     Result |= ElementCI->getValue().zext(Result.getBitWidth());
95   }
96 
97   return nullptr;
98 }
99 
100 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
101 /// This always returns a non-null constant, but it may be a
102 /// ConstantExpr if unfoldable.
103 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
104   assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&
105          "Invalid constantexpr bitcast!");
106 
107   // Catch the obvious splat cases.
108   if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
109     return Res;
110 
111   if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
112     // Handle a vector->scalar integer/fp cast.
113     if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
114       unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements();
115       Type *SrcEltTy = VTy->getElementType();
116 
117       // If the vector is a vector of floating point, convert it to vector of int
118       // to simplify things.
119       if (SrcEltTy->isFloatingPointTy()) {
120         unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
121         auto *SrcIVTy = FixedVectorType::get(
122             IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
123         // Ask IR to do the conversion now that #elts line up.
124         C = ConstantExpr::getBitCast(C, SrcIVTy);
125       }
126 
127       APInt Result(DL.getTypeSizeInBits(DestTy), 0);
128       if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
129                                                 SrcEltTy, NumSrcElts, DL))
130         return CE;
131 
132       if (isa<IntegerType>(DestTy))
133         return ConstantInt::get(DestTy, Result);
134 
135       APFloat FP(DestTy->getFltSemantics(), Result);
136       return ConstantFP::get(DestTy->getContext(), FP);
137     }
138   }
139 
140   // The code below only handles casts to vectors currently.
141   auto *DestVTy = dyn_cast<VectorType>(DestTy);
142   if (!DestVTy)
143     return ConstantExpr::getBitCast(C, DestTy);
144 
145   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
146   // vector so the code below can handle it uniformly.
147   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
148     Constant *Ops = C; // don't take the address of C!
149     return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
150   }
151 
152   // If this is a bitcast from constant vector -> vector, fold it.
153   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
154     return ConstantExpr::getBitCast(C, DestTy);
155 
156   // If the element types match, IR can fold it.
157   unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements();
158   unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements();
159   if (NumDstElt == NumSrcElt)
160     return ConstantExpr::getBitCast(C, DestTy);
161 
162   Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType();
163   Type *DstEltTy = DestVTy->getElementType();
164 
165   // Otherwise, we're changing the number of elements in a vector, which
166   // requires endianness information to do the right thing.  For example,
167   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
168   // folds to (little endian):
169   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
170   // and to (big endian):
171   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
172 
173   // First thing is first.  We only want to think about integer here, so if
174   // we have something in FP form, recast it as integer.
175   if (DstEltTy->isFloatingPointTy()) {
176     // Fold to an vector of integers with same size as our FP type.
177     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
178     auto *DestIVTy = FixedVectorType::get(
179         IntegerType::get(C->getContext(), FPWidth), NumDstElt);
180     // Recursively handle this integer conversion, if possible.
181     C = FoldBitCast(C, DestIVTy, DL);
182 
183     // Finally, IR can handle this now that #elts line up.
184     return ConstantExpr::getBitCast(C, DestTy);
185   }
186 
187   // Okay, we know the destination is integer, if the input is FP, convert
188   // it to integer first.
189   if (SrcEltTy->isFloatingPointTy()) {
190     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
191     auto *SrcIVTy = FixedVectorType::get(
192         IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
193     // Ask IR to do the conversion now that #elts line up.
194     C = ConstantExpr::getBitCast(C, SrcIVTy);
195     // If IR wasn't able to fold it, bail out.
196     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
197         !isa<ConstantDataVector>(C))
198       return C;
199   }
200 
201   // Now we know that the input and output vectors are both integer vectors
202   // of the same size, and that their #elements is not the same.  Do the
203   // conversion here, which depends on whether the input or output has
204   // more elements.
205   bool isLittleEndian = DL.isLittleEndian();
206 
207   SmallVector<Constant*, 32> Result;
208   if (NumDstElt < NumSrcElt) {
209     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
210     Constant *Zero = Constant::getNullValue(DstEltTy);
211     unsigned Ratio = NumSrcElt/NumDstElt;
212     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
213     unsigned SrcElt = 0;
214     for (unsigned i = 0; i != NumDstElt; ++i) {
215       // Build each element of the result.
216       Constant *Elt = Zero;
217       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
218       for (unsigned j = 0; j != Ratio; ++j) {
219         Constant *Src = C->getAggregateElement(SrcElt++);
220         if (Src && isa<UndefValue>(Src))
221           Src = Constant::getNullValue(
222               cast<VectorType>(C->getType())->getElementType());
223         else
224           Src = dyn_cast_or_null<ConstantInt>(Src);
225         if (!Src)  // Reject constantexpr elements.
226           return ConstantExpr::getBitCast(C, DestTy);
227 
228         // Zero extend the element to the right size.
229         Src = ConstantExpr::getZExt(Src, Elt->getType());
230 
231         // Shift it to the right place, depending on endianness.
232         Src = ConstantExpr::getShl(Src,
233                                    ConstantInt::get(Src->getType(), ShiftAmt));
234         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
235 
236         // Mix it in.
237         Elt = ConstantExpr::getOr(Elt, Src);
238       }
239       Result.push_back(Elt);
240     }
241     return ConstantVector::get(Result);
242   }
243 
244   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
245   unsigned Ratio = NumDstElt/NumSrcElt;
246   unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
247 
248   // Loop over each source value, expanding into multiple results.
249   for (unsigned i = 0; i != NumSrcElt; ++i) {
250     auto *Element = C->getAggregateElement(i);
251 
252     if (!Element) // Reject constantexpr elements.
253       return ConstantExpr::getBitCast(C, DestTy);
254 
255     if (isa<UndefValue>(Element)) {
256       // Correctly Propagate undef values.
257       Result.append(Ratio, UndefValue::get(DstEltTy));
258       continue;
259     }
260 
261     auto *Src = dyn_cast<ConstantInt>(Element);
262     if (!Src)
263       return ConstantExpr::getBitCast(C, DestTy);
264 
265     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
266     for (unsigned j = 0; j != Ratio; ++j) {
267       // Shift the piece of the value into the right place, depending on
268       // endianness.
269       Constant *Elt = ConstantExpr::getLShr(Src,
270                                   ConstantInt::get(Src->getType(), ShiftAmt));
271       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
272 
273       // Truncate the element to an integer with the same pointer size and
274       // convert the element back to a pointer using a inttoptr.
275       if (DstEltTy->isPointerTy()) {
276         IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
277         Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
278         Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
279         continue;
280       }
281 
282       // Truncate and remember this piece.
283       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
284     }
285   }
286 
287   return ConstantVector::get(Result);
288 }
289 
290 } // end anonymous namespace
291 
292 /// If this constant is a constant offset from a global, return the global and
293 /// the constant. Because of constantexprs, this function is recursive.
294 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
295                                       APInt &Offset, const DataLayout &DL,
296                                       DSOLocalEquivalent **DSOEquiv) {
297   if (DSOEquiv)
298     *DSOEquiv = nullptr;
299 
300   // Trivial case, constant is the global.
301   if ((GV = dyn_cast<GlobalValue>(C))) {
302     unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
303     Offset = APInt(BitWidth, 0);
304     return true;
305   }
306 
307   if (auto *FoundDSOEquiv = dyn_cast<DSOLocalEquivalent>(C)) {
308     if (DSOEquiv)
309       *DSOEquiv = FoundDSOEquiv;
310     GV = FoundDSOEquiv->getGlobalValue();
311     unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
312     Offset = APInt(BitWidth, 0);
313     return true;
314   }
315 
316   // Otherwise, if this isn't a constant expr, bail out.
317   auto *CE = dyn_cast<ConstantExpr>(C);
318   if (!CE) return false;
319 
320   // Look through ptr->int and ptr->ptr casts.
321   if (CE->getOpcode() == Instruction::PtrToInt ||
322       CE->getOpcode() == Instruction::BitCast)
323     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL,
324                                       DSOEquiv);
325 
326   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
327   auto *GEP = dyn_cast<GEPOperator>(CE);
328   if (!GEP)
329     return false;
330 
331   unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
332   APInt TmpOffset(BitWidth, 0);
333 
334   // If the base isn't a global+constant, we aren't either.
335   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL,
336                                   DSOEquiv))
337     return false;
338 
339   // Otherwise, add any offset that our operands provide.
340   if (!GEP->accumulateConstantOffset(DL, TmpOffset))
341     return false;
342 
343   Offset = TmpOffset;
344   return true;
345 }
346 
347 Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
348                                          const DataLayout &DL) {
349   do {
350     Type *SrcTy = C->getType();
351     if (SrcTy == DestTy)
352       return C;
353 
354     TypeSize DestSize = DL.getTypeSizeInBits(DestTy);
355     TypeSize SrcSize = DL.getTypeSizeInBits(SrcTy);
356     if (!TypeSize::isKnownGE(SrcSize, DestSize))
357       return nullptr;
358 
359     // Catch the obvious splat cases (since all-zeros can coerce non-integral
360     // pointers legally).
361     if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
362       return Res;
363 
364     // If the type sizes are the same and a cast is legal, just directly
365     // cast the constant.
366     // But be careful not to coerce non-integral pointers illegally.
367     if (SrcSize == DestSize &&
368         DL.isNonIntegralPointerType(SrcTy->getScalarType()) ==
369             DL.isNonIntegralPointerType(DestTy->getScalarType())) {
370       Instruction::CastOps Cast = Instruction::BitCast;
371       // If we are going from a pointer to int or vice versa, we spell the cast
372       // differently.
373       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
374         Cast = Instruction::IntToPtr;
375       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
376         Cast = Instruction::PtrToInt;
377 
378       if (CastInst::castIsValid(Cast, C, DestTy))
379         return ConstantExpr::getCast(Cast, C, DestTy);
380     }
381 
382     // If this isn't an aggregate type, there is nothing we can do to drill down
383     // and find a bitcastable constant.
384     if (!SrcTy->isAggregateType() && !SrcTy->isVectorTy())
385       return nullptr;
386 
387     // We're simulating a load through a pointer that was bitcast to point to
388     // a different type, so we can try to walk down through the initial
389     // elements of an aggregate to see if some part of the aggregate is
390     // castable to implement the "load" semantic model.
391     if (SrcTy->isStructTy()) {
392       // Struct types might have leading zero-length elements like [0 x i32],
393       // which are certainly not what we are looking for, so skip them.
394       unsigned Elem = 0;
395       Constant *ElemC;
396       do {
397         ElemC = C->getAggregateElement(Elem++);
398       } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero());
399       C = ElemC;
400     } else {
401       // For non-byte-sized vector elements, the first element is not
402       // necessarily located at the vector base address.
403       if (auto *VT = dyn_cast<VectorType>(SrcTy))
404         if (!DL.typeSizeEqualsStoreSize(VT->getElementType()))
405           return nullptr;
406 
407       C = C->getAggregateElement(0u);
408     }
409   } while (C);
410 
411   return nullptr;
412 }
413 
414 namespace {
415 
416 /// Recursive helper to read bits out of global. C is the constant being copied
417 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
418 /// results into and BytesLeft is the number of bytes left in
419 /// the CurPtr buffer. DL is the DataLayout.
420 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
421                         unsigned BytesLeft, const DataLayout &DL) {
422   assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
423          "Out of range access");
424 
425   // If this element is zero or undefined, we can just return since *CurPtr is
426   // zero initialized.
427   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
428     return true;
429 
430   if (auto *CI = dyn_cast<ConstantInt>(C)) {
431     if (CI->getBitWidth() > 64 ||
432         (CI->getBitWidth() & 7) != 0)
433       return false;
434 
435     uint64_t Val = CI->getZExtValue();
436     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
437 
438     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
439       int n = ByteOffset;
440       if (!DL.isLittleEndian())
441         n = IntBytes - n - 1;
442       CurPtr[i] = (unsigned char)(Val >> (n * 8));
443       ++ByteOffset;
444     }
445     return true;
446   }
447 
448   if (auto *CFP = dyn_cast<ConstantFP>(C)) {
449     if (CFP->getType()->isDoubleTy()) {
450       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
451       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
452     }
453     if (CFP->getType()->isFloatTy()){
454       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
455       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
456     }
457     if (CFP->getType()->isHalfTy()){
458       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
459       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
460     }
461     return false;
462   }
463 
464   if (auto *CS = dyn_cast<ConstantStruct>(C)) {
465     const StructLayout *SL = DL.getStructLayout(CS->getType());
466     unsigned Index = SL->getElementContainingOffset(ByteOffset);
467     uint64_t CurEltOffset = SL->getElementOffset(Index);
468     ByteOffset -= CurEltOffset;
469 
470     while (true) {
471       // If the element access is to the element itself and not to tail padding,
472       // read the bytes from the element.
473       uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
474 
475       if (ByteOffset < EltSize &&
476           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
477                               BytesLeft, DL))
478         return false;
479 
480       ++Index;
481 
482       // Check to see if we read from the last struct element, if so we're done.
483       if (Index == CS->getType()->getNumElements())
484         return true;
485 
486       // If we read all of the bytes we needed from this element we're done.
487       uint64_t NextEltOffset = SL->getElementOffset(Index);
488 
489       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
490         return true;
491 
492       // Move to the next element of the struct.
493       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
494       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
495       ByteOffset = 0;
496       CurEltOffset = NextEltOffset;
497     }
498     // not reached.
499   }
500 
501   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
502       isa<ConstantDataSequential>(C)) {
503     uint64_t NumElts;
504     Type *EltTy;
505     if (auto *AT = dyn_cast<ArrayType>(C->getType())) {
506       NumElts = AT->getNumElements();
507       EltTy = AT->getElementType();
508     } else {
509       NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
510       EltTy = cast<FixedVectorType>(C->getType())->getElementType();
511     }
512     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
513     uint64_t Index = ByteOffset / EltSize;
514     uint64_t Offset = ByteOffset - Index * EltSize;
515 
516     for (; Index != NumElts; ++Index) {
517       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
518                               BytesLeft, DL))
519         return false;
520 
521       uint64_t BytesWritten = EltSize - Offset;
522       assert(BytesWritten <= EltSize && "Not indexing into this element?");
523       if (BytesWritten >= BytesLeft)
524         return true;
525 
526       Offset = 0;
527       BytesLeft -= BytesWritten;
528       CurPtr += BytesWritten;
529     }
530     return true;
531   }
532 
533   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
534     if (CE->getOpcode() == Instruction::IntToPtr &&
535         CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
536       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
537                                 BytesLeft, DL);
538     }
539   }
540 
541   // Otherwise, unknown initializer type.
542   return false;
543 }
544 
545 Constant *FoldReinterpretLoadFromConst(Constant *C, Type *LoadTy,
546                                        int64_t Offset, const DataLayout &DL) {
547   // Bail out early. Not expect to load from scalable global variable.
548   if (isa<ScalableVectorType>(LoadTy))
549     return nullptr;
550 
551   auto *IntType = dyn_cast<IntegerType>(LoadTy);
552 
553   // If this isn't an integer load we can't fold it directly.
554   if (!IntType) {
555     // If this is a non-integer load, we can try folding it as an int load and
556     // then bitcast the result.  This can be useful for union cases.  Note
557     // that address spaces don't matter here since we're not going to result in
558     // an actual new load.
559     if (!LoadTy->isFloatingPointTy() && !LoadTy->isPointerTy() &&
560         !LoadTy->isVectorTy())
561       return nullptr;
562 
563     Type *MapTy = Type::getIntNTy(
564           C->getContext(), DL.getTypeSizeInBits(LoadTy).getFixedSize());
565     if (Constant *Res = FoldReinterpretLoadFromConst(C, MapTy, Offset, DL)) {
566       if (Res->isNullValue() && !LoadTy->isX86_MMXTy() &&
567           !LoadTy->isX86_AMXTy())
568         // Materializing a zero can be done trivially without a bitcast
569         return Constant::getNullValue(LoadTy);
570       Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
571       Res = FoldBitCast(Res, CastTy, DL);
572       if (LoadTy->isPtrOrPtrVectorTy()) {
573         // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
574         if (Res->isNullValue() && !LoadTy->isX86_MMXTy() &&
575             !LoadTy->isX86_AMXTy())
576           return Constant::getNullValue(LoadTy);
577         if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
578           // Be careful not to replace a load of an addrspace value with an inttoptr here
579           return nullptr;
580         Res = ConstantExpr::getCast(Instruction::IntToPtr, Res, LoadTy);
581       }
582       return Res;
583     }
584     return nullptr;
585   }
586 
587   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
588   if (BytesLoaded > 32 || BytesLoaded == 0)
589     return nullptr;
590 
591   // If we're not accessing anything in this constant, the result is undefined.
592   if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
593     return UndefValue::get(IntType);
594 
595   // TODO: We should be able to support scalable types.
596   TypeSize InitializerSize = DL.getTypeAllocSize(C->getType());
597   if (InitializerSize.isScalable())
598     return nullptr;
599 
600   // If we're not accessing anything in this constant, the result is undefined.
601   if (Offset >= (int64_t)InitializerSize.getFixedValue())
602     return UndefValue::get(IntType);
603 
604   unsigned char RawBytes[32] = {0};
605   unsigned char *CurPtr = RawBytes;
606   unsigned BytesLeft = BytesLoaded;
607 
608   // If we're loading off the beginning of the global, some bytes may be valid.
609   if (Offset < 0) {
610     CurPtr += -Offset;
611     BytesLeft += Offset;
612     Offset = 0;
613   }
614 
615   if (!ReadDataFromGlobal(C, Offset, CurPtr, BytesLeft, DL))
616     return nullptr;
617 
618   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
619   if (DL.isLittleEndian()) {
620     ResultVal = RawBytes[BytesLoaded - 1];
621     for (unsigned i = 1; i != BytesLoaded; ++i) {
622       ResultVal <<= 8;
623       ResultVal |= RawBytes[BytesLoaded - 1 - i];
624     }
625   } else {
626     ResultVal = RawBytes[0];
627     for (unsigned i = 1; i != BytesLoaded; ++i) {
628       ResultVal <<= 8;
629       ResultVal |= RawBytes[i];
630     }
631   }
632 
633   return ConstantInt::get(IntType->getContext(), ResultVal);
634 }
635 
636 } // anonymous namespace
637 
638 // If GV is a constant with an initializer read its representation starting
639 // at Offset and return it as a constant array of unsigned char.  Otherwise
640 // return null.
641 Constant *llvm::ReadByteArrayFromGlobal(const GlobalVariable *GV,
642                                         uint64_t Offset) {
643   if (!GV->isConstant() || !GV->hasDefinitiveInitializer())
644     return nullptr;
645 
646   const DataLayout &DL = GV->getParent()->getDataLayout();
647   Constant *Init = const_cast<Constant *>(GV->getInitializer());
648   TypeSize InitSize = DL.getTypeAllocSize(Init->getType());
649   if (InitSize < Offset)
650     return nullptr;
651 
652   uint64_t NBytes = InitSize - Offset;
653   if (NBytes > UINT16_MAX)
654     // Bail for large initializers in excess of 64K to avoid allocating
655     // too much memory.
656     // Offset is assumed to be less than or equal than InitSize (this
657     // is enforced in ReadDataFromGlobal).
658     return nullptr;
659 
660   SmallVector<unsigned char, 256> RawBytes(static_cast<size_t>(NBytes));
661   unsigned char *CurPtr = RawBytes.data();
662 
663   if (!ReadDataFromGlobal(Init, Offset, CurPtr, NBytes, DL))
664     return nullptr;
665 
666   return ConstantDataArray::get(GV->getContext(), RawBytes);
667 }
668 
669 /// If this Offset points exactly to the start of an aggregate element, return
670 /// that element, otherwise return nullptr.
671 Constant *getConstantAtOffset(Constant *Base, APInt Offset,
672                               const DataLayout &DL) {
673   if (Offset.isZero())
674     return Base;
675 
676   if (!isa<ConstantAggregate>(Base) && !isa<ConstantDataSequential>(Base))
677     return nullptr;
678 
679   Type *ElemTy = Base->getType();
680   SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
681   if (!Offset.isZero() || !Indices[0].isZero())
682     return nullptr;
683 
684   Constant *C = Base;
685   for (const APInt &Index : drop_begin(Indices)) {
686     if (Index.isNegative() || Index.getActiveBits() >= 32)
687       return nullptr;
688 
689     C = C->getAggregateElement(Index.getZExtValue());
690     if (!C)
691       return nullptr;
692   }
693 
694   return C;
695 }
696 
697 Constant *llvm::ConstantFoldLoadFromConst(Constant *C, Type *Ty,
698                                           const APInt &Offset,
699                                           const DataLayout &DL) {
700   if (Constant *AtOffset = getConstantAtOffset(C, Offset, DL))
701     if (Constant *Result = ConstantFoldLoadThroughBitcast(AtOffset, Ty, DL))
702       return Result;
703 
704   // Explicitly check for out-of-bounds access, so we return undef even if the
705   // constant is a uniform value.
706   TypeSize Size = DL.getTypeAllocSize(C->getType());
707   if (!Size.isScalable() && Offset.sge(Size.getFixedSize()))
708     return UndefValue::get(Ty);
709 
710   // Try an offset-independent fold of a uniform value.
711   if (Constant *Result = ConstantFoldLoadFromUniformValue(C, Ty))
712     return Result;
713 
714   // Try hard to fold loads from bitcasted strange and non-type-safe things.
715   if (Offset.getMinSignedBits() <= 64)
716     if (Constant *Result =
717             FoldReinterpretLoadFromConst(C, Ty, Offset.getSExtValue(), DL))
718       return Result;
719 
720   return nullptr;
721 }
722 
723 Constant *llvm::ConstantFoldLoadFromConst(Constant *C, Type *Ty,
724                                           const DataLayout &DL) {
725   return ConstantFoldLoadFromConst(C, Ty, APInt(64, 0), DL);
726 }
727 
728 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
729                                              APInt Offset,
730                                              const DataLayout &DL) {
731   C = cast<Constant>(C->stripAndAccumulateConstantOffsets(
732           DL, Offset, /* AllowNonInbounds */ true));
733 
734   if (auto *GV = dyn_cast<GlobalVariable>(C))
735     if (GV->isConstant() && GV->hasDefinitiveInitializer())
736       if (Constant *Result = ConstantFoldLoadFromConst(GV->getInitializer(), Ty,
737                                                        Offset, DL))
738         return Result;
739 
740   // If this load comes from anywhere in a uniform constant global, the value
741   // is always the same, regardless of the loaded offset.
742   if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C))) {
743     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
744       if (Constant *Res =
745               ConstantFoldLoadFromUniformValue(GV->getInitializer(), Ty))
746         return Res;
747     }
748   }
749 
750   return nullptr;
751 }
752 
753 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
754                                              const DataLayout &DL) {
755   APInt Offset(DL.getIndexTypeSizeInBits(C->getType()), 0);
756   return ConstantFoldLoadFromConstPtr(C, Ty, Offset, DL);
757 }
758 
759 Constant *llvm::ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty) {
760   if (isa<PoisonValue>(C))
761     return PoisonValue::get(Ty);
762   if (isa<UndefValue>(C))
763     return UndefValue::get(Ty);
764   if (C->isNullValue() && !Ty->isX86_MMXTy() && !Ty->isX86_AMXTy())
765     return Constant::getNullValue(Ty);
766   if (C->isAllOnesValue() &&
767       (Ty->isIntOrIntVectorTy() || Ty->isFPOrFPVectorTy()))
768     return Constant::getAllOnesValue(Ty);
769   return nullptr;
770 }
771 
772 namespace {
773 
774 /// One of Op0/Op1 is a constant expression.
775 /// Attempt to symbolically evaluate the result of a binary operator merging
776 /// these together.  If target data info is available, it is provided as DL,
777 /// otherwise DL is null.
778 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
779                                     const DataLayout &DL) {
780   // SROA
781 
782   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
783   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
784   // bits.
785 
786   if (Opc == Instruction::And) {
787     KnownBits Known0 = computeKnownBits(Op0, DL);
788     KnownBits Known1 = computeKnownBits(Op1, DL);
789     if ((Known1.One | Known0.Zero).isAllOnes()) {
790       // All the bits of Op0 that the 'and' could be masking are already zero.
791       return Op0;
792     }
793     if ((Known0.One | Known1.Zero).isAllOnes()) {
794       // All the bits of Op1 that the 'and' could be masking are already zero.
795       return Op1;
796     }
797 
798     Known0 &= Known1;
799     if (Known0.isConstant())
800       return ConstantInt::get(Op0->getType(), Known0.getConstant());
801   }
802 
803   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
804   // constant.  This happens frequently when iterating over a global array.
805   if (Opc == Instruction::Sub) {
806     GlobalValue *GV1, *GV2;
807     APInt Offs1, Offs2;
808 
809     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
810       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
811         unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
812 
813         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
814         // PtrToInt may change the bitwidth so we have convert to the right size
815         // first.
816         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
817                                                 Offs2.zextOrTrunc(OpSize));
818       }
819   }
820 
821   return nullptr;
822 }
823 
824 /// If array indices are not pointer-sized integers, explicitly cast them so
825 /// that they aren't implicitly casted by the getelementptr.
826 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
827                          Type *ResultTy, Optional<unsigned> InRangeIndex,
828                          const DataLayout &DL, const TargetLibraryInfo *TLI) {
829   Type *IntIdxTy = DL.getIndexType(ResultTy);
830   Type *IntIdxScalarTy = IntIdxTy->getScalarType();
831 
832   bool Any = false;
833   SmallVector<Constant*, 32> NewIdxs;
834   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
835     if ((i == 1 ||
836          !isa<StructType>(GetElementPtrInst::getIndexedType(
837              SrcElemTy, Ops.slice(1, i - 1)))) &&
838         Ops[i]->getType()->getScalarType() != IntIdxScalarTy) {
839       Any = true;
840       Type *NewType = Ops[i]->getType()->isVectorTy()
841                           ? IntIdxTy
842                           : IntIdxScalarTy;
843       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
844                                                                       true,
845                                                                       NewType,
846                                                                       true),
847                                               Ops[i], NewType));
848     } else
849       NewIdxs.push_back(Ops[i]);
850   }
851 
852   if (!Any)
853     return nullptr;
854 
855   Constant *C = ConstantExpr::getGetElementPtr(
856       SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
857   return ConstantFoldConstant(C, DL, TLI);
858 }
859 
860 /// Strip the pointer casts, but preserve the address space information.
861 Constant *StripPtrCastKeepAS(Constant *Ptr) {
862   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
863   auto *OldPtrTy = cast<PointerType>(Ptr->getType());
864   Ptr = cast<Constant>(Ptr->stripPointerCasts());
865   auto *NewPtrTy = cast<PointerType>(Ptr->getType());
866 
867   // Preserve the address space number of the pointer.
868   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
869     Ptr = ConstantExpr::getPointerCast(
870         Ptr, PointerType::getWithSamePointeeType(NewPtrTy,
871                                                  OldPtrTy->getAddressSpace()));
872   }
873   return Ptr;
874 }
875 
876 /// If we can symbolically evaluate the GEP constant expression, do so.
877 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
878                                   ArrayRef<Constant *> Ops,
879                                   const DataLayout &DL,
880                                   const TargetLibraryInfo *TLI) {
881   const GEPOperator *InnermostGEP = GEP;
882   bool InBounds = GEP->isInBounds();
883 
884   Type *SrcElemTy = GEP->getSourceElementType();
885   Type *ResElemTy = GEP->getResultElementType();
886   Type *ResTy = GEP->getType();
887   if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy))
888     return nullptr;
889 
890   if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
891                                    GEP->getInRangeIndex(), DL, TLI))
892     return C;
893 
894   Constant *Ptr = Ops[0];
895   if (!Ptr->getType()->isPointerTy())
896     return nullptr;
897 
898   Type *IntIdxTy = DL.getIndexType(Ptr->getType());
899 
900   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
901     if (!isa<ConstantInt>(Ops[i]))
902       return nullptr;
903 
904   unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy);
905   APInt Offset =
906       APInt(BitWidth,
907             DL.getIndexedOffsetInType(
908                 SrcElemTy,
909                 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
910   Ptr = StripPtrCastKeepAS(Ptr);
911 
912   // If this is a GEP of a GEP, fold it all into a single GEP.
913   while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
914     InnermostGEP = GEP;
915     InBounds &= GEP->isInBounds();
916 
917     SmallVector<Value *, 4> NestedOps(llvm::drop_begin(GEP->operands()));
918 
919     // Do not try the incorporate the sub-GEP if some index is not a number.
920     bool AllConstantInt = true;
921     for (Value *NestedOp : NestedOps)
922       if (!isa<ConstantInt>(NestedOp)) {
923         AllConstantInt = false;
924         break;
925       }
926     if (!AllConstantInt)
927       break;
928 
929     Ptr = cast<Constant>(GEP->getOperand(0));
930     SrcElemTy = GEP->getSourceElementType();
931     Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
932     Ptr = StripPtrCastKeepAS(Ptr);
933   }
934 
935   // If the base value for this address is a literal integer value, fold the
936   // getelementptr to the resulting integer value casted to the pointer type.
937   APInt BasePtr(BitWidth, 0);
938   if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
939     if (CE->getOpcode() == Instruction::IntToPtr) {
940       if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
941         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
942     }
943   }
944 
945   auto *PTy = cast<PointerType>(Ptr->getType());
946   if ((Ptr->isNullValue() || BasePtr != 0) &&
947       !DL.isNonIntegralPointerType(PTy)) {
948     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
949     return ConstantExpr::getIntToPtr(C, ResTy);
950   }
951 
952   // Otherwise form a regular getelementptr. Recompute the indices so that
953   // we eliminate over-indexing of the notional static type array bounds.
954   // This makes it easy to determine if the getelementptr is "inbounds".
955   // Also, this helps GlobalOpt do SROA on GlobalVariables.
956 
957   // For GEPs of GlobalValues, use the value type even for opaque pointers.
958   // Otherwise use an i8 GEP.
959   if (auto *GV = dyn_cast<GlobalValue>(Ptr))
960     SrcElemTy = GV->getValueType();
961   else if (!PTy->isOpaque())
962     SrcElemTy = PTy->getNonOpaquePointerElementType();
963   else
964     SrcElemTy = Type::getInt8Ty(Ptr->getContext());
965 
966   if (!SrcElemTy->isSized())
967     return nullptr;
968 
969   Type *ElemTy = SrcElemTy;
970   SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
971   if (Offset != 0)
972     return nullptr;
973 
974   // Try to add additional zero indices to reach the desired result element
975   // type.
976   // TODO: Should we avoid extra zero indices if ResElemTy can't be reached and
977   // we'll have to insert a bitcast anyway?
978   while (ElemTy != ResElemTy) {
979     Type *NextTy = GetElementPtrInst::getTypeAtIndex(ElemTy, (uint64_t)0);
980     if (!NextTy)
981       break;
982 
983     Indices.push_back(APInt::getZero(isa<StructType>(ElemTy) ? 32 : BitWidth));
984     ElemTy = NextTy;
985   }
986 
987   SmallVector<Constant *, 32> NewIdxs;
988   for (const APInt &Index : Indices)
989     NewIdxs.push_back(ConstantInt::get(
990         Type::getIntNTy(Ptr->getContext(), Index.getBitWidth()), Index));
991 
992   // Preserve the inrange index from the innermost GEP if possible. We must
993   // have calculated the same indices up to and including the inrange index.
994   Optional<unsigned> InRangeIndex;
995   if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
996     if (SrcElemTy == InnermostGEP->getSourceElementType() &&
997         NewIdxs.size() > *LastIRIndex) {
998       InRangeIndex = LastIRIndex;
999       for (unsigned I = 0; I <= *LastIRIndex; ++I)
1000         if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
1001           return nullptr;
1002     }
1003 
1004   // Create a GEP.
1005   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
1006                                                InBounds, InRangeIndex);
1007   assert(
1008       cast<PointerType>(C->getType())->isOpaqueOrPointeeTypeMatches(ElemTy) &&
1009       "Computed GetElementPtr has unexpected type!");
1010 
1011   // If we ended up indexing a member with a type that doesn't match
1012   // the type of what the original indices indexed, add a cast.
1013   if (C->getType() != ResTy)
1014     C = FoldBitCast(C, ResTy, DL);
1015 
1016   return C;
1017 }
1018 
1019 /// Attempt to constant fold an instruction with the
1020 /// specified opcode and operands.  If successful, the constant result is
1021 /// returned, if not, null is returned.  Note that this function can fail when
1022 /// attempting to fold instructions like loads and stores, which have no
1023 /// constant expression form.
1024 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
1025                                        ArrayRef<Constant *> Ops,
1026                                        const DataLayout &DL,
1027                                        const TargetLibraryInfo *TLI) {
1028   Type *DestTy = InstOrCE->getType();
1029 
1030   if (Instruction::isUnaryOp(Opcode))
1031     return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1032 
1033   if (Instruction::isBinaryOp(Opcode)) {
1034     switch (Opcode) {
1035     default:
1036       break;
1037     case Instruction::FAdd:
1038     case Instruction::FSub:
1039     case Instruction::FMul:
1040     case Instruction::FDiv:
1041     case Instruction::FRem:
1042       // Handle floating point instructions separately to account for denormals
1043       // TODO: If a constant expression is being folded rather than an
1044       // instruction, denormals will not be flushed/treated as zero
1045       if (const auto *I = dyn_cast<Instruction>(InstOrCE)) {
1046         return ConstantFoldFPInstOperands(Opcode, Ops[0], Ops[1], DL, I);
1047       }
1048     }
1049     return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1050   }
1051 
1052   if (Instruction::isCast(Opcode))
1053     return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1054 
1055   if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1056     if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1057       return C;
1058 
1059     return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1060                                           Ops.slice(1), GEP->isInBounds(),
1061                                           GEP->getInRangeIndex());
1062   }
1063 
1064   if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1065     return CE->getWithOperands(Ops);
1066 
1067   switch (Opcode) {
1068   default: return nullptr;
1069   case Instruction::ICmp:
1070   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1071   case Instruction::Freeze:
1072     return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1073   case Instruction::Call:
1074     if (auto *F = dyn_cast<Function>(Ops.back())) {
1075       const auto *Call = cast<CallBase>(InstOrCE);
1076       if (canConstantFoldCallTo(Call, F))
1077         return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
1078     }
1079     return nullptr;
1080   case Instruction::Select:
1081     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1082   case Instruction::ExtractElement:
1083     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1084   case Instruction::ExtractValue:
1085     return ConstantExpr::getExtractValue(
1086         Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1087   case Instruction::InsertElement:
1088     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1089   case Instruction::ShuffleVector:
1090     return ConstantExpr::getShuffleVector(
1091         Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1092   }
1093 }
1094 
1095 } // end anonymous namespace
1096 
1097 //===----------------------------------------------------------------------===//
1098 // Constant Folding public APIs
1099 //===----------------------------------------------------------------------===//
1100 
1101 namespace {
1102 
1103 Constant *
1104 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1105                          const TargetLibraryInfo *TLI,
1106                          SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1107   if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1108     return const_cast<Constant *>(C);
1109 
1110   SmallVector<Constant *, 8> Ops;
1111   for (const Use &OldU : C->operands()) {
1112     Constant *OldC = cast<Constant>(&OldU);
1113     Constant *NewC = OldC;
1114     // Recursively fold the ConstantExpr's operands. If we have already folded
1115     // a ConstantExpr, we don't have to process it again.
1116     if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1117       auto It = FoldedOps.find(OldC);
1118       if (It == FoldedOps.end()) {
1119         NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1120         FoldedOps.insert({OldC, NewC});
1121       } else {
1122         NewC = It->second;
1123       }
1124     }
1125     Ops.push_back(NewC);
1126   }
1127 
1128   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1129     if (CE->isCompare())
1130       return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1131                                              DL, TLI);
1132 
1133     return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
1134   }
1135 
1136   assert(isa<ConstantVector>(C));
1137   return ConstantVector::get(Ops);
1138 }
1139 
1140 } // end anonymous namespace
1141 
1142 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1143                                         const TargetLibraryInfo *TLI) {
1144   // Handle PHI nodes quickly here...
1145   if (auto *PN = dyn_cast<PHINode>(I)) {
1146     Constant *CommonValue = nullptr;
1147 
1148     SmallDenseMap<Constant *, Constant *> FoldedOps;
1149     for (Value *Incoming : PN->incoming_values()) {
1150       // If the incoming value is undef then skip it.  Note that while we could
1151       // skip the value if it is equal to the phi node itself we choose not to
1152       // because that would break the rule that constant folding only applies if
1153       // all operands are constants.
1154       if (isa<UndefValue>(Incoming))
1155         continue;
1156       // If the incoming value is not a constant, then give up.
1157       auto *C = dyn_cast<Constant>(Incoming);
1158       if (!C)
1159         return nullptr;
1160       // Fold the PHI's operands.
1161       C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1162       // If the incoming value is a different constant to
1163       // the one we saw previously, then give up.
1164       if (CommonValue && C != CommonValue)
1165         return nullptr;
1166       CommonValue = C;
1167     }
1168 
1169     // If we reach here, all incoming values are the same constant or undef.
1170     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1171   }
1172 
1173   // Scan the operand list, checking to see if they are all constants, if so,
1174   // hand off to ConstantFoldInstOperandsImpl.
1175   if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1176     return nullptr;
1177 
1178   SmallDenseMap<Constant *, Constant *> FoldedOps;
1179   SmallVector<Constant *, 8> Ops;
1180   for (const Use &OpU : I->operands()) {
1181     auto *Op = cast<Constant>(&OpU);
1182     // Fold the Instruction's operands.
1183     Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1184     Ops.push_back(Op);
1185   }
1186 
1187   if (const auto *CI = dyn_cast<CmpInst>(I))
1188     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1189                                            DL, TLI);
1190 
1191   if (const auto *LI = dyn_cast<LoadInst>(I)) {
1192     if (LI->isVolatile())
1193       return nullptr;
1194     return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL);
1195   }
1196 
1197   if (auto *IVI = dyn_cast<InsertValueInst>(I))
1198     return ConstantExpr::getInsertValue(Ops[0], Ops[1], IVI->getIndices());
1199 
1200   if (auto *EVI = dyn_cast<ExtractValueInst>(I))
1201     return ConstantExpr::getExtractValue(Ops[0], EVI->getIndices());
1202 
1203   return ConstantFoldInstOperands(I, Ops, DL, TLI);
1204 }
1205 
1206 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1207                                      const TargetLibraryInfo *TLI) {
1208   SmallDenseMap<Constant *, Constant *> FoldedOps;
1209   return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1210 }
1211 
1212 Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1213                                          ArrayRef<Constant *> Ops,
1214                                          const DataLayout &DL,
1215                                          const TargetLibraryInfo *TLI) {
1216   return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1217 }
1218 
1219 Constant *llvm::ConstantFoldCompareInstOperands(unsigned IntPredicate,
1220                                                 Constant *Ops0, Constant *Ops1,
1221                                                 const DataLayout &DL,
1222                                                 const TargetLibraryInfo *TLI) {
1223   CmpInst::Predicate Predicate = (CmpInst::Predicate)IntPredicate;
1224   // fold: icmp (inttoptr x), null         -> icmp x, 0
1225   // fold: icmp null, (inttoptr x)         -> icmp 0, x
1226   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1227   // fold: icmp 0, (ptrtoint x)            -> icmp null, x
1228   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1229   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1230   //
1231   // FIXME: The following comment is out of data and the DataLayout is here now.
1232   // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1233   // around to know if bit truncation is happening.
1234   if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1235     if (Ops1->isNullValue()) {
1236       if (CE0->getOpcode() == Instruction::IntToPtr) {
1237         Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1238         // Convert the integer value to the right size to ensure we get the
1239         // proper extension or truncation.
1240         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1241                                                    IntPtrTy, false);
1242         Constant *Null = Constant::getNullValue(C->getType());
1243         return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1244       }
1245 
1246       // Only do this transformation if the int is intptrty in size, otherwise
1247       // there is a truncation or extension that we aren't modeling.
1248       if (CE0->getOpcode() == Instruction::PtrToInt) {
1249         Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1250         if (CE0->getType() == IntPtrTy) {
1251           Constant *C = CE0->getOperand(0);
1252           Constant *Null = Constant::getNullValue(C->getType());
1253           return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1254         }
1255       }
1256     }
1257 
1258     if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1259       if (CE0->getOpcode() == CE1->getOpcode()) {
1260         if (CE0->getOpcode() == Instruction::IntToPtr) {
1261           Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1262 
1263           // Convert the integer value to the right size to ensure we get the
1264           // proper extension or truncation.
1265           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1266                                                       IntPtrTy, false);
1267           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1268                                                       IntPtrTy, false);
1269           return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1270         }
1271 
1272         // Only do this transformation if the int is intptrty in size, otherwise
1273         // there is a truncation or extension that we aren't modeling.
1274         if (CE0->getOpcode() == Instruction::PtrToInt) {
1275           Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1276           if (CE0->getType() == IntPtrTy &&
1277               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1278             return ConstantFoldCompareInstOperands(
1279                 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1280           }
1281         }
1282       }
1283     }
1284 
1285     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1286     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1287     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1288         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1289       Constant *LHS = ConstantFoldCompareInstOperands(
1290           Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1291       Constant *RHS = ConstantFoldCompareInstOperands(
1292           Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1293       unsigned OpC =
1294         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1295       return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1296     }
1297 
1298     // Convert pointer comparison (base+offset1) pred (base+offset2) into
1299     // offset1 pred offset2, for the case where the offset is inbounds. This
1300     // only works for equality and unsigned comparison, as inbounds permits
1301     // crossing the sign boundary. However, the offset comparison itself is
1302     // signed.
1303     if (Ops0->getType()->isPointerTy() && !ICmpInst::isSigned(Predicate)) {
1304       unsigned IndexWidth = DL.getIndexTypeSizeInBits(Ops0->getType());
1305       APInt Offset0(IndexWidth, 0);
1306       Value *Stripped0 =
1307           Ops0->stripAndAccumulateInBoundsConstantOffsets(DL, Offset0);
1308       APInt Offset1(IndexWidth, 0);
1309       Value *Stripped1 =
1310           Ops1->stripAndAccumulateInBoundsConstantOffsets(DL, Offset1);
1311       if (Stripped0 == Stripped1)
1312         return ConstantExpr::getCompare(
1313             ICmpInst::getSignedPredicate(Predicate),
1314             ConstantInt::get(CE0->getContext(), Offset0),
1315             ConstantInt::get(CE0->getContext(), Offset1));
1316     }
1317   } else if (isa<ConstantExpr>(Ops1)) {
1318     // If RHS is a constant expression, but the left side isn't, swap the
1319     // operands and try again.
1320     Predicate = ICmpInst::getSwappedPredicate(Predicate);
1321     return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1322   }
1323 
1324   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1325 }
1326 
1327 Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1328                                            const DataLayout &DL) {
1329   assert(Instruction::isUnaryOp(Opcode));
1330 
1331   return ConstantExpr::get(Opcode, Op);
1332 }
1333 
1334 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1335                                              Constant *RHS,
1336                                              const DataLayout &DL) {
1337   assert(Instruction::isBinaryOp(Opcode));
1338   if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1339     if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1340       return C;
1341 
1342   return ConstantExpr::get(Opcode, LHS, RHS);
1343 }
1344 
1345 // Check whether a constant is a floating point denormal that should be flushed
1346 // to zero according to the denormal handling mode set in the function
1347 // attributes. If so, return a zero with the correct sign, otherwise return the
1348 // original constant. Inputs and outputs to floating point instructions can have
1349 // their mode set separately, so the direction is also needed.
1350 Constant *FlushFPConstant(Constant *Operand, const llvm::Function *F,
1351                           bool IsOutput) {
1352   if (F == nullptr)
1353     return Operand;
1354   if (auto *CFP = dyn_cast<ConstantFP>(Operand)) {
1355     const APFloat &APF = CFP->getValueAPF();
1356     Type *Ty = CFP->getType();
1357     DenormalMode DenormMode = F->getDenormalMode(Ty->getFltSemantics());
1358     DenormalMode::DenormalModeKind Mode =
1359         IsOutput ? DenormMode.Output : DenormMode.Input;
1360     switch (Mode) {
1361     default:
1362       llvm_unreachable("unknown denormal mode");
1363       return Operand;
1364     case DenormalMode::IEEE:
1365       return Operand;
1366     case DenormalMode::PreserveSign:
1367       if (APF.isDenormal()) {
1368         return ConstantFP::get(
1369             Ty->getContext(),
1370             APFloat::getZero(Ty->getFltSemantics(), APF.isNegative()));
1371       }
1372       return Operand;
1373     case DenormalMode::PositiveZero:
1374       if (APF.isDenormal()) {
1375         return ConstantFP::get(Ty->getContext(),
1376                                APFloat::getZero(Ty->getFltSemantics(), false));
1377       }
1378       return Operand;
1379     }
1380   }
1381   return Operand;
1382 }
1383 
1384 Constant *llvm::ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS,
1385                                            Constant *RHS, const DataLayout &DL,
1386                                            const Instruction *I) {
1387   if (auto *BB = I->getParent()) {
1388     if (auto *F = BB->getParent()) {
1389       if (Instruction::isBinaryOp(Opcode)) {
1390         Constant *Op0 = FlushFPConstant(LHS, F, false);
1391         Constant *Op1 = FlushFPConstant(RHS, F, false);
1392         Constant *C = ConstantFoldBinaryOpOperands(Opcode, Op0, Op1, DL);
1393         return FlushFPConstant(C, F, true);
1394       }
1395     }
1396   }
1397   // If instruction lacks a parent/function and the denormal mode cannot be
1398   // determined, use the default (IEEE).
1399   return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
1400 }
1401 
1402 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1403                                         Type *DestTy, const DataLayout &DL) {
1404   assert(Instruction::isCast(Opcode));
1405   switch (Opcode) {
1406   default:
1407     llvm_unreachable("Missing case");
1408   case Instruction::PtrToInt:
1409     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1410       Constant *FoldedValue = nullptr;
1411       // If the input is a inttoptr, eliminate the pair.  This requires knowing
1412       // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1413       if (CE->getOpcode() == Instruction::IntToPtr) {
1414         // zext/trunc the inttoptr to pointer size.
1415         FoldedValue = ConstantExpr::getIntegerCast(
1416             CE->getOperand(0), DL.getIntPtrType(CE->getType()),
1417             /*IsSigned=*/false);
1418       } else if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
1419         // If we have GEP, we can perform the following folds:
1420         // (ptrtoint (gep null, x)) -> x
1421         // (ptrtoint (gep (gep null, x), y) -> x + y, etc.
1422         unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1423         APInt BaseOffset(BitWidth, 0);
1424         auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets(
1425             DL, BaseOffset, /*AllowNonInbounds=*/true));
1426         if (Base->isNullValue()) {
1427           FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset);
1428         } else {
1429           // ptrtoint (gep i8, Ptr, (sub 0, V)) -> sub (ptrtoint Ptr), V
1430           if (GEP->getNumIndices() == 1 &&
1431               GEP->getSourceElementType()->isIntegerTy(8)) {
1432             auto *Ptr = cast<Constant>(GEP->getPointerOperand());
1433             auto *Sub = dyn_cast<ConstantExpr>(GEP->getOperand(1));
1434             Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1435             if (Sub && Sub->getType() == IntIdxTy &&
1436                 Sub->getOpcode() == Instruction::Sub &&
1437                 Sub->getOperand(0)->isNullValue())
1438               FoldedValue = ConstantExpr::getSub(
1439                   ConstantExpr::getPtrToInt(Ptr, IntIdxTy), Sub->getOperand(1));
1440           }
1441         }
1442       }
1443       if (FoldedValue) {
1444         // Do a zext or trunc to get to the ptrtoint dest size.
1445         return ConstantExpr::getIntegerCast(FoldedValue, DestTy,
1446                                             /*IsSigned=*/false);
1447       }
1448     }
1449     return ConstantExpr::getCast(Opcode, C, DestTy);
1450   case Instruction::IntToPtr:
1451     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1452     // the int size is >= the ptr size and the address spaces are the same.
1453     // This requires knowing the width of a pointer, so it can't be done in
1454     // ConstantExpr::getCast.
1455     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1456       if (CE->getOpcode() == Instruction::PtrToInt) {
1457         Constant *SrcPtr = CE->getOperand(0);
1458         unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1459         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1460 
1461         if (MidIntSize >= SrcPtrSize) {
1462           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1463           if (SrcAS == DestTy->getPointerAddressSpace())
1464             return FoldBitCast(CE->getOperand(0), DestTy, DL);
1465         }
1466       }
1467     }
1468 
1469     return ConstantExpr::getCast(Opcode, C, DestTy);
1470   case Instruction::Trunc:
1471   case Instruction::ZExt:
1472   case Instruction::SExt:
1473   case Instruction::FPTrunc:
1474   case Instruction::FPExt:
1475   case Instruction::UIToFP:
1476   case Instruction::SIToFP:
1477   case Instruction::FPToUI:
1478   case Instruction::FPToSI:
1479   case Instruction::AddrSpaceCast:
1480       return ConstantExpr::getCast(Opcode, C, DestTy);
1481   case Instruction::BitCast:
1482     return FoldBitCast(C, DestTy, DL);
1483   }
1484 }
1485 
1486 //===----------------------------------------------------------------------===//
1487 //  Constant Folding for Calls
1488 //
1489 
1490 bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1491   if (Call->isNoBuiltin())
1492     return false;
1493   if (Call->getFunctionType() != F->getFunctionType())
1494     return false;
1495   switch (F->getIntrinsicID()) {
1496   // Operations that do not operate floating-point numbers and do not depend on
1497   // FP environment can be folded even in strictfp functions.
1498   case Intrinsic::bswap:
1499   case Intrinsic::ctpop:
1500   case Intrinsic::ctlz:
1501   case Intrinsic::cttz:
1502   case Intrinsic::fshl:
1503   case Intrinsic::fshr:
1504   case Intrinsic::launder_invariant_group:
1505   case Intrinsic::strip_invariant_group:
1506   case Intrinsic::masked_load:
1507   case Intrinsic::get_active_lane_mask:
1508   case Intrinsic::abs:
1509   case Intrinsic::smax:
1510   case Intrinsic::smin:
1511   case Intrinsic::umax:
1512   case Intrinsic::umin:
1513   case Intrinsic::sadd_with_overflow:
1514   case Intrinsic::uadd_with_overflow:
1515   case Intrinsic::ssub_with_overflow:
1516   case Intrinsic::usub_with_overflow:
1517   case Intrinsic::smul_with_overflow:
1518   case Intrinsic::umul_with_overflow:
1519   case Intrinsic::sadd_sat:
1520   case Intrinsic::uadd_sat:
1521   case Intrinsic::ssub_sat:
1522   case Intrinsic::usub_sat:
1523   case Intrinsic::smul_fix:
1524   case Intrinsic::smul_fix_sat:
1525   case Intrinsic::bitreverse:
1526   case Intrinsic::is_constant:
1527   case Intrinsic::vector_reduce_add:
1528   case Intrinsic::vector_reduce_mul:
1529   case Intrinsic::vector_reduce_and:
1530   case Intrinsic::vector_reduce_or:
1531   case Intrinsic::vector_reduce_xor:
1532   case Intrinsic::vector_reduce_smin:
1533   case Intrinsic::vector_reduce_smax:
1534   case Intrinsic::vector_reduce_umin:
1535   case Intrinsic::vector_reduce_umax:
1536   // Target intrinsics
1537   case Intrinsic::amdgcn_perm:
1538   case Intrinsic::arm_mve_vctp8:
1539   case Intrinsic::arm_mve_vctp16:
1540   case Intrinsic::arm_mve_vctp32:
1541   case Intrinsic::arm_mve_vctp64:
1542   case Intrinsic::aarch64_sve_convert_from_svbool:
1543   // WebAssembly float semantics are always known
1544   case Intrinsic::wasm_trunc_signed:
1545   case Intrinsic::wasm_trunc_unsigned:
1546     return true;
1547 
1548   // Floating point operations cannot be folded in strictfp functions in
1549   // general case. They can be folded if FP environment is known to compiler.
1550   case Intrinsic::minnum:
1551   case Intrinsic::maxnum:
1552   case Intrinsic::minimum:
1553   case Intrinsic::maximum:
1554   case Intrinsic::log:
1555   case Intrinsic::log2:
1556   case Intrinsic::log10:
1557   case Intrinsic::exp:
1558   case Intrinsic::exp2:
1559   case Intrinsic::sqrt:
1560   case Intrinsic::sin:
1561   case Intrinsic::cos:
1562   case Intrinsic::pow:
1563   case Intrinsic::powi:
1564   case Intrinsic::fma:
1565   case Intrinsic::fmuladd:
1566   case Intrinsic::fptoui_sat:
1567   case Intrinsic::fptosi_sat:
1568   case Intrinsic::convert_from_fp16:
1569   case Intrinsic::convert_to_fp16:
1570   case Intrinsic::amdgcn_cos:
1571   case Intrinsic::amdgcn_cubeid:
1572   case Intrinsic::amdgcn_cubema:
1573   case Intrinsic::amdgcn_cubesc:
1574   case Intrinsic::amdgcn_cubetc:
1575   case Intrinsic::amdgcn_fmul_legacy:
1576   case Intrinsic::amdgcn_fma_legacy:
1577   case Intrinsic::amdgcn_fract:
1578   case Intrinsic::amdgcn_ldexp:
1579   case Intrinsic::amdgcn_sin:
1580   // The intrinsics below depend on rounding mode in MXCSR.
1581   case Intrinsic::x86_sse_cvtss2si:
1582   case Intrinsic::x86_sse_cvtss2si64:
1583   case Intrinsic::x86_sse_cvttss2si:
1584   case Intrinsic::x86_sse_cvttss2si64:
1585   case Intrinsic::x86_sse2_cvtsd2si:
1586   case Intrinsic::x86_sse2_cvtsd2si64:
1587   case Intrinsic::x86_sse2_cvttsd2si:
1588   case Intrinsic::x86_sse2_cvttsd2si64:
1589   case Intrinsic::x86_avx512_vcvtss2si32:
1590   case Intrinsic::x86_avx512_vcvtss2si64:
1591   case Intrinsic::x86_avx512_cvttss2si:
1592   case Intrinsic::x86_avx512_cvttss2si64:
1593   case Intrinsic::x86_avx512_vcvtsd2si32:
1594   case Intrinsic::x86_avx512_vcvtsd2si64:
1595   case Intrinsic::x86_avx512_cvttsd2si:
1596   case Intrinsic::x86_avx512_cvttsd2si64:
1597   case Intrinsic::x86_avx512_vcvtss2usi32:
1598   case Intrinsic::x86_avx512_vcvtss2usi64:
1599   case Intrinsic::x86_avx512_cvttss2usi:
1600   case Intrinsic::x86_avx512_cvttss2usi64:
1601   case Intrinsic::x86_avx512_vcvtsd2usi32:
1602   case Intrinsic::x86_avx512_vcvtsd2usi64:
1603   case Intrinsic::x86_avx512_cvttsd2usi:
1604   case Intrinsic::x86_avx512_cvttsd2usi64:
1605     return !Call->isStrictFP();
1606 
1607   // Sign operations are actually bitwise operations, they do not raise
1608   // exceptions even for SNANs.
1609   case Intrinsic::fabs:
1610   case Intrinsic::copysign:
1611   // Non-constrained variants of rounding operations means default FP
1612   // environment, they can be folded in any case.
1613   case Intrinsic::ceil:
1614   case Intrinsic::floor:
1615   case Intrinsic::round:
1616   case Intrinsic::roundeven:
1617   case Intrinsic::trunc:
1618   case Intrinsic::nearbyint:
1619   case Intrinsic::rint:
1620   // Constrained intrinsics can be folded if FP environment is known
1621   // to compiler.
1622   case Intrinsic::experimental_constrained_fma:
1623   case Intrinsic::experimental_constrained_fmuladd:
1624   case Intrinsic::experimental_constrained_fadd:
1625   case Intrinsic::experimental_constrained_fsub:
1626   case Intrinsic::experimental_constrained_fmul:
1627   case Intrinsic::experimental_constrained_fdiv:
1628   case Intrinsic::experimental_constrained_frem:
1629   case Intrinsic::experimental_constrained_ceil:
1630   case Intrinsic::experimental_constrained_floor:
1631   case Intrinsic::experimental_constrained_round:
1632   case Intrinsic::experimental_constrained_roundeven:
1633   case Intrinsic::experimental_constrained_trunc:
1634   case Intrinsic::experimental_constrained_nearbyint:
1635   case Intrinsic::experimental_constrained_rint:
1636   case Intrinsic::experimental_constrained_fcmp:
1637   case Intrinsic::experimental_constrained_fcmps:
1638     return true;
1639   default:
1640     return false;
1641   case Intrinsic::not_intrinsic: break;
1642   }
1643 
1644   if (!F->hasName() || Call->isStrictFP())
1645     return false;
1646 
1647   // In these cases, the check of the length is required.  We don't want to
1648   // return true for a name like "cos\0blah" which strcmp would return equal to
1649   // "cos", but has length 8.
1650   StringRef Name = F->getName();
1651   switch (Name[0]) {
1652   default:
1653     return false;
1654   case 'a':
1655     return Name == "acos" || Name == "acosf" ||
1656            Name == "asin" || Name == "asinf" ||
1657            Name == "atan" || Name == "atanf" ||
1658            Name == "atan2" || Name == "atan2f";
1659   case 'c':
1660     return Name == "ceil" || Name == "ceilf" ||
1661            Name == "cos" || Name == "cosf" ||
1662            Name == "cosh" || Name == "coshf";
1663   case 'e':
1664     return Name == "exp" || Name == "expf" ||
1665            Name == "exp2" || Name == "exp2f";
1666   case 'f':
1667     return Name == "fabs" || Name == "fabsf" ||
1668            Name == "floor" || Name == "floorf" ||
1669            Name == "fmod" || Name == "fmodf";
1670   case 'l':
1671     return Name == "log" || Name == "logf" ||
1672            Name == "log2" || Name == "log2f" ||
1673            Name == "log10" || Name == "log10f";
1674   case 'n':
1675     return Name == "nearbyint" || Name == "nearbyintf";
1676   case 'p':
1677     return Name == "pow" || Name == "powf";
1678   case 'r':
1679     return Name == "remainder" || Name == "remainderf" ||
1680            Name == "rint" || Name == "rintf" ||
1681            Name == "round" || Name == "roundf";
1682   case 's':
1683     return Name == "sin" || Name == "sinf" ||
1684            Name == "sinh" || Name == "sinhf" ||
1685            Name == "sqrt" || Name == "sqrtf";
1686   case 't':
1687     return Name == "tan" || Name == "tanf" ||
1688            Name == "tanh" || Name == "tanhf" ||
1689            Name == "trunc" || Name == "truncf";
1690   case '_':
1691     // Check for various function names that get used for the math functions
1692     // when the header files are preprocessed with the macro
1693     // __FINITE_MATH_ONLY__ enabled.
1694     // The '12' here is the length of the shortest name that can match.
1695     // We need to check the size before looking at Name[1] and Name[2]
1696     // so we may as well check a limit that will eliminate mismatches.
1697     if (Name.size() < 12 || Name[1] != '_')
1698       return false;
1699     switch (Name[2]) {
1700     default:
1701       return false;
1702     case 'a':
1703       return Name == "__acos_finite" || Name == "__acosf_finite" ||
1704              Name == "__asin_finite" || Name == "__asinf_finite" ||
1705              Name == "__atan2_finite" || Name == "__atan2f_finite";
1706     case 'c':
1707       return Name == "__cosh_finite" || Name == "__coshf_finite";
1708     case 'e':
1709       return Name == "__exp_finite" || Name == "__expf_finite" ||
1710              Name == "__exp2_finite" || Name == "__exp2f_finite";
1711     case 'l':
1712       return Name == "__log_finite" || Name == "__logf_finite" ||
1713              Name == "__log10_finite" || Name == "__log10f_finite";
1714     case 'p':
1715       return Name == "__pow_finite" || Name == "__powf_finite";
1716     case 's':
1717       return Name == "__sinh_finite" || Name == "__sinhf_finite";
1718     }
1719   }
1720 }
1721 
1722 namespace {
1723 
1724 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1725   if (Ty->isHalfTy() || Ty->isFloatTy()) {
1726     APFloat APF(V);
1727     bool unused;
1728     APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1729     return ConstantFP::get(Ty->getContext(), APF);
1730   }
1731   if (Ty->isDoubleTy())
1732     return ConstantFP::get(Ty->getContext(), APFloat(V));
1733   llvm_unreachable("Can only constant fold half/float/double");
1734 }
1735 
1736 /// Clear the floating-point exception state.
1737 inline void llvm_fenv_clearexcept() {
1738 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1739   feclearexcept(FE_ALL_EXCEPT);
1740 #endif
1741   errno = 0;
1742 }
1743 
1744 /// Test if a floating-point exception was raised.
1745 inline bool llvm_fenv_testexcept() {
1746   int errno_val = errno;
1747   if (errno_val == ERANGE || errno_val == EDOM)
1748     return true;
1749 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1750   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1751     return true;
1752 #endif
1753   return false;
1754 }
1755 
1756 Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V,
1757                          Type *Ty) {
1758   llvm_fenv_clearexcept();
1759   double Result = NativeFP(V.convertToDouble());
1760   if (llvm_fenv_testexcept()) {
1761     llvm_fenv_clearexcept();
1762     return nullptr;
1763   }
1764 
1765   return GetConstantFoldFPValue(Result, Ty);
1766 }
1767 
1768 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1769                                const APFloat &V, const APFloat &W, Type *Ty) {
1770   llvm_fenv_clearexcept();
1771   double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
1772   if (llvm_fenv_testexcept()) {
1773     llvm_fenv_clearexcept();
1774     return nullptr;
1775   }
1776 
1777   return GetConstantFoldFPValue(Result, Ty);
1778 }
1779 
1780 Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1781   FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1782   if (!VT)
1783     return nullptr;
1784 
1785   // This isn't strictly necessary, but handle the special/common case of zero:
1786   // all integer reductions of a zero input produce zero.
1787   if (isa<ConstantAggregateZero>(Op))
1788     return ConstantInt::get(VT->getElementType(), 0);
1789 
1790   // This is the same as the underlying binops - poison propagates.
1791   if (isa<PoisonValue>(Op) || Op->containsPoisonElement())
1792     return PoisonValue::get(VT->getElementType());
1793 
1794   // TODO: Handle undef.
1795   if (!isa<ConstantVector>(Op) && !isa<ConstantDataVector>(Op))
1796     return nullptr;
1797 
1798   auto *EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1799   if (!EltC)
1800     return nullptr;
1801 
1802   APInt Acc = EltC->getValue();
1803   for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
1804     if (!(EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1805       return nullptr;
1806     const APInt &X = EltC->getValue();
1807     switch (IID) {
1808     case Intrinsic::vector_reduce_add:
1809       Acc = Acc + X;
1810       break;
1811     case Intrinsic::vector_reduce_mul:
1812       Acc = Acc * X;
1813       break;
1814     case Intrinsic::vector_reduce_and:
1815       Acc = Acc & X;
1816       break;
1817     case Intrinsic::vector_reduce_or:
1818       Acc = Acc | X;
1819       break;
1820     case Intrinsic::vector_reduce_xor:
1821       Acc = Acc ^ X;
1822       break;
1823     case Intrinsic::vector_reduce_smin:
1824       Acc = APIntOps::smin(Acc, X);
1825       break;
1826     case Intrinsic::vector_reduce_smax:
1827       Acc = APIntOps::smax(Acc, X);
1828       break;
1829     case Intrinsic::vector_reduce_umin:
1830       Acc = APIntOps::umin(Acc, X);
1831       break;
1832     case Intrinsic::vector_reduce_umax:
1833       Acc = APIntOps::umax(Acc, X);
1834       break;
1835     }
1836   }
1837 
1838   return ConstantInt::get(Op->getContext(), Acc);
1839 }
1840 
1841 /// Attempt to fold an SSE floating point to integer conversion of a constant
1842 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1843 /// used (toward nearest, ties to even). This matches the behavior of the
1844 /// non-truncating SSE instructions in the default rounding mode. The desired
1845 /// integer type Ty is used to select how many bits are available for the
1846 /// result. Returns null if the conversion cannot be performed, otherwise
1847 /// returns the Constant value resulting from the conversion.
1848 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1849                                       Type *Ty, bool IsSigned) {
1850   // All of these conversion intrinsics form an integer of at most 64bits.
1851   unsigned ResultWidth = Ty->getIntegerBitWidth();
1852   assert(ResultWidth <= 64 &&
1853          "Can only constant fold conversions to 64 and 32 bit ints");
1854 
1855   uint64_t UIntVal;
1856   bool isExact = false;
1857   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1858                                               : APFloat::rmNearestTiesToEven;
1859   APFloat::opStatus status =
1860       Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1861                            IsSigned, mode, &isExact);
1862   if (status != APFloat::opOK &&
1863       (!roundTowardZero || status != APFloat::opInexact))
1864     return nullptr;
1865   return ConstantInt::get(Ty, UIntVal, IsSigned);
1866 }
1867 
1868 double getValueAsDouble(ConstantFP *Op) {
1869   Type *Ty = Op->getType();
1870 
1871   if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
1872     return Op->getValueAPF().convertToDouble();
1873 
1874   bool unused;
1875   APFloat APF = Op->getValueAPF();
1876   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1877   return APF.convertToDouble();
1878 }
1879 
1880 static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1881   if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1882     C = &CI->getValue();
1883     return true;
1884   }
1885   if (isa<UndefValue>(Op)) {
1886     C = nullptr;
1887     return true;
1888   }
1889   return false;
1890 }
1891 
1892 /// Checks if the given intrinsic call, which evaluates to constant, is allowed
1893 /// to be folded.
1894 ///
1895 /// \param CI Constrained intrinsic call.
1896 /// \param St Exception flags raised during constant evaluation.
1897 static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
1898                                APFloat::opStatus St) {
1899   Optional<RoundingMode> ORM = CI->getRoundingMode();
1900   Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1901 
1902   // If the operation does not change exception status flags, it is safe
1903   // to fold.
1904   if (St == APFloat::opStatus::opOK)
1905     return true;
1906 
1907   // If evaluation raised FP exception, the result can depend on rounding
1908   // mode. If the latter is unknown, folding is not possible.
1909   if (ORM && *ORM == RoundingMode::Dynamic)
1910     return false;
1911 
1912   // If FP exceptions are ignored, fold the call, even if such exception is
1913   // raised.
1914   if (EB && *EB != fp::ExceptionBehavior::ebStrict)
1915     return true;
1916 
1917   // Leave the calculation for runtime so that exception flags be correctly set
1918   // in hardware.
1919   return false;
1920 }
1921 
1922 /// Returns the rounding mode that should be used for constant evaluation.
1923 static RoundingMode
1924 getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
1925   Optional<RoundingMode> ORM = CI->getRoundingMode();
1926   if (!ORM || *ORM == RoundingMode::Dynamic)
1927     // Even if the rounding mode is unknown, try evaluating the operation.
1928     // If it does not raise inexact exception, rounding was not applied,
1929     // so the result is exact and does not depend on rounding mode. Whether
1930     // other FP exceptions are raised, it does not depend on rounding mode.
1931     return RoundingMode::NearestTiesToEven;
1932   return *ORM;
1933 }
1934 
1935 static Constant *ConstantFoldScalarCall1(StringRef Name,
1936                                          Intrinsic::ID IntrinsicID,
1937                                          Type *Ty,
1938                                          ArrayRef<Constant *> Operands,
1939                                          const TargetLibraryInfo *TLI,
1940                                          const CallBase *Call) {
1941   assert(Operands.size() == 1 && "Wrong number of operands.");
1942 
1943   if (IntrinsicID == Intrinsic::is_constant) {
1944     // We know we have a "Constant" argument. But we want to only
1945     // return true for manifest constants, not those that depend on
1946     // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1947     if (Operands[0]->isManifestConstant())
1948       return ConstantInt::getTrue(Ty->getContext());
1949     return nullptr;
1950   }
1951   if (isa<UndefValue>(Operands[0])) {
1952     // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1953     // ctpop() is between 0 and bitwidth, pick 0 for undef.
1954     // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
1955     if (IntrinsicID == Intrinsic::cos ||
1956         IntrinsicID == Intrinsic::ctpop ||
1957         IntrinsicID == Intrinsic::fptoui_sat ||
1958         IntrinsicID == Intrinsic::fptosi_sat)
1959       return Constant::getNullValue(Ty);
1960     if (IntrinsicID == Intrinsic::bswap ||
1961         IntrinsicID == Intrinsic::bitreverse ||
1962         IntrinsicID == Intrinsic::launder_invariant_group ||
1963         IntrinsicID == Intrinsic::strip_invariant_group)
1964       return Operands[0];
1965   }
1966 
1967   if (isa<ConstantPointerNull>(Operands[0])) {
1968     // launder(null) == null == strip(null) iff in addrspace 0
1969     if (IntrinsicID == Intrinsic::launder_invariant_group ||
1970         IntrinsicID == Intrinsic::strip_invariant_group) {
1971       // If instruction is not yet put in a basic block (e.g. when cloning
1972       // a function during inlining), Call's caller may not be available.
1973       // So check Call's BB first before querying Call->getCaller.
1974       const Function *Caller =
1975           Call->getParent() ? Call->getCaller() : nullptr;
1976       if (Caller &&
1977           !NullPointerIsDefined(
1978               Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1979         return Operands[0];
1980       }
1981       return nullptr;
1982     }
1983   }
1984 
1985   if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1986     if (IntrinsicID == Intrinsic::convert_to_fp16) {
1987       APFloat Val(Op->getValueAPF());
1988 
1989       bool lost = false;
1990       Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1991 
1992       return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1993     }
1994 
1995     APFloat U = Op->getValueAPF();
1996 
1997     if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
1998         IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
1999       bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
2000 
2001       if (U.isNaN())
2002         return nullptr;
2003 
2004       unsigned Width = Ty->getIntegerBitWidth();
2005       APSInt Int(Width, !Signed);
2006       bool IsExact = false;
2007       APFloat::opStatus Status =
2008           U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2009 
2010       if (Status == APFloat::opOK || Status == APFloat::opInexact)
2011         return ConstantInt::get(Ty, Int);
2012 
2013       return nullptr;
2014     }
2015 
2016     if (IntrinsicID == Intrinsic::fptoui_sat ||
2017         IntrinsicID == Intrinsic::fptosi_sat) {
2018       // convertToInteger() already has the desired saturation semantics.
2019       APSInt Int(Ty->getIntegerBitWidth(),
2020                  IntrinsicID == Intrinsic::fptoui_sat);
2021       bool IsExact;
2022       U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2023       return ConstantInt::get(Ty, Int);
2024     }
2025 
2026     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2027       return nullptr;
2028 
2029     // Use internal versions of these intrinsics.
2030 
2031     if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
2032       U.roundToIntegral(APFloat::rmNearestTiesToEven);
2033       return ConstantFP::get(Ty->getContext(), U);
2034     }
2035 
2036     if (IntrinsicID == Intrinsic::round) {
2037       U.roundToIntegral(APFloat::rmNearestTiesToAway);
2038       return ConstantFP::get(Ty->getContext(), U);
2039     }
2040 
2041     if (IntrinsicID == Intrinsic::roundeven) {
2042       U.roundToIntegral(APFloat::rmNearestTiesToEven);
2043       return ConstantFP::get(Ty->getContext(), U);
2044     }
2045 
2046     if (IntrinsicID == Intrinsic::ceil) {
2047       U.roundToIntegral(APFloat::rmTowardPositive);
2048       return ConstantFP::get(Ty->getContext(), U);
2049     }
2050 
2051     if (IntrinsicID == Intrinsic::floor) {
2052       U.roundToIntegral(APFloat::rmTowardNegative);
2053       return ConstantFP::get(Ty->getContext(), U);
2054     }
2055 
2056     if (IntrinsicID == Intrinsic::trunc) {
2057       U.roundToIntegral(APFloat::rmTowardZero);
2058       return ConstantFP::get(Ty->getContext(), U);
2059     }
2060 
2061     if (IntrinsicID == Intrinsic::fabs) {
2062       U.clearSign();
2063       return ConstantFP::get(Ty->getContext(), U);
2064     }
2065 
2066     if (IntrinsicID == Intrinsic::amdgcn_fract) {
2067       // The v_fract instruction behaves like the OpenCL spec, which defines
2068       // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2069       //   there to prevent fract(-small) from returning 1.0. It returns the
2070       //   largest positive floating-point number less than 1.0."
2071       APFloat FloorU(U);
2072       FloorU.roundToIntegral(APFloat::rmTowardNegative);
2073       APFloat FractU(U - FloorU);
2074       APFloat AlmostOne(U.getSemantics(), 1);
2075       AlmostOne.next(/*nextDown*/ true);
2076       return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
2077     }
2078 
2079     // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2080     // raise FP exceptions, unless the argument is signaling NaN.
2081 
2082     Optional<APFloat::roundingMode> RM;
2083     switch (IntrinsicID) {
2084     default:
2085       break;
2086     case Intrinsic::experimental_constrained_nearbyint:
2087     case Intrinsic::experimental_constrained_rint: {
2088       auto CI = cast<ConstrainedFPIntrinsic>(Call);
2089       RM = CI->getRoundingMode();
2090       if (!RM || *RM == RoundingMode::Dynamic)
2091         return nullptr;
2092       break;
2093     }
2094     case Intrinsic::experimental_constrained_round:
2095       RM = APFloat::rmNearestTiesToAway;
2096       break;
2097     case Intrinsic::experimental_constrained_ceil:
2098       RM = APFloat::rmTowardPositive;
2099       break;
2100     case Intrinsic::experimental_constrained_floor:
2101       RM = APFloat::rmTowardNegative;
2102       break;
2103     case Intrinsic::experimental_constrained_trunc:
2104       RM = APFloat::rmTowardZero;
2105       break;
2106     }
2107     if (RM) {
2108       auto CI = cast<ConstrainedFPIntrinsic>(Call);
2109       if (U.isFinite()) {
2110         APFloat::opStatus St = U.roundToIntegral(*RM);
2111         if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2112             St == APFloat::opInexact) {
2113           Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2114           if (EB && *EB == fp::ebStrict)
2115             return nullptr;
2116         }
2117       } else if (U.isSignaling()) {
2118         Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2119         if (EB && *EB != fp::ebIgnore)
2120           return nullptr;
2121         U = APFloat::getQNaN(U.getSemantics());
2122       }
2123       return ConstantFP::get(Ty->getContext(), U);
2124     }
2125 
2126     /// We only fold functions with finite arguments. Folding NaN and inf is
2127     /// likely to be aborted with an exception anyway, and some host libms
2128     /// have known errors raising exceptions.
2129     if (!U.isFinite())
2130       return nullptr;
2131 
2132     /// Currently APFloat versions of these functions do not exist, so we use
2133     /// the host native double versions.  Float versions are not called
2134     /// directly but for all these it is true (float)(f((double)arg)) ==
2135     /// f(arg).  Long double not supported yet.
2136     const APFloat &APF = Op->getValueAPF();
2137 
2138     switch (IntrinsicID) {
2139       default: break;
2140       case Intrinsic::log:
2141         return ConstantFoldFP(log, APF, Ty);
2142       case Intrinsic::log2:
2143         // TODO: What about hosts that lack a C99 library?
2144         return ConstantFoldFP(Log2, APF, Ty);
2145       case Intrinsic::log10:
2146         // TODO: What about hosts that lack a C99 library?
2147         return ConstantFoldFP(log10, APF, Ty);
2148       case Intrinsic::exp:
2149         return ConstantFoldFP(exp, APF, Ty);
2150       case Intrinsic::exp2:
2151         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2152         return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2153       case Intrinsic::sin:
2154         return ConstantFoldFP(sin, APF, Ty);
2155       case Intrinsic::cos:
2156         return ConstantFoldFP(cos, APF, Ty);
2157       case Intrinsic::sqrt:
2158         return ConstantFoldFP(sqrt, APF, Ty);
2159       case Intrinsic::amdgcn_cos:
2160       case Intrinsic::amdgcn_sin: {
2161         double V = getValueAsDouble(Op);
2162         if (V < -256.0 || V > 256.0)
2163           // The gfx8 and gfx9 architectures handle arguments outside the range
2164           // [-256, 256] differently. This should be a rare case so bail out
2165           // rather than trying to handle the difference.
2166           return nullptr;
2167         bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2168         double V4 = V * 4.0;
2169         if (V4 == floor(V4)) {
2170           // Force exact results for quarter-integer inputs.
2171           const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2172           V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2173         } else {
2174           if (IsCos)
2175             V = cos(V * 2.0 * numbers::pi);
2176           else
2177             V = sin(V * 2.0 * numbers::pi);
2178         }
2179         return GetConstantFoldFPValue(V, Ty);
2180       }
2181     }
2182 
2183     if (!TLI)
2184       return nullptr;
2185 
2186     LibFunc Func = NotLibFunc;
2187     if (!TLI->getLibFunc(Name, Func))
2188       return nullptr;
2189 
2190     switch (Func) {
2191     default:
2192       break;
2193     case LibFunc_acos:
2194     case LibFunc_acosf:
2195     case LibFunc_acos_finite:
2196     case LibFunc_acosf_finite:
2197       if (TLI->has(Func))
2198         return ConstantFoldFP(acos, APF, Ty);
2199       break;
2200     case LibFunc_asin:
2201     case LibFunc_asinf:
2202     case LibFunc_asin_finite:
2203     case LibFunc_asinf_finite:
2204       if (TLI->has(Func))
2205         return ConstantFoldFP(asin, APF, Ty);
2206       break;
2207     case LibFunc_atan:
2208     case LibFunc_atanf:
2209       if (TLI->has(Func))
2210         return ConstantFoldFP(atan, APF, Ty);
2211       break;
2212     case LibFunc_ceil:
2213     case LibFunc_ceilf:
2214       if (TLI->has(Func)) {
2215         U.roundToIntegral(APFloat::rmTowardPositive);
2216         return ConstantFP::get(Ty->getContext(), U);
2217       }
2218       break;
2219     case LibFunc_cos:
2220     case LibFunc_cosf:
2221       if (TLI->has(Func))
2222         return ConstantFoldFP(cos, APF, Ty);
2223       break;
2224     case LibFunc_cosh:
2225     case LibFunc_coshf:
2226     case LibFunc_cosh_finite:
2227     case LibFunc_coshf_finite:
2228       if (TLI->has(Func))
2229         return ConstantFoldFP(cosh, APF, Ty);
2230       break;
2231     case LibFunc_exp:
2232     case LibFunc_expf:
2233     case LibFunc_exp_finite:
2234     case LibFunc_expf_finite:
2235       if (TLI->has(Func))
2236         return ConstantFoldFP(exp, APF, Ty);
2237       break;
2238     case LibFunc_exp2:
2239     case LibFunc_exp2f:
2240     case LibFunc_exp2_finite:
2241     case LibFunc_exp2f_finite:
2242       if (TLI->has(Func))
2243         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2244         return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2245       break;
2246     case LibFunc_fabs:
2247     case LibFunc_fabsf:
2248       if (TLI->has(Func)) {
2249         U.clearSign();
2250         return ConstantFP::get(Ty->getContext(), U);
2251       }
2252       break;
2253     case LibFunc_floor:
2254     case LibFunc_floorf:
2255       if (TLI->has(Func)) {
2256         U.roundToIntegral(APFloat::rmTowardNegative);
2257         return ConstantFP::get(Ty->getContext(), U);
2258       }
2259       break;
2260     case LibFunc_log:
2261     case LibFunc_logf:
2262     case LibFunc_log_finite:
2263     case LibFunc_logf_finite:
2264       if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2265         return ConstantFoldFP(log, APF, Ty);
2266       break;
2267     case LibFunc_log2:
2268     case LibFunc_log2f:
2269     case LibFunc_log2_finite:
2270     case LibFunc_log2f_finite:
2271       if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2272         // TODO: What about hosts that lack a C99 library?
2273         return ConstantFoldFP(Log2, APF, Ty);
2274       break;
2275     case LibFunc_log10:
2276     case LibFunc_log10f:
2277     case LibFunc_log10_finite:
2278     case LibFunc_log10f_finite:
2279       if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2280         // TODO: What about hosts that lack a C99 library?
2281         return ConstantFoldFP(log10, APF, Ty);
2282       break;
2283     case LibFunc_nearbyint:
2284     case LibFunc_nearbyintf:
2285     case LibFunc_rint:
2286     case LibFunc_rintf:
2287       if (TLI->has(Func)) {
2288         U.roundToIntegral(APFloat::rmNearestTiesToEven);
2289         return ConstantFP::get(Ty->getContext(), U);
2290       }
2291       break;
2292     case LibFunc_round:
2293     case LibFunc_roundf:
2294       if (TLI->has(Func)) {
2295         U.roundToIntegral(APFloat::rmNearestTiesToAway);
2296         return ConstantFP::get(Ty->getContext(), U);
2297       }
2298       break;
2299     case LibFunc_sin:
2300     case LibFunc_sinf:
2301       if (TLI->has(Func))
2302         return ConstantFoldFP(sin, APF, Ty);
2303       break;
2304     case LibFunc_sinh:
2305     case LibFunc_sinhf:
2306     case LibFunc_sinh_finite:
2307     case LibFunc_sinhf_finite:
2308       if (TLI->has(Func))
2309         return ConstantFoldFP(sinh, APF, Ty);
2310       break;
2311     case LibFunc_sqrt:
2312     case LibFunc_sqrtf:
2313       if (!APF.isNegative() && TLI->has(Func))
2314         return ConstantFoldFP(sqrt, APF, Ty);
2315       break;
2316     case LibFunc_tan:
2317     case LibFunc_tanf:
2318       if (TLI->has(Func))
2319         return ConstantFoldFP(tan, APF, Ty);
2320       break;
2321     case LibFunc_tanh:
2322     case LibFunc_tanhf:
2323       if (TLI->has(Func))
2324         return ConstantFoldFP(tanh, APF, Ty);
2325       break;
2326     case LibFunc_trunc:
2327     case LibFunc_truncf:
2328       if (TLI->has(Func)) {
2329         U.roundToIntegral(APFloat::rmTowardZero);
2330         return ConstantFP::get(Ty->getContext(), U);
2331       }
2332       break;
2333     }
2334     return nullptr;
2335   }
2336 
2337   if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2338     switch (IntrinsicID) {
2339     case Intrinsic::bswap:
2340       return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2341     case Intrinsic::ctpop:
2342       return ConstantInt::get(Ty, Op->getValue().countPopulation());
2343     case Intrinsic::bitreverse:
2344       return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2345     case Intrinsic::convert_from_fp16: {
2346       APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2347 
2348       bool lost = false;
2349       APFloat::opStatus status = Val.convert(
2350           Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2351 
2352       // Conversion is always precise.
2353       (void)status;
2354       assert(status == APFloat::opOK && !lost &&
2355              "Precision lost during fp16 constfolding");
2356 
2357       return ConstantFP::get(Ty->getContext(), Val);
2358     }
2359     default:
2360       return nullptr;
2361     }
2362   }
2363 
2364   switch (IntrinsicID) {
2365   default: break;
2366   case Intrinsic::vector_reduce_add:
2367   case Intrinsic::vector_reduce_mul:
2368   case Intrinsic::vector_reduce_and:
2369   case Intrinsic::vector_reduce_or:
2370   case Intrinsic::vector_reduce_xor:
2371   case Intrinsic::vector_reduce_smin:
2372   case Intrinsic::vector_reduce_smax:
2373   case Intrinsic::vector_reduce_umin:
2374   case Intrinsic::vector_reduce_umax:
2375     if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
2376       return C;
2377     break;
2378   }
2379 
2380   // Support ConstantVector in case we have an Undef in the top.
2381   if (isa<ConstantVector>(Operands[0]) ||
2382       isa<ConstantDataVector>(Operands[0])) {
2383     auto *Op = cast<Constant>(Operands[0]);
2384     switch (IntrinsicID) {
2385     default: break;
2386     case Intrinsic::x86_sse_cvtss2si:
2387     case Intrinsic::x86_sse_cvtss2si64:
2388     case Intrinsic::x86_sse2_cvtsd2si:
2389     case Intrinsic::x86_sse2_cvtsd2si64:
2390       if (ConstantFP *FPOp =
2391               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2392         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2393                                            /*roundTowardZero=*/false, Ty,
2394                                            /*IsSigned*/true);
2395       break;
2396     case Intrinsic::x86_sse_cvttss2si:
2397     case Intrinsic::x86_sse_cvttss2si64:
2398     case Intrinsic::x86_sse2_cvttsd2si:
2399     case Intrinsic::x86_sse2_cvttsd2si64:
2400       if (ConstantFP *FPOp =
2401               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2402         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2403                                            /*roundTowardZero=*/true, Ty,
2404                                            /*IsSigned*/true);
2405       break;
2406     }
2407   }
2408 
2409   return nullptr;
2410 }
2411 
2412 static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2,
2413                                  const ConstrainedFPIntrinsic *Call) {
2414   APFloat::opStatus St = APFloat::opOK;
2415   auto *FCmp = cast<ConstrainedFPCmpIntrinsic>(Call);
2416   FCmpInst::Predicate Cond = FCmp->getPredicate();
2417   if (FCmp->isSignaling()) {
2418     if (Op1.isNaN() || Op2.isNaN())
2419       St = APFloat::opInvalidOp;
2420   } else {
2421     if (Op1.isSignaling() || Op2.isSignaling())
2422       St = APFloat::opInvalidOp;
2423   }
2424   bool Result = FCmpInst::compare(Op1, Op2, Cond);
2425   if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St))
2426     return ConstantInt::get(Call->getType()->getScalarType(), Result);
2427   return nullptr;
2428 }
2429 
2430 static Constant *ConstantFoldScalarCall2(StringRef Name,
2431                                          Intrinsic::ID IntrinsicID,
2432                                          Type *Ty,
2433                                          ArrayRef<Constant *> Operands,
2434                                          const TargetLibraryInfo *TLI,
2435                                          const CallBase *Call) {
2436   assert(Operands.size() == 2 && "Wrong number of operands.");
2437 
2438   if (Ty->isFloatingPointTy()) {
2439     // TODO: We should have undef handling for all of the FP intrinsics that
2440     //       are attempted to be folded in this function.
2441     bool IsOp0Undef = isa<UndefValue>(Operands[0]);
2442     bool IsOp1Undef = isa<UndefValue>(Operands[1]);
2443     switch (IntrinsicID) {
2444     case Intrinsic::maxnum:
2445     case Intrinsic::minnum:
2446     case Intrinsic::maximum:
2447     case Intrinsic::minimum:
2448       // If one argument is undef, return the other argument.
2449       if (IsOp0Undef)
2450         return Operands[1];
2451       if (IsOp1Undef)
2452         return Operands[0];
2453       break;
2454     }
2455   }
2456 
2457   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2458     const APFloat &Op1V = Op1->getValueAPF();
2459 
2460     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2461       if (Op2->getType() != Op1->getType())
2462         return nullptr;
2463       const APFloat &Op2V = Op2->getValueAPF();
2464 
2465       if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2466         RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2467         APFloat Res = Op1V;
2468         APFloat::opStatus St;
2469         switch (IntrinsicID) {
2470         default:
2471           return nullptr;
2472         case Intrinsic::experimental_constrained_fadd:
2473           St = Res.add(Op2V, RM);
2474           break;
2475         case Intrinsic::experimental_constrained_fsub:
2476           St = Res.subtract(Op2V, RM);
2477           break;
2478         case Intrinsic::experimental_constrained_fmul:
2479           St = Res.multiply(Op2V, RM);
2480           break;
2481         case Intrinsic::experimental_constrained_fdiv:
2482           St = Res.divide(Op2V, RM);
2483           break;
2484         case Intrinsic::experimental_constrained_frem:
2485           St = Res.mod(Op2V);
2486           break;
2487         case Intrinsic::experimental_constrained_fcmp:
2488         case Intrinsic::experimental_constrained_fcmps:
2489           return evaluateCompare(Op1V, Op2V, ConstrIntr);
2490         }
2491         if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
2492                                St))
2493           return ConstantFP::get(Ty->getContext(), Res);
2494         return nullptr;
2495       }
2496 
2497       switch (IntrinsicID) {
2498       default:
2499         break;
2500       case Intrinsic::copysign:
2501         return ConstantFP::get(Ty->getContext(), APFloat::copySign(Op1V, Op2V));
2502       case Intrinsic::minnum:
2503         return ConstantFP::get(Ty->getContext(), minnum(Op1V, Op2V));
2504       case Intrinsic::maxnum:
2505         return ConstantFP::get(Ty->getContext(), maxnum(Op1V, Op2V));
2506       case Intrinsic::minimum:
2507         return ConstantFP::get(Ty->getContext(), minimum(Op1V, Op2V));
2508       case Intrinsic::maximum:
2509         return ConstantFP::get(Ty->getContext(), maximum(Op1V, Op2V));
2510       }
2511 
2512       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2513         return nullptr;
2514 
2515       switch (IntrinsicID) {
2516       default:
2517         break;
2518       case Intrinsic::pow:
2519         return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2520       case Intrinsic::amdgcn_fmul_legacy:
2521         // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2522         // NaN or infinity, gives +0.0.
2523         if (Op1V.isZero() || Op2V.isZero())
2524           return ConstantFP::getNullValue(Ty);
2525         return ConstantFP::get(Ty->getContext(), Op1V * Op2V);
2526       }
2527 
2528       if (!TLI)
2529         return nullptr;
2530 
2531       LibFunc Func = NotLibFunc;
2532       if (!TLI->getLibFunc(Name, Func))
2533         return nullptr;
2534 
2535       switch (Func) {
2536       default:
2537         break;
2538       case LibFunc_pow:
2539       case LibFunc_powf:
2540       case LibFunc_pow_finite:
2541       case LibFunc_powf_finite:
2542         if (TLI->has(Func))
2543           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2544         break;
2545       case LibFunc_fmod:
2546       case LibFunc_fmodf:
2547         if (TLI->has(Func)) {
2548           APFloat V = Op1->getValueAPF();
2549           if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2550             return ConstantFP::get(Ty->getContext(), V);
2551         }
2552         break;
2553       case LibFunc_remainder:
2554       case LibFunc_remainderf:
2555         if (TLI->has(Func)) {
2556           APFloat V = Op1->getValueAPF();
2557           if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2558             return ConstantFP::get(Ty->getContext(), V);
2559         }
2560         break;
2561       case LibFunc_atan2:
2562       case LibFunc_atan2f:
2563       case LibFunc_atan2_finite:
2564       case LibFunc_atan2f_finite:
2565         if (TLI->has(Func))
2566           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2567         break;
2568       }
2569     } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2570       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2571         return nullptr;
2572       if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2573         return ConstantFP::get(
2574             Ty->getContext(),
2575             APFloat((float)std::pow((float)Op1V.convertToDouble(),
2576                                     (int)Op2C->getZExtValue())));
2577       if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2578         return ConstantFP::get(
2579             Ty->getContext(),
2580             APFloat((float)std::pow((float)Op1V.convertToDouble(),
2581                                     (int)Op2C->getZExtValue())));
2582       if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2583         return ConstantFP::get(
2584             Ty->getContext(),
2585             APFloat((double)std::pow(Op1V.convertToDouble(),
2586                                      (int)Op2C->getZExtValue())));
2587 
2588       if (IntrinsicID == Intrinsic::amdgcn_ldexp) {
2589         // FIXME: Should flush denorms depending on FP mode, but that's ignored
2590         // everywhere else.
2591 
2592         // scalbn is equivalent to ldexp with float radix 2
2593         APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(),
2594                                 APFloat::rmNearestTiesToEven);
2595         return ConstantFP::get(Ty->getContext(), Result);
2596       }
2597     }
2598     return nullptr;
2599   }
2600 
2601   if (Operands[0]->getType()->isIntegerTy() &&
2602       Operands[1]->getType()->isIntegerTy()) {
2603     const APInt *C0, *C1;
2604     if (!getConstIntOrUndef(Operands[0], C0) ||
2605         !getConstIntOrUndef(Operands[1], C1))
2606       return nullptr;
2607 
2608     switch (IntrinsicID) {
2609     default: break;
2610     case Intrinsic::smax:
2611     case Intrinsic::smin:
2612     case Intrinsic::umax:
2613     case Intrinsic::umin:
2614       // This is the same as for binary ops - poison propagates.
2615       // TODO: Poison handling should be consolidated.
2616       if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2617         return PoisonValue::get(Ty);
2618 
2619       if (!C0 && !C1)
2620         return UndefValue::get(Ty);
2621       if (!C0 || !C1)
2622         return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty);
2623       return ConstantInt::get(
2624           Ty, ICmpInst::compare(*C0, *C1,
2625                                 MinMaxIntrinsic::getPredicate(IntrinsicID))
2626                   ? *C0
2627                   : *C1);
2628 
2629     case Intrinsic::usub_with_overflow:
2630     case Intrinsic::ssub_with_overflow:
2631       // X - undef -> { 0, false }
2632       // undef - X -> { 0, false }
2633       if (!C0 || !C1)
2634         return Constant::getNullValue(Ty);
2635       LLVM_FALLTHROUGH;
2636     case Intrinsic::uadd_with_overflow:
2637     case Intrinsic::sadd_with_overflow:
2638       // X + undef -> { -1, false }
2639       // undef + x -> { -1, false }
2640       if (!C0 || !C1) {
2641         return ConstantStruct::get(
2642             cast<StructType>(Ty),
2643             {Constant::getAllOnesValue(Ty->getStructElementType(0)),
2644              Constant::getNullValue(Ty->getStructElementType(1))});
2645       }
2646       LLVM_FALLTHROUGH;
2647     case Intrinsic::smul_with_overflow:
2648     case Intrinsic::umul_with_overflow: {
2649       // undef * X -> { 0, false }
2650       // X * undef -> { 0, false }
2651       if (!C0 || !C1)
2652         return Constant::getNullValue(Ty);
2653 
2654       APInt Res;
2655       bool Overflow;
2656       switch (IntrinsicID) {
2657       default: llvm_unreachable("Invalid case");
2658       case Intrinsic::sadd_with_overflow:
2659         Res = C0->sadd_ov(*C1, Overflow);
2660         break;
2661       case Intrinsic::uadd_with_overflow:
2662         Res = C0->uadd_ov(*C1, Overflow);
2663         break;
2664       case Intrinsic::ssub_with_overflow:
2665         Res = C0->ssub_ov(*C1, Overflow);
2666         break;
2667       case Intrinsic::usub_with_overflow:
2668         Res = C0->usub_ov(*C1, Overflow);
2669         break;
2670       case Intrinsic::smul_with_overflow:
2671         Res = C0->smul_ov(*C1, Overflow);
2672         break;
2673       case Intrinsic::umul_with_overflow:
2674         Res = C0->umul_ov(*C1, Overflow);
2675         break;
2676       }
2677       Constant *Ops[] = {
2678         ConstantInt::get(Ty->getContext(), Res),
2679         ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2680       };
2681       return ConstantStruct::get(cast<StructType>(Ty), Ops);
2682     }
2683     case Intrinsic::uadd_sat:
2684     case Intrinsic::sadd_sat:
2685       // This is the same as for binary ops - poison propagates.
2686       // TODO: Poison handling should be consolidated.
2687       if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2688         return PoisonValue::get(Ty);
2689 
2690       if (!C0 && !C1)
2691         return UndefValue::get(Ty);
2692       if (!C0 || !C1)
2693         return Constant::getAllOnesValue(Ty);
2694       if (IntrinsicID == Intrinsic::uadd_sat)
2695         return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2696       else
2697         return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2698     case Intrinsic::usub_sat:
2699     case Intrinsic::ssub_sat:
2700       // This is the same as for binary ops - poison propagates.
2701       // TODO: Poison handling should be consolidated.
2702       if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2703         return PoisonValue::get(Ty);
2704 
2705       if (!C0 && !C1)
2706         return UndefValue::get(Ty);
2707       if (!C0 || !C1)
2708         return Constant::getNullValue(Ty);
2709       if (IntrinsicID == Intrinsic::usub_sat)
2710         return ConstantInt::get(Ty, C0->usub_sat(*C1));
2711       else
2712         return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2713     case Intrinsic::cttz:
2714     case Intrinsic::ctlz:
2715       assert(C1 && "Must be constant int");
2716 
2717       // cttz(0, 1) and ctlz(0, 1) are poison.
2718       if (C1->isOne() && (!C0 || C0->isZero()))
2719         return PoisonValue::get(Ty);
2720       if (!C0)
2721         return Constant::getNullValue(Ty);
2722       if (IntrinsicID == Intrinsic::cttz)
2723         return ConstantInt::get(Ty, C0->countTrailingZeros());
2724       else
2725         return ConstantInt::get(Ty, C0->countLeadingZeros());
2726 
2727     case Intrinsic::abs:
2728       assert(C1 && "Must be constant int");
2729       assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1");
2730 
2731       // Undef or minimum val operand with poison min --> undef
2732       if (C1->isOne() && (!C0 || C0->isMinSignedValue()))
2733         return UndefValue::get(Ty);
2734 
2735       // Undef operand with no poison min --> 0 (sign bit must be clear)
2736       if (!C0)
2737         return Constant::getNullValue(Ty);
2738 
2739       return ConstantInt::get(Ty, C0->abs());
2740     }
2741 
2742     return nullptr;
2743   }
2744 
2745   // Support ConstantVector in case we have an Undef in the top.
2746   if ((isa<ConstantVector>(Operands[0]) ||
2747        isa<ConstantDataVector>(Operands[0])) &&
2748       // Check for default rounding mode.
2749       // FIXME: Support other rounding modes?
2750       isa<ConstantInt>(Operands[1]) &&
2751       cast<ConstantInt>(Operands[1])->getValue() == 4) {
2752     auto *Op = cast<Constant>(Operands[0]);
2753     switch (IntrinsicID) {
2754     default: break;
2755     case Intrinsic::x86_avx512_vcvtss2si32:
2756     case Intrinsic::x86_avx512_vcvtss2si64:
2757     case Intrinsic::x86_avx512_vcvtsd2si32:
2758     case Intrinsic::x86_avx512_vcvtsd2si64:
2759       if (ConstantFP *FPOp =
2760               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2761         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2762                                            /*roundTowardZero=*/false, Ty,
2763                                            /*IsSigned*/true);
2764       break;
2765     case Intrinsic::x86_avx512_vcvtss2usi32:
2766     case Intrinsic::x86_avx512_vcvtss2usi64:
2767     case Intrinsic::x86_avx512_vcvtsd2usi32:
2768     case Intrinsic::x86_avx512_vcvtsd2usi64:
2769       if (ConstantFP *FPOp =
2770               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2771         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2772                                            /*roundTowardZero=*/false, Ty,
2773                                            /*IsSigned*/false);
2774       break;
2775     case Intrinsic::x86_avx512_cvttss2si:
2776     case Intrinsic::x86_avx512_cvttss2si64:
2777     case Intrinsic::x86_avx512_cvttsd2si:
2778     case Intrinsic::x86_avx512_cvttsd2si64:
2779       if (ConstantFP *FPOp =
2780               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2781         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2782                                            /*roundTowardZero=*/true, Ty,
2783                                            /*IsSigned*/true);
2784       break;
2785     case Intrinsic::x86_avx512_cvttss2usi:
2786     case Intrinsic::x86_avx512_cvttss2usi64:
2787     case Intrinsic::x86_avx512_cvttsd2usi:
2788     case Intrinsic::x86_avx512_cvttsd2usi64:
2789       if (ConstantFP *FPOp =
2790               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2791         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2792                                            /*roundTowardZero=*/true, Ty,
2793                                            /*IsSigned*/false);
2794       break;
2795     }
2796   }
2797   return nullptr;
2798 }
2799 
2800 static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2801                                                const APFloat &S0,
2802                                                const APFloat &S1,
2803                                                const APFloat &S2) {
2804   unsigned ID;
2805   const fltSemantics &Sem = S0.getSemantics();
2806   APFloat MA(Sem), SC(Sem), TC(Sem);
2807   if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2808     if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2809       // S2 < 0
2810       ID = 5;
2811       SC = -S0;
2812     } else {
2813       ID = 4;
2814       SC = S0;
2815     }
2816     MA = S2;
2817     TC = -S1;
2818   } else if (abs(S1) >= abs(S0)) {
2819     if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2820       // S1 < 0
2821       ID = 3;
2822       TC = -S2;
2823     } else {
2824       ID = 2;
2825       TC = S2;
2826     }
2827     MA = S1;
2828     SC = S0;
2829   } else {
2830     if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2831       // S0 < 0
2832       ID = 1;
2833       SC = S2;
2834     } else {
2835       ID = 0;
2836       SC = -S2;
2837     }
2838     MA = S0;
2839     TC = -S1;
2840   }
2841   switch (IntrinsicID) {
2842   default:
2843     llvm_unreachable("unhandled amdgcn cube intrinsic");
2844   case Intrinsic::amdgcn_cubeid:
2845     return APFloat(Sem, ID);
2846   case Intrinsic::amdgcn_cubema:
2847     return MA + MA;
2848   case Intrinsic::amdgcn_cubesc:
2849     return SC;
2850   case Intrinsic::amdgcn_cubetc:
2851     return TC;
2852   }
2853 }
2854 
2855 static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
2856                                                  Type *Ty) {
2857   const APInt *C0, *C1, *C2;
2858   if (!getConstIntOrUndef(Operands[0], C0) ||
2859       !getConstIntOrUndef(Operands[1], C1) ||
2860       !getConstIntOrUndef(Operands[2], C2))
2861     return nullptr;
2862 
2863   if (!C2)
2864     return UndefValue::get(Ty);
2865 
2866   APInt Val(32, 0);
2867   unsigned NumUndefBytes = 0;
2868   for (unsigned I = 0; I < 32; I += 8) {
2869     unsigned Sel = C2->extractBitsAsZExtValue(8, I);
2870     unsigned B = 0;
2871 
2872     if (Sel >= 13)
2873       B = 0xff;
2874     else if (Sel == 12)
2875       B = 0x00;
2876     else {
2877       const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
2878       if (!Src)
2879         ++NumUndefBytes;
2880       else if (Sel < 8)
2881         B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
2882       else
2883         B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
2884     }
2885 
2886     Val.insertBits(B, I, 8);
2887   }
2888 
2889   if (NumUndefBytes == 4)
2890     return UndefValue::get(Ty);
2891 
2892   return ConstantInt::get(Ty, Val);
2893 }
2894 
2895 static Constant *ConstantFoldScalarCall3(StringRef Name,
2896                                          Intrinsic::ID IntrinsicID,
2897                                          Type *Ty,
2898                                          ArrayRef<Constant *> Operands,
2899                                          const TargetLibraryInfo *TLI,
2900                                          const CallBase *Call) {
2901   assert(Operands.size() == 3 && "Wrong number of operands.");
2902 
2903   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2904     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2905       if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2906         const APFloat &C1 = Op1->getValueAPF();
2907         const APFloat &C2 = Op2->getValueAPF();
2908         const APFloat &C3 = Op3->getValueAPF();
2909 
2910         if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2911           RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2912           APFloat Res = C1;
2913           APFloat::opStatus St;
2914           switch (IntrinsicID) {
2915           default:
2916             return nullptr;
2917           case Intrinsic::experimental_constrained_fma:
2918           case Intrinsic::experimental_constrained_fmuladd:
2919             St = Res.fusedMultiplyAdd(C2, C3, RM);
2920             break;
2921           }
2922           if (mayFoldConstrained(
2923                   const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
2924             return ConstantFP::get(Ty->getContext(), Res);
2925           return nullptr;
2926         }
2927 
2928         switch (IntrinsicID) {
2929         default: break;
2930         case Intrinsic::amdgcn_fma_legacy: {
2931           // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2932           // NaN or infinity, gives +0.0.
2933           if (C1.isZero() || C2.isZero()) {
2934             // It's tempting to just return C3 here, but that would give the
2935             // wrong result if C3 was -0.0.
2936             return ConstantFP::get(Ty->getContext(), APFloat(0.0f) + C3);
2937           }
2938           LLVM_FALLTHROUGH;
2939         }
2940         case Intrinsic::fma:
2941         case Intrinsic::fmuladd: {
2942           APFloat V = C1;
2943           V.fusedMultiplyAdd(C2, C3, APFloat::rmNearestTiesToEven);
2944           return ConstantFP::get(Ty->getContext(), V);
2945         }
2946         case Intrinsic::amdgcn_cubeid:
2947         case Intrinsic::amdgcn_cubema:
2948         case Intrinsic::amdgcn_cubesc:
2949         case Intrinsic::amdgcn_cubetc: {
2950           APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
2951           return ConstantFP::get(Ty->getContext(), V);
2952         }
2953         }
2954       }
2955     }
2956   }
2957 
2958   if (IntrinsicID == Intrinsic::smul_fix ||
2959       IntrinsicID == Intrinsic::smul_fix_sat) {
2960     // poison * C -> poison
2961     // C * poison -> poison
2962     if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2963       return PoisonValue::get(Ty);
2964 
2965     const APInt *C0, *C1;
2966     if (!getConstIntOrUndef(Operands[0], C0) ||
2967         !getConstIntOrUndef(Operands[1], C1))
2968       return nullptr;
2969 
2970     // undef * C -> 0
2971     // C * undef -> 0
2972     if (!C0 || !C1)
2973       return Constant::getNullValue(Ty);
2974 
2975     // This code performs rounding towards negative infinity in case the result
2976     // cannot be represented exactly for the given scale. Targets that do care
2977     // about rounding should use a target hook for specifying how rounding
2978     // should be done, and provide their own folding to be consistent with
2979     // rounding. This is the same approach as used by
2980     // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2981     unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
2982     unsigned Width = C0->getBitWidth();
2983     assert(Scale < Width && "Illegal scale.");
2984     unsigned ExtendedWidth = Width * 2;
2985     APInt Product =
2986         (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale);
2987     if (IntrinsicID == Intrinsic::smul_fix_sat) {
2988       APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth);
2989       APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth);
2990       Product = APIntOps::smin(Product, Max);
2991       Product = APIntOps::smax(Product, Min);
2992     }
2993     return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
2994   }
2995 
2996   if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
2997     const APInt *C0, *C1, *C2;
2998     if (!getConstIntOrUndef(Operands[0], C0) ||
2999         !getConstIntOrUndef(Operands[1], C1) ||
3000         !getConstIntOrUndef(Operands[2], C2))
3001       return nullptr;
3002 
3003     bool IsRight = IntrinsicID == Intrinsic::fshr;
3004     if (!C2)
3005       return Operands[IsRight ? 1 : 0];
3006     if (!C0 && !C1)
3007       return UndefValue::get(Ty);
3008 
3009     // The shift amount is interpreted as modulo the bitwidth. If the shift
3010     // amount is effectively 0, avoid UB due to oversized inverse shift below.
3011     unsigned BitWidth = C2->getBitWidth();
3012     unsigned ShAmt = C2->urem(BitWidth);
3013     if (!ShAmt)
3014       return Operands[IsRight ? 1 : 0];
3015 
3016     // (C0 << ShlAmt) | (C1 >> LshrAmt)
3017     unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
3018     unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
3019     if (!C0)
3020       return ConstantInt::get(Ty, C1->lshr(LshrAmt));
3021     if (!C1)
3022       return ConstantInt::get(Ty, C0->shl(ShlAmt));
3023     return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
3024   }
3025 
3026   if (IntrinsicID == Intrinsic::amdgcn_perm)
3027     return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
3028 
3029   return nullptr;
3030 }
3031 
3032 static Constant *ConstantFoldScalarCall(StringRef Name,
3033                                         Intrinsic::ID IntrinsicID,
3034                                         Type *Ty,
3035                                         ArrayRef<Constant *> Operands,
3036                                         const TargetLibraryInfo *TLI,
3037                                         const CallBase *Call) {
3038   if (Operands.size() == 1)
3039     return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
3040 
3041   if (Operands.size() == 2)
3042     return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
3043 
3044   if (Operands.size() == 3)
3045     return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
3046 
3047   return nullptr;
3048 }
3049 
3050 static Constant *ConstantFoldFixedVectorCall(
3051     StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
3052     ArrayRef<Constant *> Operands, const DataLayout &DL,
3053     const TargetLibraryInfo *TLI, const CallBase *Call) {
3054   SmallVector<Constant *, 4> Result(FVTy->getNumElements());
3055   SmallVector<Constant *, 4> Lane(Operands.size());
3056   Type *Ty = FVTy->getElementType();
3057 
3058   switch (IntrinsicID) {
3059   case Intrinsic::masked_load: {
3060     auto *SrcPtr = Operands[0];
3061     auto *Mask = Operands[2];
3062     auto *Passthru = Operands[3];
3063 
3064     Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
3065 
3066     SmallVector<Constant *, 32> NewElements;
3067     for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3068       auto *MaskElt = Mask->getAggregateElement(I);
3069       if (!MaskElt)
3070         break;
3071       auto *PassthruElt = Passthru->getAggregateElement(I);
3072       auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
3073       if (isa<UndefValue>(MaskElt)) {
3074         if (PassthruElt)
3075           NewElements.push_back(PassthruElt);
3076         else if (VecElt)
3077           NewElements.push_back(VecElt);
3078         else
3079           return nullptr;
3080       }
3081       if (MaskElt->isNullValue()) {
3082         if (!PassthruElt)
3083           return nullptr;
3084         NewElements.push_back(PassthruElt);
3085       } else if (MaskElt->isOneValue()) {
3086         if (!VecElt)
3087           return nullptr;
3088         NewElements.push_back(VecElt);
3089       } else {
3090         return nullptr;
3091       }
3092     }
3093     if (NewElements.size() != FVTy->getNumElements())
3094       return nullptr;
3095     return ConstantVector::get(NewElements);
3096   }
3097   case Intrinsic::arm_mve_vctp8:
3098   case Intrinsic::arm_mve_vctp16:
3099   case Intrinsic::arm_mve_vctp32:
3100   case Intrinsic::arm_mve_vctp64: {
3101     if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3102       unsigned Lanes = FVTy->getNumElements();
3103       uint64_t Limit = Op->getZExtValue();
3104 
3105       SmallVector<Constant *, 16> NCs;
3106       for (unsigned i = 0; i < Lanes; i++) {
3107         if (i < Limit)
3108           NCs.push_back(ConstantInt::getTrue(Ty));
3109         else
3110           NCs.push_back(ConstantInt::getFalse(Ty));
3111       }
3112       return ConstantVector::get(NCs);
3113     }
3114     break;
3115   }
3116   case Intrinsic::get_active_lane_mask: {
3117     auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
3118     auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
3119     if (Op0 && Op1) {
3120       unsigned Lanes = FVTy->getNumElements();
3121       uint64_t Base = Op0->getZExtValue();
3122       uint64_t Limit = Op1->getZExtValue();
3123 
3124       SmallVector<Constant *, 16> NCs;
3125       for (unsigned i = 0; i < Lanes; i++) {
3126         if (Base + i < Limit)
3127           NCs.push_back(ConstantInt::getTrue(Ty));
3128         else
3129           NCs.push_back(ConstantInt::getFalse(Ty));
3130       }
3131       return ConstantVector::get(NCs);
3132     }
3133     break;
3134   }
3135   default:
3136     break;
3137   }
3138 
3139   for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3140     // Gather a column of constants.
3141     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
3142       // Some intrinsics use a scalar type for certain arguments.
3143       if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J)) {
3144         Lane[J] = Operands[J];
3145         continue;
3146       }
3147 
3148       Constant *Agg = Operands[J]->getAggregateElement(I);
3149       if (!Agg)
3150         return nullptr;
3151 
3152       Lane[J] = Agg;
3153     }
3154 
3155     // Use the regular scalar folding to simplify this column.
3156     Constant *Folded =
3157         ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
3158     if (!Folded)
3159       return nullptr;
3160     Result[I] = Folded;
3161   }
3162 
3163   return ConstantVector::get(Result);
3164 }
3165 
3166 static Constant *ConstantFoldScalableVectorCall(
3167     StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
3168     ArrayRef<Constant *> Operands, const DataLayout &DL,
3169     const TargetLibraryInfo *TLI, const CallBase *Call) {
3170   switch (IntrinsicID) {
3171   case Intrinsic::aarch64_sve_convert_from_svbool: {
3172     auto *Src = dyn_cast<Constant>(Operands[0]);
3173     if (!Src || !Src->isNullValue())
3174       break;
3175 
3176     return ConstantInt::getFalse(SVTy);
3177   }
3178   default:
3179     break;
3180   }
3181   return nullptr;
3182 }
3183 
3184 } // end anonymous namespace
3185 
3186 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
3187                                  ArrayRef<Constant *> Operands,
3188                                  const TargetLibraryInfo *TLI) {
3189   if (Call->isNoBuiltin())
3190     return nullptr;
3191   if (!F->hasName())
3192     return nullptr;
3193 
3194   // If this is not an intrinsic and not recognized as a library call, bail out.
3195   if (F->getIntrinsicID() == Intrinsic::not_intrinsic) {
3196     if (!TLI)
3197       return nullptr;
3198     LibFunc LibF;
3199     if (!TLI->getLibFunc(*F, LibF))
3200       return nullptr;
3201   }
3202 
3203   StringRef Name = F->getName();
3204   Type *Ty = F->getReturnType();
3205   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
3206     return ConstantFoldFixedVectorCall(
3207         Name, F->getIntrinsicID(), FVTy, Operands,
3208         F->getParent()->getDataLayout(), TLI, Call);
3209 
3210   if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
3211     return ConstantFoldScalableVectorCall(
3212         Name, F->getIntrinsicID(), SVTy, Operands,
3213         F->getParent()->getDataLayout(), TLI, Call);
3214 
3215   // TODO: If this is a library function, we already discovered that above,
3216   //       so we should pass the LibFunc, not the name (and it might be better
3217   //       still to separate intrinsic handling from libcalls).
3218   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
3219                                 Call);
3220 }
3221 
3222 bool llvm::isMathLibCallNoop(const CallBase *Call,
3223                              const TargetLibraryInfo *TLI) {
3224   // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
3225   // (and to some extent ConstantFoldScalarCall).
3226   if (Call->isNoBuiltin() || Call->isStrictFP())
3227     return false;
3228   Function *F = Call->getCalledFunction();
3229   if (!F)
3230     return false;
3231 
3232   LibFunc Func;
3233   if (!TLI || !TLI->getLibFunc(*F, Func))
3234     return false;
3235 
3236   if (Call->arg_size() == 1) {
3237     if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
3238       const APFloat &Op = OpC->getValueAPF();
3239       switch (Func) {
3240       case LibFunc_logl:
3241       case LibFunc_log:
3242       case LibFunc_logf:
3243       case LibFunc_log2l:
3244       case LibFunc_log2:
3245       case LibFunc_log2f:
3246       case LibFunc_log10l:
3247       case LibFunc_log10:
3248       case LibFunc_log10f:
3249         return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
3250 
3251       case LibFunc_expl:
3252       case LibFunc_exp:
3253       case LibFunc_expf:
3254         // FIXME: These boundaries are slightly conservative.
3255         if (OpC->getType()->isDoubleTy())
3256           return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
3257         if (OpC->getType()->isFloatTy())
3258           return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
3259         break;
3260 
3261       case LibFunc_exp2l:
3262       case LibFunc_exp2:
3263       case LibFunc_exp2f:
3264         // FIXME: These boundaries are slightly conservative.
3265         if (OpC->getType()->isDoubleTy())
3266           return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
3267         if (OpC->getType()->isFloatTy())
3268           return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
3269         break;
3270 
3271       case LibFunc_sinl:
3272       case LibFunc_sin:
3273       case LibFunc_sinf:
3274       case LibFunc_cosl:
3275       case LibFunc_cos:
3276       case LibFunc_cosf:
3277         return !Op.isInfinity();
3278 
3279       case LibFunc_tanl:
3280       case LibFunc_tan:
3281       case LibFunc_tanf: {
3282         // FIXME: Stop using the host math library.
3283         // FIXME: The computation isn't done in the right precision.
3284         Type *Ty = OpC->getType();
3285         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
3286           return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
3287         break;
3288       }
3289 
3290       case LibFunc_asinl:
3291       case LibFunc_asin:
3292       case LibFunc_asinf:
3293       case LibFunc_acosl:
3294       case LibFunc_acos:
3295       case LibFunc_acosf:
3296         return !(Op < APFloat(Op.getSemantics(), "-1") ||
3297                  Op > APFloat(Op.getSemantics(), "1"));
3298 
3299       case LibFunc_sinh:
3300       case LibFunc_cosh:
3301       case LibFunc_sinhf:
3302       case LibFunc_coshf:
3303       case LibFunc_sinhl:
3304       case LibFunc_coshl:
3305         // FIXME: These boundaries are slightly conservative.
3306         if (OpC->getType()->isDoubleTy())
3307           return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3308         if (OpC->getType()->isFloatTy())
3309           return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3310         break;
3311 
3312       case LibFunc_sqrtl:
3313       case LibFunc_sqrt:
3314       case LibFunc_sqrtf:
3315         return Op.isNaN() || Op.isZero() || !Op.isNegative();
3316 
3317       // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3318       // maybe others?
3319       default:
3320         break;
3321       }
3322     }
3323   }
3324 
3325   if (Call->arg_size() == 2) {
3326     ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3327     ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3328     if (Op0C && Op1C) {
3329       const APFloat &Op0 = Op0C->getValueAPF();
3330       const APFloat &Op1 = Op1C->getValueAPF();
3331 
3332       switch (Func) {
3333       case LibFunc_powl:
3334       case LibFunc_pow:
3335       case LibFunc_powf: {
3336         // FIXME: Stop using the host math library.
3337         // FIXME: The computation isn't done in the right precision.
3338         Type *Ty = Op0C->getType();
3339         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3340           if (Ty == Op1C->getType())
3341             return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
3342         }
3343         break;
3344       }
3345 
3346       case LibFunc_fmodl:
3347       case LibFunc_fmod:
3348       case LibFunc_fmodf:
3349       case LibFunc_remainderl:
3350       case LibFunc_remainder:
3351       case LibFunc_remainderf:
3352         return Op0.isNaN() || Op1.isNaN() ||
3353                (!Op0.isInfinity() && !Op1.isZero());
3354 
3355       default:
3356         break;
3357       }
3358     }
3359   }
3360 
3361   return false;
3362 }
3363 
3364 void TargetFolder::anchor() {}
3365