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