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