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