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     if (CE->isCompare())
1066       return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1067                                              DL, TLI);
1068     return CE->getWithOperands(Ops);
1069   }
1070 
1071   switch (Opcode) {
1072   default: return nullptr;
1073   case Instruction::ICmp:
1074   case Instruction::FCmp: {
1075     auto *C = cast<CmpInst>(InstOrCE);
1076     return ConstantFoldCompareInstOperands(C->getPredicate(), Ops[0], Ops[1],
1077                                            DL, TLI, C);
1078   }
1079   case Instruction::Freeze:
1080     return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1081   case Instruction::Call:
1082     if (auto *F = dyn_cast<Function>(Ops.back())) {
1083       const auto *Call = cast<CallBase>(InstOrCE);
1084       if (canConstantFoldCallTo(Call, F))
1085         return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
1086     }
1087     return nullptr;
1088   case Instruction::Select:
1089     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1090   case Instruction::ExtractElement:
1091     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1092   case Instruction::ExtractValue:
1093     return ConstantFoldExtractValueInstruction(
1094         Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1095   case Instruction::InsertElement:
1096     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1097   case Instruction::InsertValue:
1098     return ConstantFoldInsertValueInstruction(
1099         Ops[0], Ops[1], cast<InsertValueInst>(InstOrCE)->getIndices());
1100   case Instruction::ShuffleVector:
1101     return ConstantExpr::getShuffleVector(
1102         Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1103   case Instruction::Load: {
1104     const auto *LI = dyn_cast<LoadInst>(InstOrCE);
1105     if (LI->isVolatile())
1106       return nullptr;
1107     return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL);
1108   }
1109   }
1110 }
1111 
1112 } // end anonymous namespace
1113 
1114 //===----------------------------------------------------------------------===//
1115 // Constant Folding public APIs
1116 //===----------------------------------------------------------------------===//
1117 
1118 namespace {
1119 
1120 Constant *
1121 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1122                          const TargetLibraryInfo *TLI,
1123                          SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1124   if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1125     return const_cast<Constant *>(C);
1126 
1127   SmallVector<Constant *, 8> Ops;
1128   for (const Use &OldU : C->operands()) {
1129     Constant *OldC = cast<Constant>(&OldU);
1130     Constant *NewC = OldC;
1131     // Recursively fold the ConstantExpr's operands. If we have already folded
1132     // a ConstantExpr, we don't have to process it again.
1133     if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1134       auto It = FoldedOps.find(OldC);
1135       if (It == FoldedOps.end()) {
1136         NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1137         FoldedOps.insert({OldC, NewC});
1138       } else {
1139         NewC = It->second;
1140       }
1141     }
1142     Ops.push_back(NewC);
1143   }
1144 
1145   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1146     if (Constant *Res =
1147             ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI))
1148       return Res;
1149     return const_cast<Constant *>(C);
1150   }
1151 
1152   assert(isa<ConstantVector>(C));
1153   return ConstantVector::get(Ops);
1154 }
1155 
1156 } // end anonymous namespace
1157 
1158 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1159                                         const TargetLibraryInfo *TLI) {
1160   // Handle PHI nodes quickly here...
1161   if (auto *PN = dyn_cast<PHINode>(I)) {
1162     Constant *CommonValue = nullptr;
1163 
1164     SmallDenseMap<Constant *, Constant *> FoldedOps;
1165     for (Value *Incoming : PN->incoming_values()) {
1166       // If the incoming value is undef then skip it.  Note that while we could
1167       // skip the value if it is equal to the phi node itself we choose not to
1168       // because that would break the rule that constant folding only applies if
1169       // all operands are constants.
1170       if (isa<UndefValue>(Incoming))
1171         continue;
1172       // If the incoming value is not a constant, then give up.
1173       auto *C = dyn_cast<Constant>(Incoming);
1174       if (!C)
1175         return nullptr;
1176       // Fold the PHI's operands.
1177       C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1178       // If the incoming value is a different constant to
1179       // the one we saw previously, then give up.
1180       if (CommonValue && C != CommonValue)
1181         return nullptr;
1182       CommonValue = C;
1183     }
1184 
1185     // If we reach here, all incoming values are the same constant or undef.
1186     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1187   }
1188 
1189   // Scan the operand list, checking to see if they are all constants, if so,
1190   // hand off to ConstantFoldInstOperandsImpl.
1191   if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1192     return nullptr;
1193 
1194   SmallDenseMap<Constant *, Constant *> FoldedOps;
1195   SmallVector<Constant *, 8> Ops;
1196   for (const Use &OpU : I->operands()) {
1197     auto *Op = cast<Constant>(&OpU);
1198     // Fold the Instruction's operands.
1199     Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1200     Ops.push_back(Op);
1201   }
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(
1220     unsigned IntPredicate, Constant *Ops0, Constant *Ops1, const DataLayout &DL,
1221     const TargetLibraryInfo *TLI, const Instruction *I) {
1222   CmpInst::Predicate Predicate = (CmpInst::Predicate)IntPredicate;
1223   // fold: icmp (inttoptr x), null         -> icmp x, 0
1224   // fold: icmp null, (inttoptr x)         -> icmp 0, x
1225   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1226   // fold: icmp 0, (ptrtoint x)            -> icmp null, x
1227   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1228   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1229   //
1230   // FIXME: The following comment is out of data and the DataLayout is here now.
1231   // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1232   // around to know if bit truncation is happening.
1233   if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1234     if (Ops1->isNullValue()) {
1235       if (CE0->getOpcode() == Instruction::IntToPtr) {
1236         Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1237         // Convert the integer value to the right size to ensure we get the
1238         // proper extension or truncation.
1239         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1240                                                    IntPtrTy, false);
1241         Constant *Null = Constant::getNullValue(C->getType());
1242         return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1243       }
1244 
1245       // Only do this transformation if the int is intptrty in size, otherwise
1246       // there is a truncation or extension that we aren't modeling.
1247       if (CE0->getOpcode() == Instruction::PtrToInt) {
1248         Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1249         if (CE0->getType() == IntPtrTy) {
1250           Constant *C = CE0->getOperand(0);
1251           Constant *Null = Constant::getNullValue(C->getType());
1252           return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1253         }
1254       }
1255     }
1256 
1257     if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1258       if (CE0->getOpcode() == CE1->getOpcode()) {
1259         if (CE0->getOpcode() == Instruction::IntToPtr) {
1260           Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1261 
1262           // Convert the integer value to the right size to ensure we get the
1263           // proper extension or truncation.
1264           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1265                                                       IntPtrTy, false);
1266           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1267                                                       IntPtrTy, false);
1268           return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1269         }
1270 
1271         // Only do this transformation if the int is intptrty in size, otherwise
1272         // there is a truncation or extension that we aren't modeling.
1273         if (CE0->getOpcode() == Instruction::PtrToInt) {
1274           Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1275           if (CE0->getType() == IntPtrTy &&
1276               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1277             return ConstantFoldCompareInstOperands(
1278                 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1279           }
1280         }
1281       }
1282     }
1283 
1284     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1285     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1286     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1287         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1288       Constant *LHS = ConstantFoldCompareInstOperands(
1289           Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1290       Constant *RHS = ConstantFoldCompareInstOperands(
1291           Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1292       unsigned OpC =
1293         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1294       return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1295     }
1296 
1297     // Convert pointer comparison (base+offset1) pred (base+offset2) into
1298     // offset1 pred offset2, for the case where the offset is inbounds. This
1299     // only works for equality and unsigned comparison, as inbounds permits
1300     // crossing the sign boundary. However, the offset comparison itself is
1301     // signed.
1302     if (Ops0->getType()->isPointerTy() && !ICmpInst::isSigned(Predicate)) {
1303       unsigned IndexWidth = DL.getIndexTypeSizeInBits(Ops0->getType());
1304       APInt Offset0(IndexWidth, 0);
1305       Value *Stripped0 =
1306           Ops0->stripAndAccumulateInBoundsConstantOffsets(DL, Offset0);
1307       APInt Offset1(IndexWidth, 0);
1308       Value *Stripped1 =
1309           Ops1->stripAndAccumulateInBoundsConstantOffsets(DL, Offset1);
1310       if (Stripped0 == Stripped1)
1311         return ConstantExpr::getCompare(
1312             ICmpInst::getSignedPredicate(Predicate),
1313             ConstantInt::get(CE0->getContext(), Offset0),
1314             ConstantInt::get(CE0->getContext(), Offset1));
1315     }
1316   } else if (isa<ConstantExpr>(Ops1)) {
1317     // If RHS is a constant expression, but the left side isn't, swap the
1318     // operands and try again.
1319     Predicate = ICmpInst::getSwappedPredicate(Predicate);
1320     return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1321   }
1322 
1323   // Flush any denormal constant float input according to denormal handling
1324   // mode.
1325   Ops0 = FlushFPConstant(Ops0, I, /* IsOutput */ false);
1326   Ops1 = FlushFPConstant(Ops1, I, /* IsOutput */ false);
1327 
1328   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1329 }
1330 
1331 Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1332                                            const DataLayout &DL) {
1333   assert(Instruction::isUnaryOp(Opcode));
1334 
1335   return ConstantExpr::get(Opcode, Op);
1336 }
1337 
1338 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1339                                              Constant *RHS,
1340                                              const DataLayout &DL) {
1341   assert(Instruction::isBinaryOp(Opcode));
1342   if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1343     if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1344       return C;
1345 
1346   return ConstantExpr::get(Opcode, LHS, RHS);
1347 }
1348 
1349 Constant *llvm::FlushFPConstant(Constant *Operand, const Instruction *I,
1350                                 bool IsOutput) {
1351   if (!I || !I->getParent() || !I->getFunction())
1352     return Operand;
1353 
1354   ConstantFP *CFP = dyn_cast<ConstantFP>(Operand);
1355   if (!CFP)
1356     return Operand;
1357 
1358   const APFloat &APF = CFP->getValueAPF();
1359   Type *Ty = CFP->getType();
1360   DenormalMode DenormMode =
1361       I->getFunction()->getDenormalMode(Ty->getFltSemantics());
1362   DenormalMode::DenormalModeKind Mode =
1363       IsOutput ? DenormMode.Output : DenormMode.Input;
1364   switch (Mode) {
1365   default:
1366     llvm_unreachable("unknown denormal mode");
1367     return Operand;
1368   case DenormalMode::IEEE:
1369     return Operand;
1370   case DenormalMode::PreserveSign:
1371     if (APF.isDenormal()) {
1372       return ConstantFP::get(
1373           Ty->getContext(),
1374           APFloat::getZero(Ty->getFltSemantics(), APF.isNegative()));
1375     }
1376     return Operand;
1377   case DenormalMode::PositiveZero:
1378     if (APF.isDenormal()) {
1379       return ConstantFP::get(Ty->getContext(),
1380                              APFloat::getZero(Ty->getFltSemantics(), false));
1381     }
1382     return Operand;
1383   }
1384   return Operand;
1385 }
1386 
1387 Constant *llvm::ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS,
1388                                            Constant *RHS, const DataLayout &DL,
1389                                            const Instruction *I) {
1390   if (Instruction::isBinaryOp(Opcode)) {
1391     // Flush denormal inputs if needed.
1392     Constant *Op0 = FlushFPConstant(LHS, I, /* IsOutput */ false);
1393     Constant *Op1 = FlushFPConstant(RHS, I, /* IsOutput */ false);
1394 
1395     // Calculate constant result.
1396     Constant *C = ConstantFoldBinaryOpOperands(Opcode, Op0, Op1, DL);
1397 
1398     // Flush denormal output if needed.
1399     return FlushFPConstant(C, I, /* IsOutput */ true);
1400   }
1401   // If instruction lacks a parent/function and the denormal mode cannot be
1402   // determined, use the default (IEEE).
1403   return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
1404 }
1405 
1406 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1407                                         Type *DestTy, const DataLayout &DL) {
1408   assert(Instruction::isCast(Opcode));
1409   switch (Opcode) {
1410   default:
1411     llvm_unreachable("Missing case");
1412   case Instruction::PtrToInt:
1413     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1414       Constant *FoldedValue = nullptr;
1415       // If the input is a inttoptr, eliminate the pair.  This requires knowing
1416       // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1417       if (CE->getOpcode() == Instruction::IntToPtr) {
1418         // zext/trunc the inttoptr to pointer size.
1419         FoldedValue = ConstantExpr::getIntegerCast(
1420             CE->getOperand(0), DL.getIntPtrType(CE->getType()),
1421             /*IsSigned=*/false);
1422       } else if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
1423         // If we have GEP, we can perform the following folds:
1424         // (ptrtoint (gep null, x)) -> x
1425         // (ptrtoint (gep (gep null, x), y) -> x + y, etc.
1426         unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1427         APInt BaseOffset(BitWidth, 0);
1428         auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets(
1429             DL, BaseOffset, /*AllowNonInbounds=*/true));
1430         if (Base->isNullValue()) {
1431           FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset);
1432         } else {
1433           // ptrtoint (gep i8, Ptr, (sub 0, V)) -> sub (ptrtoint Ptr), V
1434           if (GEP->getNumIndices() == 1 &&
1435               GEP->getSourceElementType()->isIntegerTy(8)) {
1436             auto *Ptr = cast<Constant>(GEP->getPointerOperand());
1437             auto *Sub = dyn_cast<ConstantExpr>(GEP->getOperand(1));
1438             Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1439             if (Sub && Sub->getType() == IntIdxTy &&
1440                 Sub->getOpcode() == Instruction::Sub &&
1441                 Sub->getOperand(0)->isNullValue())
1442               FoldedValue = ConstantExpr::getSub(
1443                   ConstantExpr::getPtrToInt(Ptr, IntIdxTy), Sub->getOperand(1));
1444           }
1445         }
1446       }
1447       if (FoldedValue) {
1448         // Do a zext or trunc to get to the ptrtoint dest size.
1449         return ConstantExpr::getIntegerCast(FoldedValue, DestTy,
1450                                             /*IsSigned=*/false);
1451       }
1452     }
1453     return ConstantExpr::getCast(Opcode, C, DestTy);
1454   case Instruction::IntToPtr:
1455     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1456     // the int size is >= the ptr size and the address spaces are the same.
1457     // This requires knowing the width of a pointer, so it can't be done in
1458     // ConstantExpr::getCast.
1459     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1460       if (CE->getOpcode() == Instruction::PtrToInt) {
1461         Constant *SrcPtr = CE->getOperand(0);
1462         unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1463         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1464 
1465         if (MidIntSize >= SrcPtrSize) {
1466           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1467           if (SrcAS == DestTy->getPointerAddressSpace())
1468             return FoldBitCast(CE->getOperand(0), DestTy, DL);
1469         }
1470       }
1471     }
1472 
1473     return ConstantExpr::getCast(Opcode, C, DestTy);
1474   case Instruction::Trunc:
1475   case Instruction::ZExt:
1476   case Instruction::SExt:
1477   case Instruction::FPTrunc:
1478   case Instruction::FPExt:
1479   case Instruction::UIToFP:
1480   case Instruction::SIToFP:
1481   case Instruction::FPToUI:
1482   case Instruction::FPToSI:
1483   case Instruction::AddrSpaceCast:
1484       return ConstantExpr::getCast(Opcode, C, DestTy);
1485   case Instruction::BitCast:
1486     return FoldBitCast(C, DestTy, DL);
1487   }
1488 }
1489 
1490 //===----------------------------------------------------------------------===//
1491 //  Constant Folding for Calls
1492 //
1493 
1494 bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1495   if (Call->isNoBuiltin())
1496     return false;
1497   if (Call->getFunctionType() != F->getFunctionType())
1498     return false;
1499   switch (F->getIntrinsicID()) {
1500   // Operations that do not operate floating-point numbers and do not depend on
1501   // FP environment can be folded even in strictfp functions.
1502   case Intrinsic::bswap:
1503   case Intrinsic::ctpop:
1504   case Intrinsic::ctlz:
1505   case Intrinsic::cttz:
1506   case Intrinsic::fshl:
1507   case Intrinsic::fshr:
1508   case Intrinsic::launder_invariant_group:
1509   case Intrinsic::strip_invariant_group:
1510   case Intrinsic::masked_load:
1511   case Intrinsic::get_active_lane_mask:
1512   case Intrinsic::abs:
1513   case Intrinsic::smax:
1514   case Intrinsic::smin:
1515   case Intrinsic::umax:
1516   case Intrinsic::umin:
1517   case Intrinsic::sadd_with_overflow:
1518   case Intrinsic::uadd_with_overflow:
1519   case Intrinsic::ssub_with_overflow:
1520   case Intrinsic::usub_with_overflow:
1521   case Intrinsic::smul_with_overflow:
1522   case Intrinsic::umul_with_overflow:
1523   case Intrinsic::sadd_sat:
1524   case Intrinsic::uadd_sat:
1525   case Intrinsic::ssub_sat:
1526   case Intrinsic::usub_sat:
1527   case Intrinsic::smul_fix:
1528   case Intrinsic::smul_fix_sat:
1529   case Intrinsic::bitreverse:
1530   case Intrinsic::is_constant:
1531   case Intrinsic::vector_reduce_add:
1532   case Intrinsic::vector_reduce_mul:
1533   case Intrinsic::vector_reduce_and:
1534   case Intrinsic::vector_reduce_or:
1535   case Intrinsic::vector_reduce_xor:
1536   case Intrinsic::vector_reduce_smin:
1537   case Intrinsic::vector_reduce_smax:
1538   case Intrinsic::vector_reduce_umin:
1539   case Intrinsic::vector_reduce_umax:
1540   // Target intrinsics
1541   case Intrinsic::amdgcn_perm:
1542   case Intrinsic::arm_mve_vctp8:
1543   case Intrinsic::arm_mve_vctp16:
1544   case Intrinsic::arm_mve_vctp32:
1545   case Intrinsic::arm_mve_vctp64:
1546   case Intrinsic::aarch64_sve_convert_from_svbool:
1547   // WebAssembly float semantics are always known
1548   case Intrinsic::wasm_trunc_signed:
1549   case Intrinsic::wasm_trunc_unsigned:
1550     return true;
1551 
1552   // Floating point operations cannot be folded in strictfp functions in
1553   // general case. They can be folded if FP environment is known to compiler.
1554   case Intrinsic::minnum:
1555   case Intrinsic::maxnum:
1556   case Intrinsic::minimum:
1557   case Intrinsic::maximum:
1558   case Intrinsic::log:
1559   case Intrinsic::log2:
1560   case Intrinsic::log10:
1561   case Intrinsic::exp:
1562   case Intrinsic::exp2:
1563   case Intrinsic::sqrt:
1564   case Intrinsic::sin:
1565   case Intrinsic::cos:
1566   case Intrinsic::pow:
1567   case Intrinsic::powi:
1568   case Intrinsic::fma:
1569   case Intrinsic::fmuladd:
1570   case Intrinsic::fptoui_sat:
1571   case Intrinsic::fptosi_sat:
1572   case Intrinsic::convert_from_fp16:
1573   case Intrinsic::convert_to_fp16:
1574   case Intrinsic::amdgcn_cos:
1575   case Intrinsic::amdgcn_cubeid:
1576   case Intrinsic::amdgcn_cubema:
1577   case Intrinsic::amdgcn_cubesc:
1578   case Intrinsic::amdgcn_cubetc:
1579   case Intrinsic::amdgcn_fmul_legacy:
1580   case Intrinsic::amdgcn_fma_legacy:
1581   case Intrinsic::amdgcn_fract:
1582   case Intrinsic::amdgcn_ldexp:
1583   case Intrinsic::amdgcn_sin:
1584   // The intrinsics below depend on rounding mode in MXCSR.
1585   case Intrinsic::x86_sse_cvtss2si:
1586   case Intrinsic::x86_sse_cvtss2si64:
1587   case Intrinsic::x86_sse_cvttss2si:
1588   case Intrinsic::x86_sse_cvttss2si64:
1589   case Intrinsic::x86_sse2_cvtsd2si:
1590   case Intrinsic::x86_sse2_cvtsd2si64:
1591   case Intrinsic::x86_sse2_cvttsd2si:
1592   case Intrinsic::x86_sse2_cvttsd2si64:
1593   case Intrinsic::x86_avx512_vcvtss2si32:
1594   case Intrinsic::x86_avx512_vcvtss2si64:
1595   case Intrinsic::x86_avx512_cvttss2si:
1596   case Intrinsic::x86_avx512_cvttss2si64:
1597   case Intrinsic::x86_avx512_vcvtsd2si32:
1598   case Intrinsic::x86_avx512_vcvtsd2si64:
1599   case Intrinsic::x86_avx512_cvttsd2si:
1600   case Intrinsic::x86_avx512_cvttsd2si64:
1601   case Intrinsic::x86_avx512_vcvtss2usi32:
1602   case Intrinsic::x86_avx512_vcvtss2usi64:
1603   case Intrinsic::x86_avx512_cvttss2usi:
1604   case Intrinsic::x86_avx512_cvttss2usi64:
1605   case Intrinsic::x86_avx512_vcvtsd2usi32:
1606   case Intrinsic::x86_avx512_vcvtsd2usi64:
1607   case Intrinsic::x86_avx512_cvttsd2usi:
1608   case Intrinsic::x86_avx512_cvttsd2usi64:
1609     return !Call->isStrictFP();
1610 
1611   // Sign operations are actually bitwise operations, they do not raise
1612   // exceptions even for SNANs.
1613   case Intrinsic::fabs:
1614   case Intrinsic::copysign:
1615   // Non-constrained variants of rounding operations means default FP
1616   // environment, they can be folded in any case.
1617   case Intrinsic::ceil:
1618   case Intrinsic::floor:
1619   case Intrinsic::round:
1620   case Intrinsic::roundeven:
1621   case Intrinsic::trunc:
1622   case Intrinsic::nearbyint:
1623   case Intrinsic::rint:
1624   // Constrained intrinsics can be folded if FP environment is known
1625   // to compiler.
1626   case Intrinsic::experimental_constrained_fma:
1627   case Intrinsic::experimental_constrained_fmuladd:
1628   case Intrinsic::experimental_constrained_fadd:
1629   case Intrinsic::experimental_constrained_fsub:
1630   case Intrinsic::experimental_constrained_fmul:
1631   case Intrinsic::experimental_constrained_fdiv:
1632   case Intrinsic::experimental_constrained_frem:
1633   case Intrinsic::experimental_constrained_ceil:
1634   case Intrinsic::experimental_constrained_floor:
1635   case Intrinsic::experimental_constrained_round:
1636   case Intrinsic::experimental_constrained_roundeven:
1637   case Intrinsic::experimental_constrained_trunc:
1638   case Intrinsic::experimental_constrained_nearbyint:
1639   case Intrinsic::experimental_constrained_rint:
1640   case Intrinsic::experimental_constrained_fcmp:
1641   case Intrinsic::experimental_constrained_fcmps:
1642     return true;
1643   default:
1644     return false;
1645   case Intrinsic::not_intrinsic: break;
1646   }
1647 
1648   if (!F->hasName() || Call->isStrictFP())
1649     return false;
1650 
1651   // In these cases, the check of the length is required.  We don't want to
1652   // return true for a name like "cos\0blah" which strcmp would return equal to
1653   // "cos", but has length 8.
1654   StringRef Name = F->getName();
1655   switch (Name[0]) {
1656   default:
1657     return false;
1658   case 'a':
1659     return Name == "acos" || Name == "acosf" ||
1660            Name == "asin" || Name == "asinf" ||
1661            Name == "atan" || Name == "atanf" ||
1662            Name == "atan2" || Name == "atan2f";
1663   case 'c':
1664     return Name == "ceil" || Name == "ceilf" ||
1665            Name == "cos" || Name == "cosf" ||
1666            Name == "cosh" || Name == "coshf";
1667   case 'e':
1668     return Name == "exp" || Name == "expf" ||
1669            Name == "exp2" || Name == "exp2f";
1670   case 'f':
1671     return Name == "fabs" || Name == "fabsf" ||
1672            Name == "floor" || Name == "floorf" ||
1673            Name == "fmod" || Name == "fmodf";
1674   case 'l':
1675     return Name == "log" || Name == "logf" ||
1676            Name == "log2" || Name == "log2f" ||
1677            Name == "log10" || Name == "log10f";
1678   case 'n':
1679     return Name == "nearbyint" || Name == "nearbyintf";
1680   case 'p':
1681     return Name == "pow" || Name == "powf";
1682   case 'r':
1683     return Name == "remainder" || Name == "remainderf" ||
1684            Name == "rint" || Name == "rintf" ||
1685            Name == "round" || Name == "roundf";
1686   case 's':
1687     return Name == "sin" || Name == "sinf" ||
1688            Name == "sinh" || Name == "sinhf" ||
1689            Name == "sqrt" || Name == "sqrtf";
1690   case 't':
1691     return Name == "tan" || Name == "tanf" ||
1692            Name == "tanh" || Name == "tanhf" ||
1693            Name == "trunc" || Name == "truncf";
1694   case '_':
1695     // Check for various function names that get used for the math functions
1696     // when the header files are preprocessed with the macro
1697     // __FINITE_MATH_ONLY__ enabled.
1698     // The '12' here is the length of the shortest name that can match.
1699     // We need to check the size before looking at Name[1] and Name[2]
1700     // so we may as well check a limit that will eliminate mismatches.
1701     if (Name.size() < 12 || Name[1] != '_')
1702       return false;
1703     switch (Name[2]) {
1704     default:
1705       return false;
1706     case 'a':
1707       return Name == "__acos_finite" || Name == "__acosf_finite" ||
1708              Name == "__asin_finite" || Name == "__asinf_finite" ||
1709              Name == "__atan2_finite" || Name == "__atan2f_finite";
1710     case 'c':
1711       return Name == "__cosh_finite" || Name == "__coshf_finite";
1712     case 'e':
1713       return Name == "__exp_finite" || Name == "__expf_finite" ||
1714              Name == "__exp2_finite" || Name == "__exp2f_finite";
1715     case 'l':
1716       return Name == "__log_finite" || Name == "__logf_finite" ||
1717              Name == "__log10_finite" || Name == "__log10f_finite";
1718     case 'p':
1719       return Name == "__pow_finite" || Name == "__powf_finite";
1720     case 's':
1721       return Name == "__sinh_finite" || Name == "__sinhf_finite";
1722     }
1723   }
1724 }
1725 
1726 namespace {
1727 
1728 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1729   if (Ty->isHalfTy() || Ty->isFloatTy()) {
1730     APFloat APF(V);
1731     bool unused;
1732     APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1733     return ConstantFP::get(Ty->getContext(), APF);
1734   }
1735   if (Ty->isDoubleTy())
1736     return ConstantFP::get(Ty->getContext(), APFloat(V));
1737   llvm_unreachable("Can only constant fold half/float/double");
1738 }
1739 
1740 /// Clear the floating-point exception state.
1741 inline void llvm_fenv_clearexcept() {
1742 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1743   feclearexcept(FE_ALL_EXCEPT);
1744 #endif
1745   errno = 0;
1746 }
1747 
1748 /// Test if a floating-point exception was raised.
1749 inline bool llvm_fenv_testexcept() {
1750   int errno_val = errno;
1751   if (errno_val == ERANGE || errno_val == EDOM)
1752     return true;
1753 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1754   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1755     return true;
1756 #endif
1757   return false;
1758 }
1759 
1760 Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V,
1761                          Type *Ty) {
1762   llvm_fenv_clearexcept();
1763   double Result = NativeFP(V.convertToDouble());
1764   if (llvm_fenv_testexcept()) {
1765     llvm_fenv_clearexcept();
1766     return nullptr;
1767   }
1768 
1769   return GetConstantFoldFPValue(Result, Ty);
1770 }
1771 
1772 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1773                                const APFloat &V, const APFloat &W, Type *Ty) {
1774   llvm_fenv_clearexcept();
1775   double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
1776   if (llvm_fenv_testexcept()) {
1777     llvm_fenv_clearexcept();
1778     return nullptr;
1779   }
1780 
1781   return GetConstantFoldFPValue(Result, Ty);
1782 }
1783 
1784 Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1785   FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1786   if (!VT)
1787     return nullptr;
1788 
1789   // This isn't strictly necessary, but handle the special/common case of zero:
1790   // all integer reductions of a zero input produce zero.
1791   if (isa<ConstantAggregateZero>(Op))
1792     return ConstantInt::get(VT->getElementType(), 0);
1793 
1794   // This is the same as the underlying binops - poison propagates.
1795   if (isa<PoisonValue>(Op) || Op->containsPoisonElement())
1796     return PoisonValue::get(VT->getElementType());
1797 
1798   // TODO: Handle undef.
1799   if (!isa<ConstantVector>(Op) && !isa<ConstantDataVector>(Op))
1800     return nullptr;
1801 
1802   auto *EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1803   if (!EltC)
1804     return nullptr;
1805 
1806   APInt Acc = EltC->getValue();
1807   for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
1808     if (!(EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1809       return nullptr;
1810     const APInt &X = EltC->getValue();
1811     switch (IID) {
1812     case Intrinsic::vector_reduce_add:
1813       Acc = Acc + X;
1814       break;
1815     case Intrinsic::vector_reduce_mul:
1816       Acc = Acc * X;
1817       break;
1818     case Intrinsic::vector_reduce_and:
1819       Acc = Acc & X;
1820       break;
1821     case Intrinsic::vector_reduce_or:
1822       Acc = Acc | X;
1823       break;
1824     case Intrinsic::vector_reduce_xor:
1825       Acc = Acc ^ X;
1826       break;
1827     case Intrinsic::vector_reduce_smin:
1828       Acc = APIntOps::smin(Acc, X);
1829       break;
1830     case Intrinsic::vector_reduce_smax:
1831       Acc = APIntOps::smax(Acc, X);
1832       break;
1833     case Intrinsic::vector_reduce_umin:
1834       Acc = APIntOps::umin(Acc, X);
1835       break;
1836     case Intrinsic::vector_reduce_umax:
1837       Acc = APIntOps::umax(Acc, X);
1838       break;
1839     }
1840   }
1841 
1842   return ConstantInt::get(Op->getContext(), Acc);
1843 }
1844 
1845 /// Attempt to fold an SSE floating point to integer conversion of a constant
1846 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1847 /// used (toward nearest, ties to even). This matches the behavior of the
1848 /// non-truncating SSE instructions in the default rounding mode. The desired
1849 /// integer type Ty is used to select how many bits are available for the
1850 /// result. Returns null if the conversion cannot be performed, otherwise
1851 /// returns the Constant value resulting from the conversion.
1852 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1853                                       Type *Ty, bool IsSigned) {
1854   // All of these conversion intrinsics form an integer of at most 64bits.
1855   unsigned ResultWidth = Ty->getIntegerBitWidth();
1856   assert(ResultWidth <= 64 &&
1857          "Can only constant fold conversions to 64 and 32 bit ints");
1858 
1859   uint64_t UIntVal;
1860   bool isExact = false;
1861   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1862                                               : APFloat::rmNearestTiesToEven;
1863   APFloat::opStatus status =
1864       Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1865                            IsSigned, mode, &isExact);
1866   if (status != APFloat::opOK &&
1867       (!roundTowardZero || status != APFloat::opInexact))
1868     return nullptr;
1869   return ConstantInt::get(Ty, UIntVal, IsSigned);
1870 }
1871 
1872 double getValueAsDouble(ConstantFP *Op) {
1873   Type *Ty = Op->getType();
1874 
1875   if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
1876     return Op->getValueAPF().convertToDouble();
1877 
1878   bool unused;
1879   APFloat APF = Op->getValueAPF();
1880   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1881   return APF.convertToDouble();
1882 }
1883 
1884 static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1885   if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1886     C = &CI->getValue();
1887     return true;
1888   }
1889   if (isa<UndefValue>(Op)) {
1890     C = nullptr;
1891     return true;
1892   }
1893   return false;
1894 }
1895 
1896 /// Checks if the given intrinsic call, which evaluates to constant, is allowed
1897 /// to be folded.
1898 ///
1899 /// \param CI Constrained intrinsic call.
1900 /// \param St Exception flags raised during constant evaluation.
1901 static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
1902                                APFloat::opStatus St) {
1903   Optional<RoundingMode> ORM = CI->getRoundingMode();
1904   Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1905 
1906   // If the operation does not change exception status flags, it is safe
1907   // to fold.
1908   if (St == APFloat::opStatus::opOK)
1909     return true;
1910 
1911   // If evaluation raised FP exception, the result can depend on rounding
1912   // mode. If the latter is unknown, folding is not possible.
1913   if (ORM && *ORM == RoundingMode::Dynamic)
1914     return false;
1915 
1916   // If FP exceptions are ignored, fold the call, even if such exception is
1917   // raised.
1918   if (EB && *EB != fp::ExceptionBehavior::ebStrict)
1919     return true;
1920 
1921   // Leave the calculation for runtime so that exception flags be correctly set
1922   // in hardware.
1923   return false;
1924 }
1925 
1926 /// Returns the rounding mode that should be used for constant evaluation.
1927 static RoundingMode
1928 getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
1929   Optional<RoundingMode> ORM = CI->getRoundingMode();
1930   if (!ORM || *ORM == RoundingMode::Dynamic)
1931     // Even if the rounding mode is unknown, try evaluating the operation.
1932     // If it does not raise inexact exception, rounding was not applied,
1933     // so the result is exact and does not depend on rounding mode. Whether
1934     // other FP exceptions are raised, it does not depend on rounding mode.
1935     return RoundingMode::NearestTiesToEven;
1936   return *ORM;
1937 }
1938 
1939 static Constant *ConstantFoldScalarCall1(StringRef Name,
1940                                          Intrinsic::ID IntrinsicID,
1941                                          Type *Ty,
1942                                          ArrayRef<Constant *> Operands,
1943                                          const TargetLibraryInfo *TLI,
1944                                          const CallBase *Call) {
1945   assert(Operands.size() == 1 && "Wrong number of operands.");
1946 
1947   if (IntrinsicID == Intrinsic::is_constant) {
1948     // We know we have a "Constant" argument. But we want to only
1949     // return true for manifest constants, not those that depend on
1950     // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1951     if (Operands[0]->isManifestConstant())
1952       return ConstantInt::getTrue(Ty->getContext());
1953     return nullptr;
1954   }
1955   if (isa<UndefValue>(Operands[0])) {
1956     // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1957     // ctpop() is between 0 and bitwidth, pick 0 for undef.
1958     // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
1959     if (IntrinsicID == Intrinsic::cos ||
1960         IntrinsicID == Intrinsic::ctpop ||
1961         IntrinsicID == Intrinsic::fptoui_sat ||
1962         IntrinsicID == Intrinsic::fptosi_sat)
1963       return Constant::getNullValue(Ty);
1964     if (IntrinsicID == Intrinsic::bswap ||
1965         IntrinsicID == Intrinsic::bitreverse ||
1966         IntrinsicID == Intrinsic::launder_invariant_group ||
1967         IntrinsicID == Intrinsic::strip_invariant_group)
1968       return Operands[0];
1969   }
1970 
1971   if (isa<ConstantPointerNull>(Operands[0])) {
1972     // launder(null) == null == strip(null) iff in addrspace 0
1973     if (IntrinsicID == Intrinsic::launder_invariant_group ||
1974         IntrinsicID == Intrinsic::strip_invariant_group) {
1975       // If instruction is not yet put in a basic block (e.g. when cloning
1976       // a function during inlining), Call's caller may not be available.
1977       // So check Call's BB first before querying Call->getCaller.
1978       const Function *Caller =
1979           Call->getParent() ? Call->getCaller() : nullptr;
1980       if (Caller &&
1981           !NullPointerIsDefined(
1982               Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1983         return Operands[0];
1984       }
1985       return nullptr;
1986     }
1987   }
1988 
1989   if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1990     if (IntrinsicID == Intrinsic::convert_to_fp16) {
1991       APFloat Val(Op->getValueAPF());
1992 
1993       bool lost = false;
1994       Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1995 
1996       return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1997     }
1998 
1999     APFloat U = Op->getValueAPF();
2000 
2001     if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
2002         IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
2003       bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
2004 
2005       if (U.isNaN())
2006         return nullptr;
2007 
2008       unsigned Width = Ty->getIntegerBitWidth();
2009       APSInt Int(Width, !Signed);
2010       bool IsExact = false;
2011       APFloat::opStatus Status =
2012           U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2013 
2014       if (Status == APFloat::opOK || Status == APFloat::opInexact)
2015         return ConstantInt::get(Ty, Int);
2016 
2017       return nullptr;
2018     }
2019 
2020     if (IntrinsicID == Intrinsic::fptoui_sat ||
2021         IntrinsicID == Intrinsic::fptosi_sat) {
2022       // convertToInteger() already has the desired saturation semantics.
2023       APSInt Int(Ty->getIntegerBitWidth(),
2024                  IntrinsicID == Intrinsic::fptoui_sat);
2025       bool IsExact;
2026       U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2027       return ConstantInt::get(Ty, Int);
2028     }
2029 
2030     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2031       return nullptr;
2032 
2033     // Use internal versions of these intrinsics.
2034 
2035     if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
2036       U.roundToIntegral(APFloat::rmNearestTiesToEven);
2037       return ConstantFP::get(Ty->getContext(), U);
2038     }
2039 
2040     if (IntrinsicID == Intrinsic::round) {
2041       U.roundToIntegral(APFloat::rmNearestTiesToAway);
2042       return ConstantFP::get(Ty->getContext(), U);
2043     }
2044 
2045     if (IntrinsicID == Intrinsic::roundeven) {
2046       U.roundToIntegral(APFloat::rmNearestTiesToEven);
2047       return ConstantFP::get(Ty->getContext(), U);
2048     }
2049 
2050     if (IntrinsicID == Intrinsic::ceil) {
2051       U.roundToIntegral(APFloat::rmTowardPositive);
2052       return ConstantFP::get(Ty->getContext(), U);
2053     }
2054 
2055     if (IntrinsicID == Intrinsic::floor) {
2056       U.roundToIntegral(APFloat::rmTowardNegative);
2057       return ConstantFP::get(Ty->getContext(), U);
2058     }
2059 
2060     if (IntrinsicID == Intrinsic::trunc) {
2061       U.roundToIntegral(APFloat::rmTowardZero);
2062       return ConstantFP::get(Ty->getContext(), U);
2063     }
2064 
2065     if (IntrinsicID == Intrinsic::fabs) {
2066       U.clearSign();
2067       return ConstantFP::get(Ty->getContext(), U);
2068     }
2069 
2070     if (IntrinsicID == Intrinsic::amdgcn_fract) {
2071       // The v_fract instruction behaves like the OpenCL spec, which defines
2072       // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2073       //   there to prevent fract(-small) from returning 1.0. It returns the
2074       //   largest positive floating-point number less than 1.0."
2075       APFloat FloorU(U);
2076       FloorU.roundToIntegral(APFloat::rmTowardNegative);
2077       APFloat FractU(U - FloorU);
2078       APFloat AlmostOne(U.getSemantics(), 1);
2079       AlmostOne.next(/*nextDown*/ true);
2080       return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
2081     }
2082 
2083     // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2084     // raise FP exceptions, unless the argument is signaling NaN.
2085 
2086     Optional<APFloat::roundingMode> RM;
2087     switch (IntrinsicID) {
2088     default:
2089       break;
2090     case Intrinsic::experimental_constrained_nearbyint:
2091     case Intrinsic::experimental_constrained_rint: {
2092       auto CI = cast<ConstrainedFPIntrinsic>(Call);
2093       RM = CI->getRoundingMode();
2094       if (!RM || *RM == RoundingMode::Dynamic)
2095         return nullptr;
2096       break;
2097     }
2098     case Intrinsic::experimental_constrained_round:
2099       RM = APFloat::rmNearestTiesToAway;
2100       break;
2101     case Intrinsic::experimental_constrained_ceil:
2102       RM = APFloat::rmTowardPositive;
2103       break;
2104     case Intrinsic::experimental_constrained_floor:
2105       RM = APFloat::rmTowardNegative;
2106       break;
2107     case Intrinsic::experimental_constrained_trunc:
2108       RM = APFloat::rmTowardZero;
2109       break;
2110     }
2111     if (RM) {
2112       auto CI = cast<ConstrainedFPIntrinsic>(Call);
2113       if (U.isFinite()) {
2114         APFloat::opStatus St = U.roundToIntegral(*RM);
2115         if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2116             St == APFloat::opInexact) {
2117           Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2118           if (EB && *EB == fp::ebStrict)
2119             return nullptr;
2120         }
2121       } else if (U.isSignaling()) {
2122         Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2123         if (EB && *EB != fp::ebIgnore)
2124           return nullptr;
2125         U = APFloat::getQNaN(U.getSemantics());
2126       }
2127       return ConstantFP::get(Ty->getContext(), U);
2128     }
2129 
2130     /// We only fold functions with finite arguments. Folding NaN and inf is
2131     /// likely to be aborted with an exception anyway, and some host libms
2132     /// have known errors raising exceptions.
2133     if (!U.isFinite())
2134       return nullptr;
2135 
2136     /// Currently APFloat versions of these functions do not exist, so we use
2137     /// the host native double versions.  Float versions are not called
2138     /// directly but for all these it is true (float)(f((double)arg)) ==
2139     /// f(arg).  Long double not supported yet.
2140     const APFloat &APF = Op->getValueAPF();
2141 
2142     switch (IntrinsicID) {
2143       default: break;
2144       case Intrinsic::log:
2145         return ConstantFoldFP(log, APF, Ty);
2146       case Intrinsic::log2:
2147         // TODO: What about hosts that lack a C99 library?
2148         return ConstantFoldFP(Log2, APF, Ty);
2149       case Intrinsic::log10:
2150         // TODO: What about hosts that lack a C99 library?
2151         return ConstantFoldFP(log10, APF, Ty);
2152       case Intrinsic::exp:
2153         return ConstantFoldFP(exp, APF, Ty);
2154       case Intrinsic::exp2:
2155         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2156         return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2157       case Intrinsic::sin:
2158         return ConstantFoldFP(sin, APF, Ty);
2159       case Intrinsic::cos:
2160         return ConstantFoldFP(cos, APF, Ty);
2161       case Intrinsic::sqrt:
2162         return ConstantFoldFP(sqrt, APF, Ty);
2163       case Intrinsic::amdgcn_cos:
2164       case Intrinsic::amdgcn_sin: {
2165         double V = getValueAsDouble(Op);
2166         if (V < -256.0 || V > 256.0)
2167           // The gfx8 and gfx9 architectures handle arguments outside the range
2168           // [-256, 256] differently. This should be a rare case so bail out
2169           // rather than trying to handle the difference.
2170           return nullptr;
2171         bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2172         double V4 = V * 4.0;
2173         if (V4 == floor(V4)) {
2174           // Force exact results for quarter-integer inputs.
2175           const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2176           V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2177         } else {
2178           if (IsCos)
2179             V = cos(V * 2.0 * numbers::pi);
2180           else
2181             V = sin(V * 2.0 * numbers::pi);
2182         }
2183         return GetConstantFoldFPValue(V, Ty);
2184       }
2185     }
2186 
2187     if (!TLI)
2188       return nullptr;
2189 
2190     LibFunc Func = NotLibFunc;
2191     if (!TLI->getLibFunc(Name, Func))
2192       return nullptr;
2193 
2194     switch (Func) {
2195     default:
2196       break;
2197     case LibFunc_acos:
2198     case LibFunc_acosf:
2199     case LibFunc_acos_finite:
2200     case LibFunc_acosf_finite:
2201       if (TLI->has(Func))
2202         return ConstantFoldFP(acos, APF, Ty);
2203       break;
2204     case LibFunc_asin:
2205     case LibFunc_asinf:
2206     case LibFunc_asin_finite:
2207     case LibFunc_asinf_finite:
2208       if (TLI->has(Func))
2209         return ConstantFoldFP(asin, APF, Ty);
2210       break;
2211     case LibFunc_atan:
2212     case LibFunc_atanf:
2213       if (TLI->has(Func))
2214         return ConstantFoldFP(atan, APF, Ty);
2215       break;
2216     case LibFunc_ceil:
2217     case LibFunc_ceilf:
2218       if (TLI->has(Func)) {
2219         U.roundToIntegral(APFloat::rmTowardPositive);
2220         return ConstantFP::get(Ty->getContext(), U);
2221       }
2222       break;
2223     case LibFunc_cos:
2224     case LibFunc_cosf:
2225       if (TLI->has(Func))
2226         return ConstantFoldFP(cos, APF, Ty);
2227       break;
2228     case LibFunc_cosh:
2229     case LibFunc_coshf:
2230     case LibFunc_cosh_finite:
2231     case LibFunc_coshf_finite:
2232       if (TLI->has(Func))
2233         return ConstantFoldFP(cosh, APF, Ty);
2234       break;
2235     case LibFunc_exp:
2236     case LibFunc_expf:
2237     case LibFunc_exp_finite:
2238     case LibFunc_expf_finite:
2239       if (TLI->has(Func))
2240         return ConstantFoldFP(exp, APF, Ty);
2241       break;
2242     case LibFunc_exp2:
2243     case LibFunc_exp2f:
2244     case LibFunc_exp2_finite:
2245     case LibFunc_exp2f_finite:
2246       if (TLI->has(Func))
2247         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2248         return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2249       break;
2250     case LibFunc_fabs:
2251     case LibFunc_fabsf:
2252       if (TLI->has(Func)) {
2253         U.clearSign();
2254         return ConstantFP::get(Ty->getContext(), U);
2255       }
2256       break;
2257     case LibFunc_floor:
2258     case LibFunc_floorf:
2259       if (TLI->has(Func)) {
2260         U.roundToIntegral(APFloat::rmTowardNegative);
2261         return ConstantFP::get(Ty->getContext(), U);
2262       }
2263       break;
2264     case LibFunc_log:
2265     case LibFunc_logf:
2266     case LibFunc_log_finite:
2267     case LibFunc_logf_finite:
2268       if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2269         return ConstantFoldFP(log, APF, Ty);
2270       break;
2271     case LibFunc_log2:
2272     case LibFunc_log2f:
2273     case LibFunc_log2_finite:
2274     case LibFunc_log2f_finite:
2275       if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2276         // TODO: What about hosts that lack a C99 library?
2277         return ConstantFoldFP(Log2, APF, Ty);
2278       break;
2279     case LibFunc_log10:
2280     case LibFunc_log10f:
2281     case LibFunc_log10_finite:
2282     case LibFunc_log10f_finite:
2283       if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2284         // TODO: What about hosts that lack a C99 library?
2285         return ConstantFoldFP(log10, APF, Ty);
2286       break;
2287     case LibFunc_nearbyint:
2288     case LibFunc_nearbyintf:
2289     case LibFunc_rint:
2290     case LibFunc_rintf:
2291       if (TLI->has(Func)) {
2292         U.roundToIntegral(APFloat::rmNearestTiesToEven);
2293         return ConstantFP::get(Ty->getContext(), U);
2294       }
2295       break;
2296     case LibFunc_round:
2297     case LibFunc_roundf:
2298       if (TLI->has(Func)) {
2299         U.roundToIntegral(APFloat::rmNearestTiesToAway);
2300         return ConstantFP::get(Ty->getContext(), U);
2301       }
2302       break;
2303     case LibFunc_sin:
2304     case LibFunc_sinf:
2305       if (TLI->has(Func))
2306         return ConstantFoldFP(sin, APF, Ty);
2307       break;
2308     case LibFunc_sinh:
2309     case LibFunc_sinhf:
2310     case LibFunc_sinh_finite:
2311     case LibFunc_sinhf_finite:
2312       if (TLI->has(Func))
2313         return ConstantFoldFP(sinh, APF, Ty);
2314       break;
2315     case LibFunc_sqrt:
2316     case LibFunc_sqrtf:
2317       if (!APF.isNegative() && TLI->has(Func))
2318         return ConstantFoldFP(sqrt, APF, Ty);
2319       break;
2320     case LibFunc_tan:
2321     case LibFunc_tanf:
2322       if (TLI->has(Func))
2323         return ConstantFoldFP(tan, APF, Ty);
2324       break;
2325     case LibFunc_tanh:
2326     case LibFunc_tanhf:
2327       if (TLI->has(Func))
2328         return ConstantFoldFP(tanh, APF, Ty);
2329       break;
2330     case LibFunc_trunc:
2331     case LibFunc_truncf:
2332       if (TLI->has(Func)) {
2333         U.roundToIntegral(APFloat::rmTowardZero);
2334         return ConstantFP::get(Ty->getContext(), U);
2335       }
2336       break;
2337     }
2338     return nullptr;
2339   }
2340 
2341   if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2342     switch (IntrinsicID) {
2343     case Intrinsic::bswap:
2344       return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2345     case Intrinsic::ctpop:
2346       return ConstantInt::get(Ty, Op->getValue().countPopulation());
2347     case Intrinsic::bitreverse:
2348       return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2349     case Intrinsic::convert_from_fp16: {
2350       APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2351 
2352       bool lost = false;
2353       APFloat::opStatus status = Val.convert(
2354           Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2355 
2356       // Conversion is always precise.
2357       (void)status;
2358       assert(status == APFloat::opOK && !lost &&
2359              "Precision lost during fp16 constfolding");
2360 
2361       return ConstantFP::get(Ty->getContext(), Val);
2362     }
2363     default:
2364       return nullptr;
2365     }
2366   }
2367 
2368   switch (IntrinsicID) {
2369   default: break;
2370   case Intrinsic::vector_reduce_add:
2371   case Intrinsic::vector_reduce_mul:
2372   case Intrinsic::vector_reduce_and:
2373   case Intrinsic::vector_reduce_or:
2374   case Intrinsic::vector_reduce_xor:
2375   case Intrinsic::vector_reduce_smin:
2376   case Intrinsic::vector_reduce_smax:
2377   case Intrinsic::vector_reduce_umin:
2378   case Intrinsic::vector_reduce_umax:
2379     if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
2380       return C;
2381     break;
2382   }
2383 
2384   // Support ConstantVector in case we have an Undef in the top.
2385   if (isa<ConstantVector>(Operands[0]) ||
2386       isa<ConstantDataVector>(Operands[0])) {
2387     auto *Op = cast<Constant>(Operands[0]);
2388     switch (IntrinsicID) {
2389     default: break;
2390     case Intrinsic::x86_sse_cvtss2si:
2391     case Intrinsic::x86_sse_cvtss2si64:
2392     case Intrinsic::x86_sse2_cvtsd2si:
2393     case Intrinsic::x86_sse2_cvtsd2si64:
2394       if (ConstantFP *FPOp =
2395               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2396         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2397                                            /*roundTowardZero=*/false, Ty,
2398                                            /*IsSigned*/true);
2399       break;
2400     case Intrinsic::x86_sse_cvttss2si:
2401     case Intrinsic::x86_sse_cvttss2si64:
2402     case Intrinsic::x86_sse2_cvttsd2si:
2403     case Intrinsic::x86_sse2_cvttsd2si64:
2404       if (ConstantFP *FPOp =
2405               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2406         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2407                                            /*roundTowardZero=*/true, Ty,
2408                                            /*IsSigned*/true);
2409       break;
2410     }
2411   }
2412 
2413   return nullptr;
2414 }
2415 
2416 static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2,
2417                                  const ConstrainedFPIntrinsic *Call) {
2418   APFloat::opStatus St = APFloat::opOK;
2419   auto *FCmp = cast<ConstrainedFPCmpIntrinsic>(Call);
2420   FCmpInst::Predicate Cond = FCmp->getPredicate();
2421   if (FCmp->isSignaling()) {
2422     if (Op1.isNaN() || Op2.isNaN())
2423       St = APFloat::opInvalidOp;
2424   } else {
2425     if (Op1.isSignaling() || Op2.isSignaling())
2426       St = APFloat::opInvalidOp;
2427   }
2428   bool Result = FCmpInst::compare(Op1, Op2, Cond);
2429   if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St))
2430     return ConstantInt::get(Call->getType()->getScalarType(), Result);
2431   return nullptr;
2432 }
2433 
2434 static Constant *ConstantFoldScalarCall2(StringRef Name,
2435                                          Intrinsic::ID IntrinsicID,
2436                                          Type *Ty,
2437                                          ArrayRef<Constant *> Operands,
2438                                          const TargetLibraryInfo *TLI,
2439                                          const CallBase *Call) {
2440   assert(Operands.size() == 2 && "Wrong number of operands.");
2441 
2442   if (Ty->isFloatingPointTy()) {
2443     // TODO: We should have undef handling for all of the FP intrinsics that
2444     //       are attempted to be folded in this function.
2445     bool IsOp0Undef = isa<UndefValue>(Operands[0]);
2446     bool IsOp1Undef = isa<UndefValue>(Operands[1]);
2447     switch (IntrinsicID) {
2448     case Intrinsic::maxnum:
2449     case Intrinsic::minnum:
2450     case Intrinsic::maximum:
2451     case Intrinsic::minimum:
2452       // If one argument is undef, return the other argument.
2453       if (IsOp0Undef)
2454         return Operands[1];
2455       if (IsOp1Undef)
2456         return Operands[0];
2457       break;
2458     }
2459   }
2460 
2461   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2462     const APFloat &Op1V = Op1->getValueAPF();
2463 
2464     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2465       if (Op2->getType() != Op1->getType())
2466         return nullptr;
2467       const APFloat &Op2V = Op2->getValueAPF();
2468 
2469       if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2470         RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2471         APFloat Res = Op1V;
2472         APFloat::opStatus St;
2473         switch (IntrinsicID) {
2474         default:
2475           return nullptr;
2476         case Intrinsic::experimental_constrained_fadd:
2477           St = Res.add(Op2V, RM);
2478           break;
2479         case Intrinsic::experimental_constrained_fsub:
2480           St = Res.subtract(Op2V, RM);
2481           break;
2482         case Intrinsic::experimental_constrained_fmul:
2483           St = Res.multiply(Op2V, RM);
2484           break;
2485         case Intrinsic::experimental_constrained_fdiv:
2486           St = Res.divide(Op2V, RM);
2487           break;
2488         case Intrinsic::experimental_constrained_frem:
2489           St = Res.mod(Op2V);
2490           break;
2491         case Intrinsic::experimental_constrained_fcmp:
2492         case Intrinsic::experimental_constrained_fcmps:
2493           return evaluateCompare(Op1V, Op2V, ConstrIntr);
2494         }
2495         if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
2496                                St))
2497           return ConstantFP::get(Ty->getContext(), Res);
2498         return nullptr;
2499       }
2500 
2501       switch (IntrinsicID) {
2502       default:
2503         break;
2504       case Intrinsic::copysign:
2505         return ConstantFP::get(Ty->getContext(), APFloat::copySign(Op1V, Op2V));
2506       case Intrinsic::minnum:
2507         return ConstantFP::get(Ty->getContext(), minnum(Op1V, Op2V));
2508       case Intrinsic::maxnum:
2509         return ConstantFP::get(Ty->getContext(), maxnum(Op1V, Op2V));
2510       case Intrinsic::minimum:
2511         return ConstantFP::get(Ty->getContext(), minimum(Op1V, Op2V));
2512       case Intrinsic::maximum:
2513         return ConstantFP::get(Ty->getContext(), maximum(Op1V, Op2V));
2514       }
2515 
2516       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2517         return nullptr;
2518 
2519       switch (IntrinsicID) {
2520       default:
2521         break;
2522       case Intrinsic::pow:
2523         return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2524       case Intrinsic::amdgcn_fmul_legacy:
2525         // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2526         // NaN or infinity, gives +0.0.
2527         if (Op1V.isZero() || Op2V.isZero())
2528           return ConstantFP::getNullValue(Ty);
2529         return ConstantFP::get(Ty->getContext(), Op1V * Op2V);
2530       }
2531 
2532       if (!TLI)
2533         return nullptr;
2534 
2535       LibFunc Func = NotLibFunc;
2536       if (!TLI->getLibFunc(Name, Func))
2537         return nullptr;
2538 
2539       switch (Func) {
2540       default:
2541         break;
2542       case LibFunc_pow:
2543       case LibFunc_powf:
2544       case LibFunc_pow_finite:
2545       case LibFunc_powf_finite:
2546         if (TLI->has(Func))
2547           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2548         break;
2549       case LibFunc_fmod:
2550       case LibFunc_fmodf:
2551         if (TLI->has(Func)) {
2552           APFloat V = Op1->getValueAPF();
2553           if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2554             return ConstantFP::get(Ty->getContext(), V);
2555         }
2556         break;
2557       case LibFunc_remainder:
2558       case LibFunc_remainderf:
2559         if (TLI->has(Func)) {
2560           APFloat V = Op1->getValueAPF();
2561           if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2562             return ConstantFP::get(Ty->getContext(), V);
2563         }
2564         break;
2565       case LibFunc_atan2:
2566       case LibFunc_atan2f:
2567       case LibFunc_atan2_finite:
2568       case LibFunc_atan2f_finite:
2569         if (TLI->has(Func))
2570           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2571         break;
2572       }
2573     } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2574       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2575         return nullptr;
2576       if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2577         return ConstantFP::get(
2578             Ty->getContext(),
2579             APFloat((float)std::pow((float)Op1V.convertToDouble(),
2580                                     (int)Op2C->getZExtValue())));
2581       if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2582         return ConstantFP::get(
2583             Ty->getContext(),
2584             APFloat((float)std::pow((float)Op1V.convertToDouble(),
2585                                     (int)Op2C->getZExtValue())));
2586       if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2587         return ConstantFP::get(
2588             Ty->getContext(),
2589             APFloat((double)std::pow(Op1V.convertToDouble(),
2590                                      (int)Op2C->getZExtValue())));
2591 
2592       if (IntrinsicID == Intrinsic::amdgcn_ldexp) {
2593         // FIXME: Should flush denorms depending on FP mode, but that's ignored
2594         // everywhere else.
2595 
2596         // scalbn is equivalent to ldexp with float radix 2
2597         APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(),
2598                                 APFloat::rmNearestTiesToEven);
2599         return ConstantFP::get(Ty->getContext(), Result);
2600       }
2601     }
2602     return nullptr;
2603   }
2604 
2605   if (Operands[0]->getType()->isIntegerTy() &&
2606       Operands[1]->getType()->isIntegerTy()) {
2607     const APInt *C0, *C1;
2608     if (!getConstIntOrUndef(Operands[0], C0) ||
2609         !getConstIntOrUndef(Operands[1], C1))
2610       return nullptr;
2611 
2612     switch (IntrinsicID) {
2613     default: break;
2614     case Intrinsic::smax:
2615     case Intrinsic::smin:
2616     case Intrinsic::umax:
2617     case Intrinsic::umin:
2618       // This is the same as for binary ops - poison propagates.
2619       // TODO: Poison handling should be consolidated.
2620       if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2621         return PoisonValue::get(Ty);
2622 
2623       if (!C0 && !C1)
2624         return UndefValue::get(Ty);
2625       if (!C0 || !C1)
2626         return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty);
2627       return ConstantInt::get(
2628           Ty, ICmpInst::compare(*C0, *C1,
2629                                 MinMaxIntrinsic::getPredicate(IntrinsicID))
2630                   ? *C0
2631                   : *C1);
2632 
2633     case Intrinsic::usub_with_overflow:
2634     case Intrinsic::ssub_with_overflow:
2635       // X - undef -> { 0, false }
2636       // undef - X -> { 0, false }
2637       if (!C0 || !C1)
2638         return Constant::getNullValue(Ty);
2639       LLVM_FALLTHROUGH;
2640     case Intrinsic::uadd_with_overflow:
2641     case Intrinsic::sadd_with_overflow:
2642       // X + undef -> { -1, false }
2643       // undef + x -> { -1, false }
2644       if (!C0 || !C1) {
2645         return ConstantStruct::get(
2646             cast<StructType>(Ty),
2647             {Constant::getAllOnesValue(Ty->getStructElementType(0)),
2648              Constant::getNullValue(Ty->getStructElementType(1))});
2649       }
2650       LLVM_FALLTHROUGH;
2651     case Intrinsic::smul_with_overflow:
2652     case Intrinsic::umul_with_overflow: {
2653       // undef * X -> { 0, false }
2654       // X * undef -> { 0, false }
2655       if (!C0 || !C1)
2656         return Constant::getNullValue(Ty);
2657 
2658       APInt Res;
2659       bool Overflow;
2660       switch (IntrinsicID) {
2661       default: llvm_unreachable("Invalid case");
2662       case Intrinsic::sadd_with_overflow:
2663         Res = C0->sadd_ov(*C1, Overflow);
2664         break;
2665       case Intrinsic::uadd_with_overflow:
2666         Res = C0->uadd_ov(*C1, Overflow);
2667         break;
2668       case Intrinsic::ssub_with_overflow:
2669         Res = C0->ssub_ov(*C1, Overflow);
2670         break;
2671       case Intrinsic::usub_with_overflow:
2672         Res = C0->usub_ov(*C1, Overflow);
2673         break;
2674       case Intrinsic::smul_with_overflow:
2675         Res = C0->smul_ov(*C1, Overflow);
2676         break;
2677       case Intrinsic::umul_with_overflow:
2678         Res = C0->umul_ov(*C1, Overflow);
2679         break;
2680       }
2681       Constant *Ops[] = {
2682         ConstantInt::get(Ty->getContext(), Res),
2683         ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2684       };
2685       return ConstantStruct::get(cast<StructType>(Ty), Ops);
2686     }
2687     case Intrinsic::uadd_sat:
2688     case Intrinsic::sadd_sat:
2689       // This is the same as for binary ops - poison propagates.
2690       // TODO: Poison handling should be consolidated.
2691       if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2692         return PoisonValue::get(Ty);
2693 
2694       if (!C0 && !C1)
2695         return UndefValue::get(Ty);
2696       if (!C0 || !C1)
2697         return Constant::getAllOnesValue(Ty);
2698       if (IntrinsicID == Intrinsic::uadd_sat)
2699         return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2700       else
2701         return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2702     case Intrinsic::usub_sat:
2703     case Intrinsic::ssub_sat:
2704       // This is the same as for binary ops - poison propagates.
2705       // TODO: Poison handling should be consolidated.
2706       if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2707         return PoisonValue::get(Ty);
2708 
2709       if (!C0 && !C1)
2710         return UndefValue::get(Ty);
2711       if (!C0 || !C1)
2712         return Constant::getNullValue(Ty);
2713       if (IntrinsicID == Intrinsic::usub_sat)
2714         return ConstantInt::get(Ty, C0->usub_sat(*C1));
2715       else
2716         return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2717     case Intrinsic::cttz:
2718     case Intrinsic::ctlz:
2719       assert(C1 && "Must be constant int");
2720 
2721       // cttz(0, 1) and ctlz(0, 1) are poison.
2722       if (C1->isOne() && (!C0 || C0->isZero()))
2723         return PoisonValue::get(Ty);
2724       if (!C0)
2725         return Constant::getNullValue(Ty);
2726       if (IntrinsicID == Intrinsic::cttz)
2727         return ConstantInt::get(Ty, C0->countTrailingZeros());
2728       else
2729         return ConstantInt::get(Ty, C0->countLeadingZeros());
2730 
2731     case Intrinsic::abs:
2732       assert(C1 && "Must be constant int");
2733       assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1");
2734 
2735       // Undef or minimum val operand with poison min --> undef
2736       if (C1->isOne() && (!C0 || C0->isMinSignedValue()))
2737         return UndefValue::get(Ty);
2738 
2739       // Undef operand with no poison min --> 0 (sign bit must be clear)
2740       if (!C0)
2741         return Constant::getNullValue(Ty);
2742 
2743       return ConstantInt::get(Ty, C0->abs());
2744     }
2745 
2746     return nullptr;
2747   }
2748 
2749   // Support ConstantVector in case we have an Undef in the top.
2750   if ((isa<ConstantVector>(Operands[0]) ||
2751        isa<ConstantDataVector>(Operands[0])) &&
2752       // Check for default rounding mode.
2753       // FIXME: Support other rounding modes?
2754       isa<ConstantInt>(Operands[1]) &&
2755       cast<ConstantInt>(Operands[1])->getValue() == 4) {
2756     auto *Op = cast<Constant>(Operands[0]);
2757     switch (IntrinsicID) {
2758     default: break;
2759     case Intrinsic::x86_avx512_vcvtss2si32:
2760     case Intrinsic::x86_avx512_vcvtss2si64:
2761     case Intrinsic::x86_avx512_vcvtsd2si32:
2762     case Intrinsic::x86_avx512_vcvtsd2si64:
2763       if (ConstantFP *FPOp =
2764               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2765         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2766                                            /*roundTowardZero=*/false, Ty,
2767                                            /*IsSigned*/true);
2768       break;
2769     case Intrinsic::x86_avx512_vcvtss2usi32:
2770     case Intrinsic::x86_avx512_vcvtss2usi64:
2771     case Intrinsic::x86_avx512_vcvtsd2usi32:
2772     case Intrinsic::x86_avx512_vcvtsd2usi64:
2773       if (ConstantFP *FPOp =
2774               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2775         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2776                                            /*roundTowardZero=*/false, Ty,
2777                                            /*IsSigned*/false);
2778       break;
2779     case Intrinsic::x86_avx512_cvttss2si:
2780     case Intrinsic::x86_avx512_cvttss2si64:
2781     case Intrinsic::x86_avx512_cvttsd2si:
2782     case Intrinsic::x86_avx512_cvttsd2si64:
2783       if (ConstantFP *FPOp =
2784               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2785         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2786                                            /*roundTowardZero=*/true, Ty,
2787                                            /*IsSigned*/true);
2788       break;
2789     case Intrinsic::x86_avx512_cvttss2usi:
2790     case Intrinsic::x86_avx512_cvttss2usi64:
2791     case Intrinsic::x86_avx512_cvttsd2usi:
2792     case Intrinsic::x86_avx512_cvttsd2usi64:
2793       if (ConstantFP *FPOp =
2794               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2795         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2796                                            /*roundTowardZero=*/true, Ty,
2797                                            /*IsSigned*/false);
2798       break;
2799     }
2800   }
2801   return nullptr;
2802 }
2803 
2804 static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2805                                                const APFloat &S0,
2806                                                const APFloat &S1,
2807                                                const APFloat &S2) {
2808   unsigned ID;
2809   const fltSemantics &Sem = S0.getSemantics();
2810   APFloat MA(Sem), SC(Sem), TC(Sem);
2811   if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2812     if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2813       // S2 < 0
2814       ID = 5;
2815       SC = -S0;
2816     } else {
2817       ID = 4;
2818       SC = S0;
2819     }
2820     MA = S2;
2821     TC = -S1;
2822   } else if (abs(S1) >= abs(S0)) {
2823     if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2824       // S1 < 0
2825       ID = 3;
2826       TC = -S2;
2827     } else {
2828       ID = 2;
2829       TC = S2;
2830     }
2831     MA = S1;
2832     SC = S0;
2833   } else {
2834     if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2835       // S0 < 0
2836       ID = 1;
2837       SC = S2;
2838     } else {
2839       ID = 0;
2840       SC = -S2;
2841     }
2842     MA = S0;
2843     TC = -S1;
2844   }
2845   switch (IntrinsicID) {
2846   default:
2847     llvm_unreachable("unhandled amdgcn cube intrinsic");
2848   case Intrinsic::amdgcn_cubeid:
2849     return APFloat(Sem, ID);
2850   case Intrinsic::amdgcn_cubema:
2851     return MA + MA;
2852   case Intrinsic::amdgcn_cubesc:
2853     return SC;
2854   case Intrinsic::amdgcn_cubetc:
2855     return TC;
2856   }
2857 }
2858 
2859 static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
2860                                                  Type *Ty) {
2861   const APInt *C0, *C1, *C2;
2862   if (!getConstIntOrUndef(Operands[0], C0) ||
2863       !getConstIntOrUndef(Operands[1], C1) ||
2864       !getConstIntOrUndef(Operands[2], C2))
2865     return nullptr;
2866 
2867   if (!C2)
2868     return UndefValue::get(Ty);
2869 
2870   APInt Val(32, 0);
2871   unsigned NumUndefBytes = 0;
2872   for (unsigned I = 0; I < 32; I += 8) {
2873     unsigned Sel = C2->extractBitsAsZExtValue(8, I);
2874     unsigned B = 0;
2875 
2876     if (Sel >= 13)
2877       B = 0xff;
2878     else if (Sel == 12)
2879       B = 0x00;
2880     else {
2881       const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
2882       if (!Src)
2883         ++NumUndefBytes;
2884       else if (Sel < 8)
2885         B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
2886       else
2887         B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
2888     }
2889 
2890     Val.insertBits(B, I, 8);
2891   }
2892 
2893   if (NumUndefBytes == 4)
2894     return UndefValue::get(Ty);
2895 
2896   return ConstantInt::get(Ty, Val);
2897 }
2898 
2899 static Constant *ConstantFoldScalarCall3(StringRef Name,
2900                                          Intrinsic::ID IntrinsicID,
2901                                          Type *Ty,
2902                                          ArrayRef<Constant *> Operands,
2903                                          const TargetLibraryInfo *TLI,
2904                                          const CallBase *Call) {
2905   assert(Operands.size() == 3 && "Wrong number of operands.");
2906 
2907   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2908     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2909       if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2910         const APFloat &C1 = Op1->getValueAPF();
2911         const APFloat &C2 = Op2->getValueAPF();
2912         const APFloat &C3 = Op3->getValueAPF();
2913 
2914         if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2915           RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2916           APFloat Res = C1;
2917           APFloat::opStatus St;
2918           switch (IntrinsicID) {
2919           default:
2920             return nullptr;
2921           case Intrinsic::experimental_constrained_fma:
2922           case Intrinsic::experimental_constrained_fmuladd:
2923             St = Res.fusedMultiplyAdd(C2, C3, RM);
2924             break;
2925           }
2926           if (mayFoldConstrained(
2927                   const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
2928             return ConstantFP::get(Ty->getContext(), Res);
2929           return nullptr;
2930         }
2931 
2932         switch (IntrinsicID) {
2933         default: break;
2934         case Intrinsic::amdgcn_fma_legacy: {
2935           // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2936           // NaN or infinity, gives +0.0.
2937           if (C1.isZero() || C2.isZero()) {
2938             // It's tempting to just return C3 here, but that would give the
2939             // wrong result if C3 was -0.0.
2940             return ConstantFP::get(Ty->getContext(), APFloat(0.0f) + C3);
2941           }
2942           LLVM_FALLTHROUGH;
2943         }
2944         case Intrinsic::fma:
2945         case Intrinsic::fmuladd: {
2946           APFloat V = C1;
2947           V.fusedMultiplyAdd(C2, C3, APFloat::rmNearestTiesToEven);
2948           return ConstantFP::get(Ty->getContext(), V);
2949         }
2950         case Intrinsic::amdgcn_cubeid:
2951         case Intrinsic::amdgcn_cubema:
2952         case Intrinsic::amdgcn_cubesc:
2953         case Intrinsic::amdgcn_cubetc: {
2954           APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
2955           return ConstantFP::get(Ty->getContext(), V);
2956         }
2957         }
2958       }
2959     }
2960   }
2961 
2962   if (IntrinsicID == Intrinsic::smul_fix ||
2963       IntrinsicID == Intrinsic::smul_fix_sat) {
2964     // poison * C -> poison
2965     // C * poison -> poison
2966     if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2967       return PoisonValue::get(Ty);
2968 
2969     const APInt *C0, *C1;
2970     if (!getConstIntOrUndef(Operands[0], C0) ||
2971         !getConstIntOrUndef(Operands[1], C1))
2972       return nullptr;
2973 
2974     // undef * C -> 0
2975     // C * undef -> 0
2976     if (!C0 || !C1)
2977       return Constant::getNullValue(Ty);
2978 
2979     // This code performs rounding towards negative infinity in case the result
2980     // cannot be represented exactly for the given scale. Targets that do care
2981     // about rounding should use a target hook for specifying how rounding
2982     // should be done, and provide their own folding to be consistent with
2983     // rounding. This is the same approach as used by
2984     // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2985     unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
2986     unsigned Width = C0->getBitWidth();
2987     assert(Scale < Width && "Illegal scale.");
2988     unsigned ExtendedWidth = Width * 2;
2989     APInt Product =
2990         (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale);
2991     if (IntrinsicID == Intrinsic::smul_fix_sat) {
2992       APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth);
2993       APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth);
2994       Product = APIntOps::smin(Product, Max);
2995       Product = APIntOps::smax(Product, Min);
2996     }
2997     return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
2998   }
2999 
3000   if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
3001     const APInt *C0, *C1, *C2;
3002     if (!getConstIntOrUndef(Operands[0], C0) ||
3003         !getConstIntOrUndef(Operands[1], C1) ||
3004         !getConstIntOrUndef(Operands[2], C2))
3005       return nullptr;
3006 
3007     bool IsRight = IntrinsicID == Intrinsic::fshr;
3008     if (!C2)
3009       return Operands[IsRight ? 1 : 0];
3010     if (!C0 && !C1)
3011       return UndefValue::get(Ty);
3012 
3013     // The shift amount is interpreted as modulo the bitwidth. If the shift
3014     // amount is effectively 0, avoid UB due to oversized inverse shift below.
3015     unsigned BitWidth = C2->getBitWidth();
3016     unsigned ShAmt = C2->urem(BitWidth);
3017     if (!ShAmt)
3018       return Operands[IsRight ? 1 : 0];
3019 
3020     // (C0 << ShlAmt) | (C1 >> LshrAmt)
3021     unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
3022     unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
3023     if (!C0)
3024       return ConstantInt::get(Ty, C1->lshr(LshrAmt));
3025     if (!C1)
3026       return ConstantInt::get(Ty, C0->shl(ShlAmt));
3027     return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
3028   }
3029 
3030   if (IntrinsicID == Intrinsic::amdgcn_perm)
3031     return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
3032 
3033   return nullptr;
3034 }
3035 
3036 static Constant *ConstantFoldScalarCall(StringRef Name,
3037                                         Intrinsic::ID IntrinsicID,
3038                                         Type *Ty,
3039                                         ArrayRef<Constant *> Operands,
3040                                         const TargetLibraryInfo *TLI,
3041                                         const CallBase *Call) {
3042   if (Operands.size() == 1)
3043     return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
3044 
3045   if (Operands.size() == 2)
3046     return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
3047 
3048   if (Operands.size() == 3)
3049     return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
3050 
3051   return nullptr;
3052 }
3053 
3054 static Constant *ConstantFoldFixedVectorCall(
3055     StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
3056     ArrayRef<Constant *> Operands, const DataLayout &DL,
3057     const TargetLibraryInfo *TLI, const CallBase *Call) {
3058   SmallVector<Constant *, 4> Result(FVTy->getNumElements());
3059   SmallVector<Constant *, 4> Lane(Operands.size());
3060   Type *Ty = FVTy->getElementType();
3061 
3062   switch (IntrinsicID) {
3063   case Intrinsic::masked_load: {
3064     auto *SrcPtr = Operands[0];
3065     auto *Mask = Operands[2];
3066     auto *Passthru = Operands[3];
3067 
3068     Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
3069 
3070     SmallVector<Constant *, 32> NewElements;
3071     for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3072       auto *MaskElt = Mask->getAggregateElement(I);
3073       if (!MaskElt)
3074         break;
3075       auto *PassthruElt = Passthru->getAggregateElement(I);
3076       auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
3077       if (isa<UndefValue>(MaskElt)) {
3078         if (PassthruElt)
3079           NewElements.push_back(PassthruElt);
3080         else if (VecElt)
3081           NewElements.push_back(VecElt);
3082         else
3083           return nullptr;
3084       }
3085       if (MaskElt->isNullValue()) {
3086         if (!PassthruElt)
3087           return nullptr;
3088         NewElements.push_back(PassthruElt);
3089       } else if (MaskElt->isOneValue()) {
3090         if (!VecElt)
3091           return nullptr;
3092         NewElements.push_back(VecElt);
3093       } else {
3094         return nullptr;
3095       }
3096     }
3097     if (NewElements.size() != FVTy->getNumElements())
3098       return nullptr;
3099     return ConstantVector::get(NewElements);
3100   }
3101   case Intrinsic::arm_mve_vctp8:
3102   case Intrinsic::arm_mve_vctp16:
3103   case Intrinsic::arm_mve_vctp32:
3104   case Intrinsic::arm_mve_vctp64: {
3105     if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3106       unsigned Lanes = FVTy->getNumElements();
3107       uint64_t Limit = Op->getZExtValue();
3108 
3109       SmallVector<Constant *, 16> NCs;
3110       for (unsigned i = 0; i < Lanes; i++) {
3111         if (i < Limit)
3112           NCs.push_back(ConstantInt::getTrue(Ty));
3113         else
3114           NCs.push_back(ConstantInt::getFalse(Ty));
3115       }
3116       return ConstantVector::get(NCs);
3117     }
3118     break;
3119   }
3120   case Intrinsic::get_active_lane_mask: {
3121     auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
3122     auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
3123     if (Op0 && Op1) {
3124       unsigned Lanes = FVTy->getNumElements();
3125       uint64_t Base = Op0->getZExtValue();
3126       uint64_t Limit = Op1->getZExtValue();
3127 
3128       SmallVector<Constant *, 16> NCs;
3129       for (unsigned i = 0; i < Lanes; i++) {
3130         if (Base + i < Limit)
3131           NCs.push_back(ConstantInt::getTrue(Ty));
3132         else
3133           NCs.push_back(ConstantInt::getFalse(Ty));
3134       }
3135       return ConstantVector::get(NCs);
3136     }
3137     break;
3138   }
3139   default:
3140     break;
3141   }
3142 
3143   for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3144     // Gather a column of constants.
3145     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
3146       // Some intrinsics use a scalar type for certain arguments.
3147       if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J)) {
3148         Lane[J] = Operands[J];
3149         continue;
3150       }
3151 
3152       Constant *Agg = Operands[J]->getAggregateElement(I);
3153       if (!Agg)
3154         return nullptr;
3155 
3156       Lane[J] = Agg;
3157     }
3158 
3159     // Use the regular scalar folding to simplify this column.
3160     Constant *Folded =
3161         ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
3162     if (!Folded)
3163       return nullptr;
3164     Result[I] = Folded;
3165   }
3166 
3167   return ConstantVector::get(Result);
3168 }
3169 
3170 static Constant *ConstantFoldScalableVectorCall(
3171     StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
3172     ArrayRef<Constant *> Operands, const DataLayout &DL,
3173     const TargetLibraryInfo *TLI, const CallBase *Call) {
3174   switch (IntrinsicID) {
3175   case Intrinsic::aarch64_sve_convert_from_svbool: {
3176     auto *Src = dyn_cast<Constant>(Operands[0]);
3177     if (!Src || !Src->isNullValue())
3178       break;
3179 
3180     return ConstantInt::getFalse(SVTy);
3181   }
3182   default:
3183     break;
3184   }
3185   return nullptr;
3186 }
3187 
3188 } // end anonymous namespace
3189 
3190 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
3191                                  ArrayRef<Constant *> Operands,
3192                                  const TargetLibraryInfo *TLI) {
3193   if (Call->isNoBuiltin())
3194     return nullptr;
3195   if (!F->hasName())
3196     return nullptr;
3197 
3198   // If this is not an intrinsic and not recognized as a library call, bail out.
3199   if (F->getIntrinsicID() == Intrinsic::not_intrinsic) {
3200     if (!TLI)
3201       return nullptr;
3202     LibFunc LibF;
3203     if (!TLI->getLibFunc(*F, LibF))
3204       return nullptr;
3205   }
3206 
3207   StringRef Name = F->getName();
3208   Type *Ty = F->getReturnType();
3209   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
3210     return ConstantFoldFixedVectorCall(
3211         Name, F->getIntrinsicID(), FVTy, Operands,
3212         F->getParent()->getDataLayout(), TLI, Call);
3213 
3214   if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
3215     return ConstantFoldScalableVectorCall(
3216         Name, F->getIntrinsicID(), SVTy, Operands,
3217         F->getParent()->getDataLayout(), TLI, Call);
3218 
3219   // TODO: If this is a library function, we already discovered that above,
3220   //       so we should pass the LibFunc, not the name (and it might be better
3221   //       still to separate intrinsic handling from libcalls).
3222   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
3223                                 Call);
3224 }
3225 
3226 bool llvm::isMathLibCallNoop(const CallBase *Call,
3227                              const TargetLibraryInfo *TLI) {
3228   // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
3229   // (and to some extent ConstantFoldScalarCall).
3230   if (Call->isNoBuiltin() || Call->isStrictFP())
3231     return false;
3232   Function *F = Call->getCalledFunction();
3233   if (!F)
3234     return false;
3235 
3236   LibFunc Func;
3237   if (!TLI || !TLI->getLibFunc(*F, Func))
3238     return false;
3239 
3240   if (Call->arg_size() == 1) {
3241     if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
3242       const APFloat &Op = OpC->getValueAPF();
3243       switch (Func) {
3244       case LibFunc_logl:
3245       case LibFunc_log:
3246       case LibFunc_logf:
3247       case LibFunc_log2l:
3248       case LibFunc_log2:
3249       case LibFunc_log2f:
3250       case LibFunc_log10l:
3251       case LibFunc_log10:
3252       case LibFunc_log10f:
3253         return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
3254 
3255       case LibFunc_expl:
3256       case LibFunc_exp:
3257       case LibFunc_expf:
3258         // FIXME: These boundaries are slightly conservative.
3259         if (OpC->getType()->isDoubleTy())
3260           return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
3261         if (OpC->getType()->isFloatTy())
3262           return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
3263         break;
3264 
3265       case LibFunc_exp2l:
3266       case LibFunc_exp2:
3267       case LibFunc_exp2f:
3268         // FIXME: These boundaries are slightly conservative.
3269         if (OpC->getType()->isDoubleTy())
3270           return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
3271         if (OpC->getType()->isFloatTy())
3272           return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
3273         break;
3274 
3275       case LibFunc_sinl:
3276       case LibFunc_sin:
3277       case LibFunc_sinf:
3278       case LibFunc_cosl:
3279       case LibFunc_cos:
3280       case LibFunc_cosf:
3281         return !Op.isInfinity();
3282 
3283       case LibFunc_tanl:
3284       case LibFunc_tan:
3285       case LibFunc_tanf: {
3286         // FIXME: Stop using the host math library.
3287         // FIXME: The computation isn't done in the right precision.
3288         Type *Ty = OpC->getType();
3289         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
3290           return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
3291         break;
3292       }
3293 
3294       case LibFunc_asinl:
3295       case LibFunc_asin:
3296       case LibFunc_asinf:
3297       case LibFunc_acosl:
3298       case LibFunc_acos:
3299       case LibFunc_acosf:
3300         return !(Op < APFloat(Op.getSemantics(), "-1") ||
3301                  Op > APFloat(Op.getSemantics(), "1"));
3302 
3303       case LibFunc_sinh:
3304       case LibFunc_cosh:
3305       case LibFunc_sinhf:
3306       case LibFunc_coshf:
3307       case LibFunc_sinhl:
3308       case LibFunc_coshl:
3309         // FIXME: These boundaries are slightly conservative.
3310         if (OpC->getType()->isDoubleTy())
3311           return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3312         if (OpC->getType()->isFloatTy())
3313           return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3314         break;
3315 
3316       case LibFunc_sqrtl:
3317       case LibFunc_sqrt:
3318       case LibFunc_sqrtf:
3319         return Op.isNaN() || Op.isZero() || !Op.isNegative();
3320 
3321       // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3322       // maybe others?
3323       default:
3324         break;
3325       }
3326     }
3327   }
3328 
3329   if (Call->arg_size() == 2) {
3330     ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3331     ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3332     if (Op0C && Op1C) {
3333       const APFloat &Op0 = Op0C->getValueAPF();
3334       const APFloat &Op1 = Op1C->getValueAPF();
3335 
3336       switch (Func) {
3337       case LibFunc_powl:
3338       case LibFunc_pow:
3339       case LibFunc_powf: {
3340         // FIXME: Stop using the host math library.
3341         // FIXME: The computation isn't done in the right precision.
3342         Type *Ty = Op0C->getType();
3343         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3344           if (Ty == Op1C->getType())
3345             return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
3346         }
3347         break;
3348       }
3349 
3350       case LibFunc_fmodl:
3351       case LibFunc_fmod:
3352       case LibFunc_fmodf:
3353       case LibFunc_remainderl:
3354       case LibFunc_remainder:
3355       case LibFunc_remainderf:
3356         return Op0.isNaN() || Op1.isNaN() ||
3357                (!Op0.isInfinity() && !Op1.isZero());
3358 
3359       default:
3360         break;
3361       }
3362     }
3363   }
3364 
3365   return false;
3366 }
3367 
3368 void TargetFolder::anchor() {}
3369