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