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