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