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