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