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