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