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::experimental_vector_reduce_add:
1461   case Intrinsic::experimental_vector_reduce_mul:
1462   case Intrinsic::experimental_vector_reduce_and:
1463   case Intrinsic::experimental_vector_reduce_or:
1464   case Intrinsic::experimental_vector_reduce_xor:
1465   case Intrinsic::experimental_vector_reduce_smin:
1466   case Intrinsic::experimental_vector_reduce_smax:
1467   case Intrinsic::experimental_vector_reduce_umin:
1468   case Intrinsic::experimental_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_fract:
1508   case Intrinsic::amdgcn_ldexp:
1509   case Intrinsic::amdgcn_sin:
1510   // The intrinsics below depend on rounding mode in MXCSR.
1511   case Intrinsic::x86_sse_cvtss2si:
1512   case Intrinsic::x86_sse_cvtss2si64:
1513   case Intrinsic::x86_sse_cvttss2si:
1514   case Intrinsic::x86_sse_cvttss2si64:
1515   case Intrinsic::x86_sse2_cvtsd2si:
1516   case Intrinsic::x86_sse2_cvtsd2si64:
1517   case Intrinsic::x86_sse2_cvttsd2si:
1518   case Intrinsic::x86_sse2_cvttsd2si64:
1519   case Intrinsic::x86_avx512_vcvtss2si32:
1520   case Intrinsic::x86_avx512_vcvtss2si64:
1521   case Intrinsic::x86_avx512_cvttss2si:
1522   case Intrinsic::x86_avx512_cvttss2si64:
1523   case Intrinsic::x86_avx512_vcvtsd2si32:
1524   case Intrinsic::x86_avx512_vcvtsd2si64:
1525   case Intrinsic::x86_avx512_cvttsd2si:
1526   case Intrinsic::x86_avx512_cvttsd2si64:
1527   case Intrinsic::x86_avx512_vcvtss2usi32:
1528   case Intrinsic::x86_avx512_vcvtss2usi64:
1529   case Intrinsic::x86_avx512_cvttss2usi:
1530   case Intrinsic::x86_avx512_cvttss2usi64:
1531   case Intrinsic::x86_avx512_vcvtsd2usi32:
1532   case Intrinsic::x86_avx512_vcvtsd2usi64:
1533   case Intrinsic::x86_avx512_cvttsd2usi:
1534   case Intrinsic::x86_avx512_cvttsd2usi64:
1535     return !Call->isStrictFP();
1536 
1537   // Sign operations are actually bitwise operations, they do not raise
1538   // exceptions even for SNANs.
1539   case Intrinsic::fabs:
1540   case Intrinsic::copysign:
1541   // Non-constrained variants of rounding operations means default FP
1542   // environment, they can be folded in any case.
1543   case Intrinsic::ceil:
1544   case Intrinsic::floor:
1545   case Intrinsic::round:
1546   case Intrinsic::roundeven:
1547   case Intrinsic::trunc:
1548   case Intrinsic::nearbyint:
1549   case Intrinsic::rint:
1550   // Constrained intrinsics can be folded if FP environment is known
1551   // to compiler.
1552   case Intrinsic::experimental_constrained_ceil:
1553   case Intrinsic::experimental_constrained_floor:
1554   case Intrinsic::experimental_constrained_round:
1555   case Intrinsic::experimental_constrained_roundeven:
1556   case Intrinsic::experimental_constrained_trunc:
1557   case Intrinsic::experimental_constrained_nearbyint:
1558   case Intrinsic::experimental_constrained_rint:
1559     return true;
1560   default:
1561     return false;
1562   case Intrinsic::not_intrinsic: break;
1563   }
1564 
1565   if (!F->hasName() || Call->isStrictFP())
1566     return false;
1567 
1568   // In these cases, the check of the length is required.  We don't want to
1569   // return true for a name like "cos\0blah" which strcmp would return equal to
1570   // "cos", but has length 8.
1571   StringRef Name = F->getName();
1572   switch (Name[0]) {
1573   default:
1574     return false;
1575   case 'a':
1576     return Name == "acos" || Name == "acosf" ||
1577            Name == "asin" || Name == "asinf" ||
1578            Name == "atan" || Name == "atanf" ||
1579            Name == "atan2" || Name == "atan2f";
1580   case 'c':
1581     return Name == "ceil" || Name == "ceilf" ||
1582            Name == "cos" || Name == "cosf" ||
1583            Name == "cosh" || Name == "coshf";
1584   case 'e':
1585     return Name == "exp" || Name == "expf" ||
1586            Name == "exp2" || Name == "exp2f";
1587   case 'f':
1588     return Name == "fabs" || Name == "fabsf" ||
1589            Name == "floor" || Name == "floorf" ||
1590            Name == "fmod" || Name == "fmodf";
1591   case 'l':
1592     return Name == "log" || Name == "logf" ||
1593            Name == "log2" || Name == "log2f" ||
1594            Name == "log10" || Name == "log10f";
1595   case 'n':
1596     return Name == "nearbyint" || Name == "nearbyintf";
1597   case 'p':
1598     return Name == "pow" || Name == "powf";
1599   case 'r':
1600     return Name == "remainder" || Name == "remainderf" ||
1601            Name == "rint" || Name == "rintf" ||
1602            Name == "round" || Name == "roundf";
1603   case 's':
1604     return Name == "sin" || Name == "sinf" ||
1605            Name == "sinh" || Name == "sinhf" ||
1606            Name == "sqrt" || Name == "sqrtf";
1607   case 't':
1608     return Name == "tan" || Name == "tanf" ||
1609            Name == "tanh" || Name == "tanhf" ||
1610            Name == "trunc" || Name == "truncf";
1611   case '_':
1612     // Check for various function names that get used for the math functions
1613     // when the header files are preprocessed with the macro
1614     // __FINITE_MATH_ONLY__ enabled.
1615     // The '12' here is the length of the shortest name that can match.
1616     // We need to check the size before looking at Name[1] and Name[2]
1617     // so we may as well check a limit that will eliminate mismatches.
1618     if (Name.size() < 12 || Name[1] != '_')
1619       return false;
1620     switch (Name[2]) {
1621     default:
1622       return false;
1623     case 'a':
1624       return Name == "__acos_finite" || Name == "__acosf_finite" ||
1625              Name == "__asin_finite" || Name == "__asinf_finite" ||
1626              Name == "__atan2_finite" || Name == "__atan2f_finite";
1627     case 'c':
1628       return Name == "__cosh_finite" || Name == "__coshf_finite";
1629     case 'e':
1630       return Name == "__exp_finite" || Name == "__expf_finite" ||
1631              Name == "__exp2_finite" || Name == "__exp2f_finite";
1632     case 'l':
1633       return Name == "__log_finite" || Name == "__logf_finite" ||
1634              Name == "__log10_finite" || Name == "__log10f_finite";
1635     case 'p':
1636       return Name == "__pow_finite" || Name == "__powf_finite";
1637     case 's':
1638       return Name == "__sinh_finite" || Name == "__sinhf_finite";
1639     }
1640   }
1641 }
1642 
1643 namespace {
1644 
1645 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1646   if (Ty->isHalfTy() || Ty->isFloatTy()) {
1647     APFloat APF(V);
1648     bool unused;
1649     APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1650     return ConstantFP::get(Ty->getContext(), APF);
1651   }
1652   if (Ty->isDoubleTy())
1653     return ConstantFP::get(Ty->getContext(), APFloat(V));
1654   llvm_unreachable("Can only constant fold half/float/double");
1655 }
1656 
1657 /// Clear the floating-point exception state.
1658 inline void llvm_fenv_clearexcept() {
1659 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1660   feclearexcept(FE_ALL_EXCEPT);
1661 #endif
1662   errno = 0;
1663 }
1664 
1665 /// Test if a floating-point exception was raised.
1666 inline bool llvm_fenv_testexcept() {
1667   int errno_val = errno;
1668   if (errno_val == ERANGE || errno_val == EDOM)
1669     return true;
1670 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1671   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1672     return true;
1673 #endif
1674   return false;
1675 }
1676 
1677 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1678   llvm_fenv_clearexcept();
1679   V = NativeFP(V);
1680   if (llvm_fenv_testexcept()) {
1681     llvm_fenv_clearexcept();
1682     return nullptr;
1683   }
1684 
1685   return GetConstantFoldFPValue(V, Ty);
1686 }
1687 
1688 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1689                                double W, Type *Ty) {
1690   llvm_fenv_clearexcept();
1691   V = NativeFP(V, W);
1692   if (llvm_fenv_testexcept()) {
1693     llvm_fenv_clearexcept();
1694     return nullptr;
1695   }
1696 
1697   return GetConstantFoldFPValue(V, Ty);
1698 }
1699 
1700 Constant *ConstantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1701   FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1702   if (!VT)
1703     return nullptr;
1704   ConstantInt *CI = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1705   if (!CI)
1706     return nullptr;
1707   APInt Acc = CI->getValue();
1708 
1709   for (unsigned I = 1; I < VT->getNumElements(); I++) {
1710     if (!(CI = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1711       return nullptr;
1712     const APInt &X = CI->getValue();
1713     switch (IID) {
1714     case Intrinsic::experimental_vector_reduce_add:
1715       Acc = Acc + X;
1716       break;
1717     case Intrinsic::experimental_vector_reduce_mul:
1718       Acc = Acc * X;
1719       break;
1720     case Intrinsic::experimental_vector_reduce_and:
1721       Acc = Acc & X;
1722       break;
1723     case Intrinsic::experimental_vector_reduce_or:
1724       Acc = Acc | X;
1725       break;
1726     case Intrinsic::experimental_vector_reduce_xor:
1727       Acc = Acc ^ X;
1728       break;
1729     case Intrinsic::experimental_vector_reduce_smin:
1730       Acc = APIntOps::smin(Acc, X);
1731       break;
1732     case Intrinsic::experimental_vector_reduce_smax:
1733       Acc = APIntOps::smax(Acc, X);
1734       break;
1735     case Intrinsic::experimental_vector_reduce_umin:
1736       Acc = APIntOps::umin(Acc, X);
1737       break;
1738     case Intrinsic::experimental_vector_reduce_umax:
1739       Acc = APIntOps::umax(Acc, X);
1740       break;
1741     }
1742   }
1743 
1744   return ConstantInt::get(Op->getContext(), Acc);
1745 }
1746 
1747 /// Attempt to fold an SSE floating point to integer conversion of a constant
1748 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1749 /// used (toward nearest, ties to even). This matches the behavior of the
1750 /// non-truncating SSE instructions in the default rounding mode. The desired
1751 /// integer type Ty is used to select how many bits are available for the
1752 /// result. Returns null if the conversion cannot be performed, otherwise
1753 /// returns the Constant value resulting from the conversion.
1754 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1755                                       Type *Ty, bool IsSigned) {
1756   // All of these conversion intrinsics form an integer of at most 64bits.
1757   unsigned ResultWidth = Ty->getIntegerBitWidth();
1758   assert(ResultWidth <= 64 &&
1759          "Can only constant fold conversions to 64 and 32 bit ints");
1760 
1761   uint64_t UIntVal;
1762   bool isExact = false;
1763   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1764                                               : APFloat::rmNearestTiesToEven;
1765   APFloat::opStatus status =
1766       Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1767                            IsSigned, mode, &isExact);
1768   if (status != APFloat::opOK &&
1769       (!roundTowardZero || status != APFloat::opInexact))
1770     return nullptr;
1771   return ConstantInt::get(Ty, UIntVal, IsSigned);
1772 }
1773 
1774 double getValueAsDouble(ConstantFP *Op) {
1775   Type *Ty = Op->getType();
1776 
1777   if (Ty->isFloatTy())
1778     return Op->getValueAPF().convertToFloat();
1779 
1780   if (Ty->isDoubleTy())
1781     return Op->getValueAPF().convertToDouble();
1782 
1783   bool unused;
1784   APFloat APF = Op->getValueAPF();
1785   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1786   return APF.convertToDouble();
1787 }
1788 
1789 static bool isManifestConstant(const Constant *c) {
1790   if (isa<ConstantData>(c)) {
1791     return true;
1792   } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1793     for (const Value *subc : c->operand_values()) {
1794       if (!isManifestConstant(cast<Constant>(subc)))
1795         return false;
1796     }
1797     return true;
1798   }
1799   return false;
1800 }
1801 
1802 static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1803   if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1804     C = &CI->getValue();
1805     return true;
1806   }
1807   if (isa<UndefValue>(Op)) {
1808     C = nullptr;
1809     return true;
1810   }
1811   return false;
1812 }
1813 
1814 static Constant *ConstantFoldScalarCall1(StringRef Name,
1815                                          Intrinsic::ID IntrinsicID,
1816                                          Type *Ty,
1817                                          ArrayRef<Constant *> Operands,
1818                                          const TargetLibraryInfo *TLI,
1819                                          const CallBase *Call) {
1820   assert(Operands.size() == 1 && "Wrong number of operands.");
1821 
1822   if (IntrinsicID == Intrinsic::is_constant) {
1823     // We know we have a "Constant" argument. But we want to only
1824     // return true for manifest constants, not those that depend on
1825     // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1826     if (isManifestConstant(Operands[0]))
1827       return ConstantInt::getTrue(Ty->getContext());
1828     return nullptr;
1829   }
1830   if (isa<UndefValue>(Operands[0])) {
1831     // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1832     // ctpop() is between 0 and bitwidth, pick 0 for undef.
1833     if (IntrinsicID == Intrinsic::cos ||
1834         IntrinsicID == Intrinsic::ctpop)
1835       return Constant::getNullValue(Ty);
1836     if (IntrinsicID == Intrinsic::bswap ||
1837         IntrinsicID == Intrinsic::bitreverse ||
1838         IntrinsicID == Intrinsic::launder_invariant_group ||
1839         IntrinsicID == Intrinsic::strip_invariant_group)
1840       return Operands[0];
1841   }
1842 
1843   if (isa<ConstantPointerNull>(Operands[0])) {
1844     // launder(null) == null == strip(null) iff in addrspace 0
1845     if (IntrinsicID == Intrinsic::launder_invariant_group ||
1846         IntrinsicID == Intrinsic::strip_invariant_group) {
1847       // If instruction is not yet put in a basic block (e.g. when cloning
1848       // a function during inlining), Call's caller may not be available.
1849       // So check Call's BB first before querying Call->getCaller.
1850       const Function *Caller =
1851           Call->getParent() ? Call->getCaller() : nullptr;
1852       if (Caller &&
1853           !NullPointerIsDefined(
1854               Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1855         return Operands[0];
1856       }
1857       return nullptr;
1858     }
1859   }
1860 
1861   if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1862     if (IntrinsicID == Intrinsic::convert_to_fp16) {
1863       APFloat Val(Op->getValueAPF());
1864 
1865       bool lost = false;
1866       Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1867 
1868       return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1869     }
1870 
1871     APFloat U = Op->getValueAPF();
1872 
1873     if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
1874         IntrinsicID == Intrinsic::wasm_trunc_unsigned ||
1875         IntrinsicID == Intrinsic::wasm_trunc_saturate_signed ||
1876         IntrinsicID == Intrinsic::wasm_trunc_saturate_unsigned) {
1877 
1878       bool Saturating = IntrinsicID == Intrinsic::wasm_trunc_saturate_signed ||
1879                         IntrinsicID == Intrinsic::wasm_trunc_saturate_unsigned;
1880       bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed ||
1881                     IntrinsicID == Intrinsic::wasm_trunc_saturate_signed;
1882 
1883       if (U.isNaN())
1884         return Saturating ? ConstantInt::get(Ty, 0) : nullptr;
1885 
1886       unsigned Width = Ty->getIntegerBitWidth();
1887       APSInt Int(Width, !Signed);
1888       bool IsExact = false;
1889       APFloat::opStatus Status =
1890           U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
1891 
1892       if (Status == APFloat::opOK || Status == APFloat::opInexact)
1893         return ConstantInt::get(Ty, Int);
1894 
1895       if (!Saturating)
1896         return nullptr;
1897 
1898       if (U.isNegative())
1899         return Signed ? ConstantInt::get(Ty, APInt::getSignedMinValue(Width))
1900                       : ConstantInt::get(Ty, APInt::getMinValue(Width));
1901       else
1902         return Signed ? ConstantInt::get(Ty, APInt::getSignedMaxValue(Width))
1903                       : ConstantInt::get(Ty, APInt::getMaxValue(Width));
1904     }
1905 
1906     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1907       return nullptr;
1908 
1909     // Use internal versions of these intrinsics.
1910 
1911     if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
1912       U.roundToIntegral(APFloat::rmNearestTiesToEven);
1913       return ConstantFP::get(Ty->getContext(), U);
1914     }
1915 
1916     if (IntrinsicID == Intrinsic::round) {
1917       U.roundToIntegral(APFloat::rmNearestTiesToAway);
1918       return ConstantFP::get(Ty->getContext(), U);
1919     }
1920 
1921     if (IntrinsicID == Intrinsic::roundeven) {
1922       U.roundToIntegral(APFloat::rmNearestTiesToEven);
1923       return ConstantFP::get(Ty->getContext(), U);
1924     }
1925 
1926     if (IntrinsicID == Intrinsic::ceil) {
1927       U.roundToIntegral(APFloat::rmTowardPositive);
1928       return ConstantFP::get(Ty->getContext(), U);
1929     }
1930 
1931     if (IntrinsicID == Intrinsic::floor) {
1932       U.roundToIntegral(APFloat::rmTowardNegative);
1933       return ConstantFP::get(Ty->getContext(), U);
1934     }
1935 
1936     if (IntrinsicID == Intrinsic::trunc) {
1937       U.roundToIntegral(APFloat::rmTowardZero);
1938       return ConstantFP::get(Ty->getContext(), U);
1939     }
1940 
1941     if (IntrinsicID == Intrinsic::fabs) {
1942       U.clearSign();
1943       return ConstantFP::get(Ty->getContext(), U);
1944     }
1945 
1946     if (IntrinsicID == Intrinsic::amdgcn_fract) {
1947       // The v_fract instruction behaves like the OpenCL spec, which defines
1948       // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
1949       //   there to prevent fract(-small) from returning 1.0. It returns the
1950       //   largest positive floating-point number less than 1.0."
1951       APFloat FloorU(U);
1952       FloorU.roundToIntegral(APFloat::rmTowardNegative);
1953       APFloat FractU(U - FloorU);
1954       APFloat AlmostOne(U.getSemantics(), 1);
1955       AlmostOne.next(/*nextDown*/ true);
1956       return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
1957     }
1958 
1959     // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
1960     // raise FP exceptions, unless the argument is signaling NaN.
1961 
1962     Optional<APFloat::roundingMode> RM;
1963     switch (IntrinsicID) {
1964     default:
1965       break;
1966     case Intrinsic::experimental_constrained_nearbyint:
1967     case Intrinsic::experimental_constrained_rint: {
1968       auto CI = cast<ConstrainedFPIntrinsic>(Call);
1969       RM = CI->getRoundingMode();
1970       if (!RM || RM.getValue() == RoundingMode::Dynamic)
1971         return nullptr;
1972       break;
1973     }
1974     case Intrinsic::experimental_constrained_round:
1975       RM = APFloat::rmNearestTiesToAway;
1976       break;
1977     case Intrinsic::experimental_constrained_ceil:
1978       RM = APFloat::rmTowardPositive;
1979       break;
1980     case Intrinsic::experimental_constrained_floor:
1981       RM = APFloat::rmTowardNegative;
1982       break;
1983     case Intrinsic::experimental_constrained_trunc:
1984       RM = APFloat::rmTowardZero;
1985       break;
1986     }
1987     if (RM) {
1988       auto CI = cast<ConstrainedFPIntrinsic>(Call);
1989       if (U.isFinite()) {
1990         APFloat::opStatus St = U.roundToIntegral(*RM);
1991         if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
1992             St == APFloat::opInexact) {
1993           Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1994           if (EB && *EB == fp::ebStrict)
1995             return nullptr;
1996         }
1997       } else if (U.isSignaling()) {
1998         Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1999         if (EB && *EB != fp::ebIgnore)
2000           return nullptr;
2001         U = APFloat::getQNaN(U.getSemantics());
2002       }
2003       return ConstantFP::get(Ty->getContext(), U);
2004     }
2005 
2006     /// We only fold functions with finite arguments. Folding NaN and inf is
2007     /// likely to be aborted with an exception anyway, and some host libms
2008     /// have known errors raising exceptions.
2009     if (!U.isFinite())
2010       return nullptr;
2011 
2012     /// Currently APFloat versions of these functions do not exist, so we use
2013     /// the host native double versions.  Float versions are not called
2014     /// directly but for all these it is true (float)(f((double)arg)) ==
2015     /// f(arg).  Long double not supported yet.
2016     double V = getValueAsDouble(Op);
2017 
2018     switch (IntrinsicID) {
2019       default: break;
2020       case Intrinsic::log:
2021         return ConstantFoldFP(log, V, Ty);
2022       case Intrinsic::log2:
2023         // TODO: What about hosts that lack a C99 library?
2024         return ConstantFoldFP(Log2, V, Ty);
2025       case Intrinsic::log10:
2026         // TODO: What about hosts that lack a C99 library?
2027         return ConstantFoldFP(log10, V, Ty);
2028       case Intrinsic::exp:
2029         return ConstantFoldFP(exp, V, Ty);
2030       case Intrinsic::exp2:
2031         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2032         return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
2033       case Intrinsic::sin:
2034         return ConstantFoldFP(sin, V, Ty);
2035       case Intrinsic::cos:
2036         return ConstantFoldFP(cos, V, Ty);
2037       case Intrinsic::sqrt:
2038         return ConstantFoldFP(sqrt, V, Ty);
2039       case Intrinsic::amdgcn_cos:
2040       case Intrinsic::amdgcn_sin:
2041         if (V < -256.0 || V > 256.0)
2042           // The gfx8 and gfx9 architectures handle arguments outside the range
2043           // [-256, 256] differently. This should be a rare case so bail out
2044           // rather than trying to handle the difference.
2045           return nullptr;
2046         bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2047         double V4 = V * 4.0;
2048         if (V4 == floor(V4)) {
2049           // Force exact results for quarter-integer inputs.
2050           const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2051           V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2052         } else {
2053           if (IsCos)
2054             V = cos(V * 2.0 * numbers::pi);
2055           else
2056             V = sin(V * 2.0 * numbers::pi);
2057         }
2058         return GetConstantFoldFPValue(V, Ty);
2059     }
2060 
2061     if (!TLI)
2062       return nullptr;
2063 
2064     LibFunc Func = NotLibFunc;
2065     TLI->getLibFunc(Name, Func);
2066     switch (Func) {
2067     default:
2068       break;
2069     case LibFunc_acos:
2070     case LibFunc_acosf:
2071     case LibFunc_acos_finite:
2072     case LibFunc_acosf_finite:
2073       if (TLI->has(Func))
2074         return ConstantFoldFP(acos, V, Ty);
2075       break;
2076     case LibFunc_asin:
2077     case LibFunc_asinf:
2078     case LibFunc_asin_finite:
2079     case LibFunc_asinf_finite:
2080       if (TLI->has(Func))
2081         return ConstantFoldFP(asin, V, Ty);
2082       break;
2083     case LibFunc_atan:
2084     case LibFunc_atanf:
2085       if (TLI->has(Func))
2086         return ConstantFoldFP(atan, V, Ty);
2087       break;
2088     case LibFunc_ceil:
2089     case LibFunc_ceilf:
2090       if (TLI->has(Func)) {
2091         U.roundToIntegral(APFloat::rmTowardPositive);
2092         return ConstantFP::get(Ty->getContext(), U);
2093       }
2094       break;
2095     case LibFunc_cos:
2096     case LibFunc_cosf:
2097       if (TLI->has(Func))
2098         return ConstantFoldFP(cos, V, Ty);
2099       break;
2100     case LibFunc_cosh:
2101     case LibFunc_coshf:
2102     case LibFunc_cosh_finite:
2103     case LibFunc_coshf_finite:
2104       if (TLI->has(Func))
2105         return ConstantFoldFP(cosh, V, Ty);
2106       break;
2107     case LibFunc_exp:
2108     case LibFunc_expf:
2109     case LibFunc_exp_finite:
2110     case LibFunc_expf_finite:
2111       if (TLI->has(Func))
2112         return ConstantFoldFP(exp, V, Ty);
2113       break;
2114     case LibFunc_exp2:
2115     case LibFunc_exp2f:
2116     case LibFunc_exp2_finite:
2117     case LibFunc_exp2f_finite:
2118       if (TLI->has(Func))
2119         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2120         return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
2121       break;
2122     case LibFunc_fabs:
2123     case LibFunc_fabsf:
2124       if (TLI->has(Func)) {
2125         U.clearSign();
2126         return ConstantFP::get(Ty->getContext(), U);
2127       }
2128       break;
2129     case LibFunc_floor:
2130     case LibFunc_floorf:
2131       if (TLI->has(Func)) {
2132         U.roundToIntegral(APFloat::rmTowardNegative);
2133         return ConstantFP::get(Ty->getContext(), U);
2134       }
2135       break;
2136     case LibFunc_log:
2137     case LibFunc_logf:
2138     case LibFunc_log_finite:
2139     case LibFunc_logf_finite:
2140       if (V > 0.0 && TLI->has(Func))
2141         return ConstantFoldFP(log, V, Ty);
2142       break;
2143     case LibFunc_log2:
2144     case LibFunc_log2f:
2145     case LibFunc_log2_finite:
2146     case LibFunc_log2f_finite:
2147       if (V > 0.0 && TLI->has(Func))
2148         // TODO: What about hosts that lack a C99 library?
2149         return ConstantFoldFP(Log2, V, Ty);
2150       break;
2151     case LibFunc_log10:
2152     case LibFunc_log10f:
2153     case LibFunc_log10_finite:
2154     case LibFunc_log10f_finite:
2155       if (V > 0.0 && TLI->has(Func))
2156         // TODO: What about hosts that lack a C99 library?
2157         return ConstantFoldFP(log10, V, Ty);
2158       break;
2159     case LibFunc_nearbyint:
2160     case LibFunc_nearbyintf:
2161     case LibFunc_rint:
2162     case LibFunc_rintf:
2163       if (TLI->has(Func)) {
2164         U.roundToIntegral(APFloat::rmNearestTiesToEven);
2165         return ConstantFP::get(Ty->getContext(), U);
2166       }
2167       break;
2168     case LibFunc_round:
2169     case LibFunc_roundf:
2170       if (TLI->has(Func)) {
2171         U.roundToIntegral(APFloat::rmNearestTiesToAway);
2172         return ConstantFP::get(Ty->getContext(), U);
2173       }
2174       break;
2175     case LibFunc_sin:
2176     case LibFunc_sinf:
2177       if (TLI->has(Func))
2178         return ConstantFoldFP(sin, V, Ty);
2179       break;
2180     case LibFunc_sinh:
2181     case LibFunc_sinhf:
2182     case LibFunc_sinh_finite:
2183     case LibFunc_sinhf_finite:
2184       if (TLI->has(Func))
2185         return ConstantFoldFP(sinh, V, Ty);
2186       break;
2187     case LibFunc_sqrt:
2188     case LibFunc_sqrtf:
2189       if (V >= 0.0 && TLI->has(Func))
2190         return ConstantFoldFP(sqrt, V, Ty);
2191       break;
2192     case LibFunc_tan:
2193     case LibFunc_tanf:
2194       if (TLI->has(Func))
2195         return ConstantFoldFP(tan, V, Ty);
2196       break;
2197     case LibFunc_tanh:
2198     case LibFunc_tanhf:
2199       if (TLI->has(Func))
2200         return ConstantFoldFP(tanh, V, Ty);
2201       break;
2202     case LibFunc_trunc:
2203     case LibFunc_truncf:
2204       if (TLI->has(Func)) {
2205         U.roundToIntegral(APFloat::rmTowardZero);
2206         return ConstantFP::get(Ty->getContext(), U);
2207       }
2208       break;
2209     }
2210     return nullptr;
2211   }
2212 
2213   if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2214     switch (IntrinsicID) {
2215     case Intrinsic::bswap:
2216       return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2217     case Intrinsic::ctpop:
2218       return ConstantInt::get(Ty, Op->getValue().countPopulation());
2219     case Intrinsic::bitreverse:
2220       return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2221     case Intrinsic::convert_from_fp16: {
2222       APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2223 
2224       bool lost = false;
2225       APFloat::opStatus status = Val.convert(
2226           Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2227 
2228       // Conversion is always precise.
2229       (void)status;
2230       assert(status == APFloat::opOK && !lost &&
2231              "Precision lost during fp16 constfolding");
2232 
2233       return ConstantFP::get(Ty->getContext(), Val);
2234     }
2235     default:
2236       return nullptr;
2237     }
2238   }
2239 
2240   if (isa<ConstantAggregateZero>(Operands[0])) {
2241     switch (IntrinsicID) {
2242     default: break;
2243     case Intrinsic::experimental_vector_reduce_add:
2244     case Intrinsic::experimental_vector_reduce_mul:
2245     case Intrinsic::experimental_vector_reduce_and:
2246     case Intrinsic::experimental_vector_reduce_or:
2247     case Intrinsic::experimental_vector_reduce_xor:
2248     case Intrinsic::experimental_vector_reduce_smin:
2249     case Intrinsic::experimental_vector_reduce_smax:
2250     case Intrinsic::experimental_vector_reduce_umin:
2251     case Intrinsic::experimental_vector_reduce_umax:
2252       return ConstantInt::get(Ty, 0);
2253     }
2254   }
2255 
2256   // Support ConstantVector in case we have an Undef in the top.
2257   if (isa<ConstantVector>(Operands[0]) ||
2258       isa<ConstantDataVector>(Operands[0])) {
2259     auto *Op = cast<Constant>(Operands[0]);
2260     switch (IntrinsicID) {
2261     default: break;
2262     case Intrinsic::experimental_vector_reduce_add:
2263     case Intrinsic::experimental_vector_reduce_mul:
2264     case Intrinsic::experimental_vector_reduce_and:
2265     case Intrinsic::experimental_vector_reduce_or:
2266     case Intrinsic::experimental_vector_reduce_xor:
2267     case Intrinsic::experimental_vector_reduce_smin:
2268     case Intrinsic::experimental_vector_reduce_smax:
2269     case Intrinsic::experimental_vector_reduce_umin:
2270     case Intrinsic::experimental_vector_reduce_umax:
2271       if (Constant *C = ConstantFoldVectorReduce(IntrinsicID, Op))
2272         return C;
2273       break;
2274     case Intrinsic::x86_sse_cvtss2si:
2275     case Intrinsic::x86_sse_cvtss2si64:
2276     case Intrinsic::x86_sse2_cvtsd2si:
2277     case Intrinsic::x86_sse2_cvtsd2si64:
2278       if (ConstantFP *FPOp =
2279               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2280         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2281                                            /*roundTowardZero=*/false, Ty,
2282                                            /*IsSigned*/true);
2283       break;
2284     case Intrinsic::x86_sse_cvttss2si:
2285     case Intrinsic::x86_sse_cvttss2si64:
2286     case Intrinsic::x86_sse2_cvttsd2si:
2287     case Intrinsic::x86_sse2_cvttsd2si64:
2288       if (ConstantFP *FPOp =
2289               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2290         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2291                                            /*roundTowardZero=*/true, Ty,
2292                                            /*IsSigned*/true);
2293       break;
2294     }
2295   }
2296 
2297   return nullptr;
2298 }
2299 
2300 static Constant *ConstantFoldScalarCall2(StringRef Name,
2301                                          Intrinsic::ID IntrinsicID,
2302                                          Type *Ty,
2303                                          ArrayRef<Constant *> Operands,
2304                                          const TargetLibraryInfo *TLI,
2305                                          const CallBase *Call) {
2306   assert(Operands.size() == 2 && "Wrong number of operands.");
2307 
2308   if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2309     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2310       return nullptr;
2311     double Op1V = getValueAsDouble(Op1);
2312 
2313     if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2314       if (Op2->getType() != Op1->getType())
2315         return nullptr;
2316 
2317       double Op2V = getValueAsDouble(Op2);
2318       if (IntrinsicID == Intrinsic::pow) {
2319         return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2320       }
2321       if (IntrinsicID == Intrinsic::copysign) {
2322         APFloat V1 = Op1->getValueAPF();
2323         const APFloat &V2 = Op2->getValueAPF();
2324         V1.copySign(V2);
2325         return ConstantFP::get(Ty->getContext(), V1);
2326       }
2327 
2328       if (IntrinsicID == Intrinsic::minnum) {
2329         const APFloat &C1 = Op1->getValueAPF();
2330         const APFloat &C2 = Op2->getValueAPF();
2331         return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
2332       }
2333 
2334       if (IntrinsicID == Intrinsic::maxnum) {
2335         const APFloat &C1 = Op1->getValueAPF();
2336         const APFloat &C2 = Op2->getValueAPF();
2337         return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
2338       }
2339 
2340       if (IntrinsicID == Intrinsic::minimum) {
2341         const APFloat &C1 = Op1->getValueAPF();
2342         const APFloat &C2 = Op2->getValueAPF();
2343         return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
2344       }
2345 
2346       if (IntrinsicID == Intrinsic::maximum) {
2347         const APFloat &C1 = Op1->getValueAPF();
2348         const APFloat &C2 = Op2->getValueAPF();
2349         return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
2350       }
2351 
2352       if (IntrinsicID == Intrinsic::amdgcn_fmul_legacy) {
2353         const APFloat &C1 = Op1->getValueAPF();
2354         const APFloat &C2 = Op2->getValueAPF();
2355         // The legacy behaviour is that multiplying zero by anything, even NaN
2356         // or infinity, gives +0.0.
2357         if (C1.isZero() || C2.isZero())
2358           return ConstantFP::getNullValue(Ty);
2359         return ConstantFP::get(Ty->getContext(), C1 * C2);
2360       }
2361 
2362       if (!TLI)
2363         return nullptr;
2364 
2365       LibFunc Func = NotLibFunc;
2366       TLI->getLibFunc(Name, Func);
2367       switch (Func) {
2368       default:
2369         break;
2370       case LibFunc_pow:
2371       case LibFunc_powf:
2372       case LibFunc_pow_finite:
2373       case LibFunc_powf_finite:
2374         if (TLI->has(Func))
2375           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2376         break;
2377       case LibFunc_fmod:
2378       case LibFunc_fmodf:
2379         if (TLI->has(Func)) {
2380           APFloat V = Op1->getValueAPF();
2381           if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2382             return ConstantFP::get(Ty->getContext(), V);
2383         }
2384         break;
2385       case LibFunc_remainder:
2386       case LibFunc_remainderf:
2387         if (TLI->has(Func)) {
2388           APFloat V = Op1->getValueAPF();
2389           if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2390             return ConstantFP::get(Ty->getContext(), V);
2391         }
2392         break;
2393       case LibFunc_atan2:
2394       case LibFunc_atan2f:
2395       case LibFunc_atan2_finite:
2396       case LibFunc_atan2f_finite:
2397         if (TLI->has(Func))
2398           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2399         break;
2400       }
2401     } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2402       if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2403         return ConstantFP::get(Ty->getContext(),
2404                                APFloat((float)std::pow((float)Op1V,
2405                                                (int)Op2C->getZExtValue())));
2406       if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2407         return ConstantFP::get(Ty->getContext(),
2408                                APFloat((float)std::pow((float)Op1V,
2409                                                (int)Op2C->getZExtValue())));
2410       if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2411         return ConstantFP::get(Ty->getContext(),
2412                                APFloat((double)std::pow((double)Op1V,
2413                                                  (int)Op2C->getZExtValue())));
2414 
2415       if (IntrinsicID == Intrinsic::amdgcn_ldexp) {
2416         // FIXME: Should flush denorms depending on FP mode, but that's ignored
2417         // everywhere else.
2418 
2419         // scalbn is equivalent to ldexp with float radix 2
2420         APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(),
2421                                 APFloat::rmNearestTiesToEven);
2422         return ConstantFP::get(Ty->getContext(), Result);
2423       }
2424     }
2425     return nullptr;
2426   }
2427 
2428   if (Operands[0]->getType()->isIntegerTy() &&
2429       Operands[1]->getType()->isIntegerTy()) {
2430     const APInt *C0, *C1;
2431     if (!getConstIntOrUndef(Operands[0], C0) ||
2432         !getConstIntOrUndef(Operands[1], C1))
2433       return nullptr;
2434 
2435     unsigned BitWidth = Ty->getScalarSizeInBits();
2436     switch (IntrinsicID) {
2437     default: break;
2438     case Intrinsic::smax:
2439       if (!C0 && !C1)
2440         return UndefValue::get(Ty);
2441       if (!C0 || !C1)
2442         return ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
2443       return ConstantInt::get(Ty, C0->sgt(*C1) ? *C0 : *C1);
2444 
2445     case Intrinsic::smin:
2446       if (!C0 && !C1)
2447         return UndefValue::get(Ty);
2448       if (!C0 || !C1)
2449         return ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth));
2450       return ConstantInt::get(Ty, C0->slt(*C1) ? *C0 : *C1);
2451 
2452     case Intrinsic::umax:
2453       if (!C0 && !C1)
2454         return UndefValue::get(Ty);
2455       if (!C0 || !C1)
2456         return ConstantInt::get(Ty, APInt::getMaxValue(BitWidth));
2457       return ConstantInt::get(Ty, C0->ugt(*C1) ? *C0 : *C1);
2458 
2459     case Intrinsic::umin:
2460       if (!C0 && !C1)
2461         return UndefValue::get(Ty);
2462       if (!C0 || !C1)
2463         return ConstantInt::get(Ty, APInt::getMinValue(BitWidth));
2464       return ConstantInt::get(Ty, C0->ult(*C1) ? *C0 : *C1);
2465 
2466     case Intrinsic::usub_with_overflow:
2467     case Intrinsic::ssub_with_overflow:
2468     case Intrinsic::uadd_with_overflow:
2469     case Intrinsic::sadd_with_overflow:
2470       // X - undef -> { undef, false }
2471       // undef - X -> { undef, false }
2472       // X + undef -> { undef, false }
2473       // undef + x -> { undef, false }
2474       if (!C0 || !C1) {
2475         return ConstantStruct::get(
2476             cast<StructType>(Ty),
2477             {UndefValue::get(Ty->getStructElementType(0)),
2478              Constant::getNullValue(Ty->getStructElementType(1))});
2479       }
2480       LLVM_FALLTHROUGH;
2481     case Intrinsic::smul_with_overflow:
2482     case Intrinsic::umul_with_overflow: {
2483       // undef * X -> { 0, false }
2484       // X * undef -> { 0, false }
2485       if (!C0 || !C1)
2486         return Constant::getNullValue(Ty);
2487 
2488       APInt Res;
2489       bool Overflow;
2490       switch (IntrinsicID) {
2491       default: llvm_unreachable("Invalid case");
2492       case Intrinsic::sadd_with_overflow:
2493         Res = C0->sadd_ov(*C1, Overflow);
2494         break;
2495       case Intrinsic::uadd_with_overflow:
2496         Res = C0->uadd_ov(*C1, Overflow);
2497         break;
2498       case Intrinsic::ssub_with_overflow:
2499         Res = C0->ssub_ov(*C1, Overflow);
2500         break;
2501       case Intrinsic::usub_with_overflow:
2502         Res = C0->usub_ov(*C1, Overflow);
2503         break;
2504       case Intrinsic::smul_with_overflow:
2505         Res = C0->smul_ov(*C1, Overflow);
2506         break;
2507       case Intrinsic::umul_with_overflow:
2508         Res = C0->umul_ov(*C1, Overflow);
2509         break;
2510       }
2511       Constant *Ops[] = {
2512         ConstantInt::get(Ty->getContext(), Res),
2513         ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2514       };
2515       return ConstantStruct::get(cast<StructType>(Ty), Ops);
2516     }
2517     case Intrinsic::uadd_sat:
2518     case Intrinsic::sadd_sat:
2519       if (!C0 && !C1)
2520         return UndefValue::get(Ty);
2521       if (!C0 || !C1)
2522         return Constant::getAllOnesValue(Ty);
2523       if (IntrinsicID == Intrinsic::uadd_sat)
2524         return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2525       else
2526         return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2527     case Intrinsic::usub_sat:
2528     case Intrinsic::ssub_sat:
2529       if (!C0 && !C1)
2530         return UndefValue::get(Ty);
2531       if (!C0 || !C1)
2532         return Constant::getNullValue(Ty);
2533       if (IntrinsicID == Intrinsic::usub_sat)
2534         return ConstantInt::get(Ty, C0->usub_sat(*C1));
2535       else
2536         return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2537     case Intrinsic::cttz:
2538     case Intrinsic::ctlz:
2539       assert(C1 && "Must be constant int");
2540 
2541       // cttz(0, 1) and ctlz(0, 1) are undef.
2542       if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2543         return UndefValue::get(Ty);
2544       if (!C0)
2545         return Constant::getNullValue(Ty);
2546       if (IntrinsicID == Intrinsic::cttz)
2547         return ConstantInt::get(Ty, C0->countTrailingZeros());
2548       else
2549         return ConstantInt::get(Ty, C0->countLeadingZeros());
2550 
2551     case Intrinsic::abs:
2552       // Undef or minimum val operand with poison min --> undef
2553       assert(C1 && "Must be constant int");
2554       if (C1->isOneValue() && (!C0 || C0->isMinSignedValue()))
2555         return UndefValue::get(Ty);
2556 
2557       // Undef operand with no poison min --> 0 (sign bit must be clear)
2558       if (C1->isNullValue() && !C0)
2559         return Constant::getNullValue(Ty);
2560 
2561       return ConstantInt::get(Ty, C0->abs());
2562     }
2563 
2564     return nullptr;
2565   }
2566 
2567   // Support ConstantVector in case we have an Undef in the top.
2568   if ((isa<ConstantVector>(Operands[0]) ||
2569        isa<ConstantDataVector>(Operands[0])) &&
2570       // Check for default rounding mode.
2571       // FIXME: Support other rounding modes?
2572       isa<ConstantInt>(Operands[1]) &&
2573       cast<ConstantInt>(Operands[1])->getValue() == 4) {
2574     auto *Op = cast<Constant>(Operands[0]);
2575     switch (IntrinsicID) {
2576     default: break;
2577     case Intrinsic::x86_avx512_vcvtss2si32:
2578     case Intrinsic::x86_avx512_vcvtss2si64:
2579     case Intrinsic::x86_avx512_vcvtsd2si32:
2580     case Intrinsic::x86_avx512_vcvtsd2si64:
2581       if (ConstantFP *FPOp =
2582               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2583         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2584                                            /*roundTowardZero=*/false, Ty,
2585                                            /*IsSigned*/true);
2586       break;
2587     case Intrinsic::x86_avx512_vcvtss2usi32:
2588     case Intrinsic::x86_avx512_vcvtss2usi64:
2589     case Intrinsic::x86_avx512_vcvtsd2usi32:
2590     case Intrinsic::x86_avx512_vcvtsd2usi64:
2591       if (ConstantFP *FPOp =
2592               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2593         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2594                                            /*roundTowardZero=*/false, Ty,
2595                                            /*IsSigned*/false);
2596       break;
2597     case Intrinsic::x86_avx512_cvttss2si:
2598     case Intrinsic::x86_avx512_cvttss2si64:
2599     case Intrinsic::x86_avx512_cvttsd2si:
2600     case Intrinsic::x86_avx512_cvttsd2si64:
2601       if (ConstantFP *FPOp =
2602               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2603         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2604                                            /*roundTowardZero=*/true, Ty,
2605                                            /*IsSigned*/true);
2606       break;
2607     case Intrinsic::x86_avx512_cvttss2usi:
2608     case Intrinsic::x86_avx512_cvttss2usi64:
2609     case Intrinsic::x86_avx512_cvttsd2usi:
2610     case Intrinsic::x86_avx512_cvttsd2usi64:
2611       if (ConstantFP *FPOp =
2612               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2613         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2614                                            /*roundTowardZero=*/true, Ty,
2615                                            /*IsSigned*/false);
2616       break;
2617     }
2618   }
2619   return nullptr;
2620 }
2621 
2622 static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2623                                                const APFloat &S0,
2624                                                const APFloat &S1,
2625                                                const APFloat &S2) {
2626   unsigned ID;
2627   const fltSemantics &Sem = S0.getSemantics();
2628   APFloat MA(Sem), SC(Sem), TC(Sem);
2629   if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2630     if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2631       // S2 < 0
2632       ID = 5;
2633       SC = -S0;
2634     } else {
2635       ID = 4;
2636       SC = S0;
2637     }
2638     MA = S2;
2639     TC = -S1;
2640   } else if (abs(S1) >= abs(S0)) {
2641     if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2642       // S1 < 0
2643       ID = 3;
2644       TC = -S2;
2645     } else {
2646       ID = 2;
2647       TC = S2;
2648     }
2649     MA = S1;
2650     SC = S0;
2651   } else {
2652     if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2653       // S0 < 0
2654       ID = 1;
2655       SC = S2;
2656     } else {
2657       ID = 0;
2658       SC = -S2;
2659     }
2660     MA = S0;
2661     TC = -S1;
2662   }
2663   switch (IntrinsicID) {
2664   default:
2665     llvm_unreachable("unhandled amdgcn cube intrinsic");
2666   case Intrinsic::amdgcn_cubeid:
2667     return APFloat(Sem, ID);
2668   case Intrinsic::amdgcn_cubema:
2669     return MA + MA;
2670   case Intrinsic::amdgcn_cubesc:
2671     return SC;
2672   case Intrinsic::amdgcn_cubetc:
2673     return TC;
2674   }
2675 }
2676 
2677 static Constant *ConstantFoldScalarCall3(StringRef Name,
2678                                          Intrinsic::ID IntrinsicID,
2679                                          Type *Ty,
2680                                          ArrayRef<Constant *> Operands,
2681                                          const TargetLibraryInfo *TLI,
2682                                          const CallBase *Call) {
2683   assert(Operands.size() == 3 && "Wrong number of operands.");
2684 
2685   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2686     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2687       if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2688         switch (IntrinsicID) {
2689         default: break;
2690         case Intrinsic::fma:
2691         case Intrinsic::fmuladd: {
2692           APFloat V = Op1->getValueAPF();
2693           V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(),
2694                              APFloat::rmNearestTiesToEven);
2695           return ConstantFP::get(Ty->getContext(), V);
2696         }
2697         case Intrinsic::amdgcn_cubeid:
2698         case Intrinsic::amdgcn_cubema:
2699         case Intrinsic::amdgcn_cubesc:
2700         case Intrinsic::amdgcn_cubetc: {
2701           APFloat V = ConstantFoldAMDGCNCubeIntrinsic(
2702               IntrinsicID, Op1->getValueAPF(), Op2->getValueAPF(),
2703               Op3->getValueAPF());
2704           return ConstantFP::get(Ty->getContext(), V);
2705         }
2706         }
2707       }
2708     }
2709   }
2710 
2711   if (const auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
2712     if (const auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
2713       if (const auto *Op3 = dyn_cast<ConstantInt>(Operands[2])) {
2714         switch (IntrinsicID) {
2715         default: break;
2716         case Intrinsic::smul_fix:
2717         case Intrinsic::smul_fix_sat: {
2718           // This code performs rounding towards negative infinity in case the
2719           // result cannot be represented exactly for the given scale. Targets
2720           // that do care about rounding should use a target hook for specifying
2721           // how rounding should be done, and provide their own folding to be
2722           // consistent with rounding. This is the same approach as used by
2723           // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2724           const APInt &Lhs = Op1->getValue();
2725           const APInt &Rhs = Op2->getValue();
2726           unsigned Scale = Op3->getValue().getZExtValue();
2727           unsigned Width = Lhs.getBitWidth();
2728           assert(Scale < Width && "Illegal scale.");
2729           unsigned ExtendedWidth = Width * 2;
2730           APInt Product = (Lhs.sextOrSelf(ExtendedWidth) *
2731                            Rhs.sextOrSelf(ExtendedWidth)).ashr(Scale);
2732           if (IntrinsicID == Intrinsic::smul_fix_sat) {
2733             APInt MaxValue =
2734               APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth);
2735             APInt MinValue =
2736               APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth);
2737             Product = APIntOps::smin(Product, MaxValue);
2738             Product = APIntOps::smax(Product, MinValue);
2739           }
2740           return ConstantInt::get(Ty->getContext(),
2741                                   Product.sextOrTrunc(Width));
2742         }
2743         }
2744       }
2745     }
2746   }
2747 
2748   if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
2749     const APInt *C0, *C1, *C2;
2750     if (!getConstIntOrUndef(Operands[0], C0) ||
2751         !getConstIntOrUndef(Operands[1], C1) ||
2752         !getConstIntOrUndef(Operands[2], C2))
2753       return nullptr;
2754 
2755     bool IsRight = IntrinsicID == Intrinsic::fshr;
2756     if (!C2)
2757       return Operands[IsRight ? 1 : 0];
2758     if (!C0 && !C1)
2759       return UndefValue::get(Ty);
2760 
2761     // The shift amount is interpreted as modulo the bitwidth. If the shift
2762     // amount is effectively 0, avoid UB due to oversized inverse shift below.
2763     unsigned BitWidth = C2->getBitWidth();
2764     unsigned ShAmt = C2->urem(BitWidth);
2765     if (!ShAmt)
2766       return Operands[IsRight ? 1 : 0];
2767 
2768     // (C0 << ShlAmt) | (C1 >> LshrAmt)
2769     unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2770     unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
2771     if (!C0)
2772       return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2773     if (!C1)
2774       return ConstantInt::get(Ty, C0->shl(ShlAmt));
2775     return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
2776   }
2777 
2778   return nullptr;
2779 }
2780 
2781 static Constant *ConstantFoldScalarCall(StringRef Name,
2782                                         Intrinsic::ID IntrinsicID,
2783                                         Type *Ty,
2784                                         ArrayRef<Constant *> Operands,
2785                                         const TargetLibraryInfo *TLI,
2786                                         const CallBase *Call) {
2787   if (Operands.size() == 1)
2788     return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
2789 
2790   if (Operands.size() == 2)
2791     return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
2792 
2793   if (Operands.size() == 3)
2794     return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
2795 
2796   return nullptr;
2797 }
2798 
2799 static Constant *ConstantFoldVectorCall(StringRef Name,
2800                                         Intrinsic::ID IntrinsicID,
2801                                         VectorType *VTy,
2802                                         ArrayRef<Constant *> Operands,
2803                                         const DataLayout &DL,
2804                                         const TargetLibraryInfo *TLI,
2805                                         const CallBase *Call) {
2806   // Do not iterate on scalable vector. The number of elements is unknown at
2807   // compile-time.
2808   if (isa<ScalableVectorType>(VTy))
2809     return nullptr;
2810 
2811   auto *FVTy = cast<FixedVectorType>(VTy);
2812 
2813   SmallVector<Constant *, 4> Result(FVTy->getNumElements());
2814   SmallVector<Constant *, 4> Lane(Operands.size());
2815   Type *Ty = FVTy->getElementType();
2816 
2817   switch (IntrinsicID) {
2818   case Intrinsic::masked_load: {
2819     auto *SrcPtr = Operands[0];
2820     auto *Mask = Operands[2];
2821     auto *Passthru = Operands[3];
2822 
2823     Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
2824 
2825     SmallVector<Constant *, 32> NewElements;
2826     for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2827       auto *MaskElt = Mask->getAggregateElement(I);
2828       if (!MaskElt)
2829         break;
2830       auto *PassthruElt = Passthru->getAggregateElement(I);
2831       auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2832       if (isa<UndefValue>(MaskElt)) {
2833         if (PassthruElt)
2834           NewElements.push_back(PassthruElt);
2835         else if (VecElt)
2836           NewElements.push_back(VecElt);
2837         else
2838           return nullptr;
2839       }
2840       if (MaskElt->isNullValue()) {
2841         if (!PassthruElt)
2842           return nullptr;
2843         NewElements.push_back(PassthruElt);
2844       } else if (MaskElt->isOneValue()) {
2845         if (!VecElt)
2846           return nullptr;
2847         NewElements.push_back(VecElt);
2848       } else {
2849         return nullptr;
2850       }
2851     }
2852     if (NewElements.size() != FVTy->getNumElements())
2853       return nullptr;
2854     return ConstantVector::get(NewElements);
2855   }
2856   case Intrinsic::arm_mve_vctp8:
2857   case Intrinsic::arm_mve_vctp16:
2858   case Intrinsic::arm_mve_vctp32:
2859   case Intrinsic::arm_mve_vctp64: {
2860     if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2861       unsigned Lanes = FVTy->getNumElements();
2862       uint64_t Limit = Op->getZExtValue();
2863       // vctp64 are currently modelled as returning a v4i1, not a v2i1. Make
2864       // sure we get the limit right in that case and set all relevant lanes.
2865       if (IntrinsicID == Intrinsic::arm_mve_vctp64)
2866         Limit *= 2;
2867 
2868       SmallVector<Constant *, 16> NCs;
2869       for (unsigned i = 0; i < Lanes; i++) {
2870         if (i < Limit)
2871           NCs.push_back(ConstantInt::getTrue(Ty));
2872         else
2873           NCs.push_back(ConstantInt::getFalse(Ty));
2874       }
2875       return ConstantVector::get(NCs);
2876     }
2877     break;
2878   }
2879   default:
2880     break;
2881   }
2882 
2883   for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2884     // Gather a column of constants.
2885     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
2886       // Some intrinsics use a scalar type for certain arguments.
2887       if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) {
2888         Lane[J] = Operands[J];
2889         continue;
2890       }
2891 
2892       Constant *Agg = Operands[J]->getAggregateElement(I);
2893       if (!Agg)
2894         return nullptr;
2895 
2896       Lane[J] = Agg;
2897     }
2898 
2899     // Use the regular scalar folding to simplify this column.
2900     Constant *Folded =
2901         ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
2902     if (!Folded)
2903       return nullptr;
2904     Result[I] = Folded;
2905   }
2906 
2907   return ConstantVector::get(Result);
2908 }
2909 
2910 } // end anonymous namespace
2911 
2912 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
2913                                  ArrayRef<Constant *> Operands,
2914                                  const TargetLibraryInfo *TLI) {
2915   if (Call->isNoBuiltin())
2916     return nullptr;
2917   if (!F->hasName())
2918     return nullptr;
2919   StringRef Name = F->getName();
2920 
2921   Type *Ty = F->getReturnType();
2922 
2923   if (auto *VTy = dyn_cast<VectorType>(Ty))
2924     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2925                                   F->getParent()->getDataLayout(), TLI, Call);
2926 
2927   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
2928                                 Call);
2929 }
2930 
2931 bool llvm::isMathLibCallNoop(const CallBase *Call,
2932                              const TargetLibraryInfo *TLI) {
2933   // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2934   // (and to some extent ConstantFoldScalarCall).
2935   if (Call->isNoBuiltin() || Call->isStrictFP())
2936     return false;
2937   Function *F = Call->getCalledFunction();
2938   if (!F)
2939     return false;
2940 
2941   LibFunc Func;
2942   if (!TLI || !TLI->getLibFunc(*F, Func))
2943     return false;
2944 
2945   if (Call->getNumArgOperands() == 1) {
2946     if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
2947       const APFloat &Op = OpC->getValueAPF();
2948       switch (Func) {
2949       case LibFunc_logl:
2950       case LibFunc_log:
2951       case LibFunc_logf:
2952       case LibFunc_log2l:
2953       case LibFunc_log2:
2954       case LibFunc_log2f:
2955       case LibFunc_log10l:
2956       case LibFunc_log10:
2957       case LibFunc_log10f:
2958         return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2959 
2960       case LibFunc_expl:
2961       case LibFunc_exp:
2962       case LibFunc_expf:
2963         // FIXME: These boundaries are slightly conservative.
2964         if (OpC->getType()->isDoubleTy())
2965           return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
2966         if (OpC->getType()->isFloatTy())
2967           return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
2968         break;
2969 
2970       case LibFunc_exp2l:
2971       case LibFunc_exp2:
2972       case LibFunc_exp2f:
2973         // FIXME: These boundaries are slightly conservative.
2974         if (OpC->getType()->isDoubleTy())
2975           return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
2976         if (OpC->getType()->isFloatTy())
2977           return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
2978         break;
2979 
2980       case LibFunc_sinl:
2981       case LibFunc_sin:
2982       case LibFunc_sinf:
2983       case LibFunc_cosl:
2984       case LibFunc_cos:
2985       case LibFunc_cosf:
2986         return !Op.isInfinity();
2987 
2988       case LibFunc_tanl:
2989       case LibFunc_tan:
2990       case LibFunc_tanf: {
2991         // FIXME: Stop using the host math library.
2992         // FIXME: The computation isn't done in the right precision.
2993         Type *Ty = OpC->getType();
2994         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2995           double OpV = getValueAsDouble(OpC);
2996           return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2997         }
2998         break;
2999       }
3000 
3001       case LibFunc_asinl:
3002       case LibFunc_asin:
3003       case LibFunc_asinf:
3004       case LibFunc_acosl:
3005       case LibFunc_acos:
3006       case LibFunc_acosf:
3007         return !(Op < APFloat(Op.getSemantics(), "-1") ||
3008                  Op > APFloat(Op.getSemantics(), "1"));
3009 
3010       case LibFunc_sinh:
3011       case LibFunc_cosh:
3012       case LibFunc_sinhf:
3013       case LibFunc_coshf:
3014       case LibFunc_sinhl:
3015       case LibFunc_coshl:
3016         // FIXME: These boundaries are slightly conservative.
3017         if (OpC->getType()->isDoubleTy())
3018           return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3019         if (OpC->getType()->isFloatTy())
3020           return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3021         break;
3022 
3023       case LibFunc_sqrtl:
3024       case LibFunc_sqrt:
3025       case LibFunc_sqrtf:
3026         return Op.isNaN() || Op.isZero() || !Op.isNegative();
3027 
3028       // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3029       // maybe others?
3030       default:
3031         break;
3032       }
3033     }
3034   }
3035 
3036   if (Call->getNumArgOperands() == 2) {
3037     ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3038     ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3039     if (Op0C && Op1C) {
3040       const APFloat &Op0 = Op0C->getValueAPF();
3041       const APFloat &Op1 = Op1C->getValueAPF();
3042 
3043       switch (Func) {
3044       case LibFunc_powl:
3045       case LibFunc_pow:
3046       case LibFunc_powf: {
3047         // FIXME: Stop using the host math library.
3048         // FIXME: The computation isn't done in the right precision.
3049         Type *Ty = Op0C->getType();
3050         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3051           if (Ty == Op1C->getType()) {
3052             double Op0V = getValueAsDouble(Op0C);
3053             double Op1V = getValueAsDouble(Op1C);
3054             return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
3055           }
3056         }
3057         break;
3058       }
3059 
3060       case LibFunc_fmodl:
3061       case LibFunc_fmod:
3062       case LibFunc_fmodf:
3063       case LibFunc_remainderl:
3064       case LibFunc_remainder:
3065       case LibFunc_remainderf:
3066         return Op0.isNaN() || Op1.isNaN() ||
3067                (!Op0.isInfinity() && !Op1.isZero());
3068 
3069       default:
3070         break;
3071       }
3072     }
3073   }
3074 
3075   return false;
3076 }
3077 
3078 void TargetFolder::anchor() {}
3079