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