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