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