1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic IR ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // DataLayout information. These functions cannot go in IR due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include <cerrno>
38 #include <cmath>
39 
40 #ifdef HAVE_FENV_H
41 #include <fenv.h>
42 #endif
43 
44 using namespace llvm;
45 
46 //===----------------------------------------------------------------------===//
47 // Constant Folding internal helper functions
48 //===----------------------------------------------------------------------===//
49 
50 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
51 /// This always returns a non-null constant, but it may be a
52 /// ConstantExpr if unfoldable.
53 static Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
54   // Catch the obvious splat cases.
55   if (C->isNullValue() && !DestTy->isX86_MMXTy())
56     return Constant::getNullValue(DestTy);
57   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
58       !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
59     return Constant::getAllOnesValue(DestTy);
60 
61   // Handle a vector->integer cast.
62   if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
63     VectorType *VTy = dyn_cast<VectorType>(C->getType());
64     if (!VTy)
65       return ConstantExpr::getBitCast(C, DestTy);
66 
67     unsigned NumSrcElts = VTy->getNumElements();
68     Type *SrcEltTy = VTy->getElementType();
69 
70     // If the vector is a vector of floating point, convert it to vector of int
71     // to simplify things.
72     if (SrcEltTy->isFloatingPointTy()) {
73       unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
74       Type *SrcIVTy =
75         VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
76       // Ask IR to do the conversion now that #elts line up.
77       C = ConstantExpr::getBitCast(C, SrcIVTy);
78     }
79 
80     ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
81     if (!CDV)
82       return ConstantExpr::getBitCast(C, DestTy);
83 
84     // Now that we know that the input value is a vector of integers, just shift
85     // and insert them into our result.
86     unsigned BitShift = DL.getTypeAllocSizeInBits(SrcEltTy);
87     APInt Result(IT->getBitWidth(), 0);
88     for (unsigned i = 0; i != NumSrcElts; ++i) {
89       Result <<= BitShift;
90       if (DL.isLittleEndian())
91         Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
92       else
93         Result |= CDV->getElementAsInteger(i);
94     }
95 
96     return ConstantInt::get(IT, Result);
97   }
98 
99   // The code below only handles casts to vectors currently.
100   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
101   if (!DestVTy)
102     return ConstantExpr::getBitCast(C, DestTy);
103 
104   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
105   // vector so the code below can handle it uniformly.
106   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
107     Constant *Ops = C; // don't take the address of C!
108     return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
109   }
110 
111   // If this is a bitcast from constant vector -> vector, fold it.
112   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
113     return ConstantExpr::getBitCast(C, DestTy);
114 
115   // If the element types match, IR can fold it.
116   unsigned NumDstElt = DestVTy->getNumElements();
117   unsigned NumSrcElt = C->getType()->getVectorNumElements();
118   if (NumDstElt == NumSrcElt)
119     return ConstantExpr::getBitCast(C, DestTy);
120 
121   Type *SrcEltTy = C->getType()->getVectorElementType();
122   Type *DstEltTy = DestVTy->getElementType();
123 
124   // Otherwise, we're changing the number of elements in a vector, which
125   // requires endianness information to do the right thing.  For example,
126   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
127   // folds to (little endian):
128   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
129   // and to (big endian):
130   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
131 
132   // First thing is first.  We only want to think about integer here, so if
133   // we have something in FP form, recast it as integer.
134   if (DstEltTy->isFloatingPointTy()) {
135     // Fold to an vector of integers with same size as our FP type.
136     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
137     Type *DestIVTy =
138       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
139     // Recursively handle this integer conversion, if possible.
140     C = FoldBitCast(C, DestIVTy, DL);
141 
142     // Finally, IR can handle this now that #elts line up.
143     return ConstantExpr::getBitCast(C, DestTy);
144   }
145 
146   // Okay, we know the destination is integer, if the input is FP, convert
147   // it to integer first.
148   if (SrcEltTy->isFloatingPointTy()) {
149     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
150     Type *SrcIVTy =
151       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
152     // Ask IR to do the conversion now that #elts line up.
153     C = ConstantExpr::getBitCast(C, SrcIVTy);
154     // If IR wasn't able to fold it, bail out.
155     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
156         !isa<ConstantDataVector>(C))
157       return C;
158   }
159 
160   // Now we know that the input and output vectors are both integer vectors
161   // of the same size, and that their #elements is not the same.  Do the
162   // conversion here, which depends on whether the input or output has
163   // more elements.
164   bool isLittleEndian = DL.isLittleEndian();
165 
166   SmallVector<Constant*, 32> Result;
167   if (NumDstElt < NumSrcElt) {
168     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
169     Constant *Zero = Constant::getNullValue(DstEltTy);
170     unsigned Ratio = NumSrcElt/NumDstElt;
171     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
172     unsigned SrcElt = 0;
173     for (unsigned i = 0; i != NumDstElt; ++i) {
174       // Build each element of the result.
175       Constant *Elt = Zero;
176       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
177       for (unsigned j = 0; j != Ratio; ++j) {
178         Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
179         if (!Src)  // Reject constantexpr elements.
180           return ConstantExpr::getBitCast(C, DestTy);
181 
182         // Zero extend the element to the right size.
183         Src = ConstantExpr::getZExt(Src, Elt->getType());
184 
185         // Shift it to the right place, depending on endianness.
186         Src = ConstantExpr::getShl(Src,
187                                    ConstantInt::get(Src->getType(), ShiftAmt));
188         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
189 
190         // Mix it in.
191         Elt = ConstantExpr::getOr(Elt, Src);
192       }
193       Result.push_back(Elt);
194     }
195     return ConstantVector::get(Result);
196   }
197 
198   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
199   unsigned Ratio = NumDstElt/NumSrcElt;
200   unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
201 
202   // Loop over each source value, expanding into multiple results.
203   for (unsigned i = 0; i != NumSrcElt; ++i) {
204     Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
205     if (!Src)  // Reject constantexpr elements.
206       return ConstantExpr::getBitCast(C, DestTy);
207 
208     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
209     for (unsigned j = 0; j != Ratio; ++j) {
210       // Shift the piece of the value into the right place, depending on
211       // endianness.
212       Constant *Elt = ConstantExpr::getLShr(Src,
213                                   ConstantInt::get(Src->getType(), ShiftAmt));
214       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
215 
216       // Truncate the element to an integer with the same pointer size and
217       // convert the element back to a pointer using a inttoptr.
218       if (DstEltTy->isPointerTy()) {
219         IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
220         Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
221         Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
222         continue;
223       }
224 
225       // Truncate and remember this piece.
226       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
227     }
228   }
229 
230   return ConstantVector::get(Result);
231 }
232 
233 
234 /// If this constant is a constant offset from a global, return the global and
235 /// the constant. Because of constantexprs, this function is recursive.
236 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
237                                        APInt &Offset, const DataLayout &DL) {
238   // Trivial case, constant is the global.
239   if ((GV = dyn_cast<GlobalValue>(C))) {
240     unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
241     Offset = APInt(BitWidth, 0);
242     return true;
243   }
244 
245   // Otherwise, if this isn't a constant expr, bail out.
246   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
247   if (!CE) return false;
248 
249   // Look through ptr->int and ptr->ptr casts.
250   if (CE->getOpcode() == Instruction::PtrToInt ||
251       CE->getOpcode() == Instruction::BitCast)
252     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
253 
254   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
255   GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
256   if (!GEP)
257     return false;
258 
259   unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
260   APInt TmpOffset(BitWidth, 0);
261 
262   // If the base isn't a global+constant, we aren't either.
263   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
264     return false;
265 
266   // Otherwise, add any offset that our operands provide.
267   if (!GEP->accumulateConstantOffset(DL, TmpOffset))
268     return false;
269 
270   Offset = TmpOffset;
271   return true;
272 }
273 
274 /// Recursive helper to read bits out of global. C is the constant being copied
275 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
276 /// results into and BytesLeft is the number of bytes left in
277 /// the CurPtr buffer. DL is the DataLayout.
278 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
279                                unsigned char *CurPtr, unsigned BytesLeft,
280                                const DataLayout &DL) {
281   assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
282          "Out of range access");
283 
284   // If this element is zero or undefined, we can just return since *CurPtr is
285   // zero initialized.
286   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
287     return true;
288 
289   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
290     if (CI->getBitWidth() > 64 ||
291         (CI->getBitWidth() & 7) != 0)
292       return false;
293 
294     uint64_t Val = CI->getZExtValue();
295     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
296 
297     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
298       int n = ByteOffset;
299       if (!DL.isLittleEndian())
300         n = IntBytes - n - 1;
301       CurPtr[i] = (unsigned char)(Val >> (n * 8));
302       ++ByteOffset;
303     }
304     return true;
305   }
306 
307   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
308     if (CFP->getType()->isDoubleTy()) {
309       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
310       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
311     }
312     if (CFP->getType()->isFloatTy()){
313       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
314       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
315     }
316     if (CFP->getType()->isHalfTy()){
317       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
318       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
319     }
320     return false;
321   }
322 
323   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
324     const StructLayout *SL = DL.getStructLayout(CS->getType());
325     unsigned Index = SL->getElementContainingOffset(ByteOffset);
326     uint64_t CurEltOffset = SL->getElementOffset(Index);
327     ByteOffset -= CurEltOffset;
328 
329     while (1) {
330       // If the element access is to the element itself and not to tail padding,
331       // read the bytes from the element.
332       uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
333 
334       if (ByteOffset < EltSize &&
335           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
336                               BytesLeft, DL))
337         return false;
338 
339       ++Index;
340 
341       // Check to see if we read from the last struct element, if so we're done.
342       if (Index == CS->getType()->getNumElements())
343         return true;
344 
345       // If we read all of the bytes we needed from this element we're done.
346       uint64_t NextEltOffset = SL->getElementOffset(Index);
347 
348       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
349         return true;
350 
351       // Move to the next element of the struct.
352       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
353       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
354       ByteOffset = 0;
355       CurEltOffset = NextEltOffset;
356     }
357     // not reached.
358   }
359 
360   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
361       isa<ConstantDataSequential>(C)) {
362     Type *EltTy = C->getType()->getSequentialElementType();
363     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
364     uint64_t Index = ByteOffset / EltSize;
365     uint64_t Offset = ByteOffset - Index * EltSize;
366     uint64_t NumElts;
367     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
368       NumElts = AT->getNumElements();
369     else
370       NumElts = C->getType()->getVectorNumElements();
371 
372     for (; Index != NumElts; ++Index) {
373       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
374                               BytesLeft, DL))
375         return false;
376 
377       uint64_t BytesWritten = EltSize - Offset;
378       assert(BytesWritten <= EltSize && "Not indexing into this element?");
379       if (BytesWritten >= BytesLeft)
380         return true;
381 
382       Offset = 0;
383       BytesLeft -= BytesWritten;
384       CurPtr += BytesWritten;
385     }
386     return true;
387   }
388 
389   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
390     if (CE->getOpcode() == Instruction::IntToPtr &&
391         CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
392       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
393                                 BytesLeft, DL);
394     }
395   }
396 
397   // Otherwise, unknown initializer type.
398   return false;
399 }
400 
401 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
402                                                  Type *LoadTy,
403                                                  const DataLayout &DL) {
404   PointerType *PTy = cast<PointerType>(C->getType());
405   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
406 
407   // If this isn't an integer load we can't fold it directly.
408   if (!IntType) {
409     unsigned AS = PTy->getAddressSpace();
410 
411     // If this is a float/double load, we can try folding it as an int32/64 load
412     // and then bitcast the result.  This can be useful for union cases.  Note
413     // that address spaces don't matter here since we're not going to result in
414     // an actual new load.
415     Type *MapTy;
416     if (LoadTy->isHalfTy())
417       MapTy = Type::getInt16Ty(C->getContext());
418     else if (LoadTy->isFloatTy())
419       MapTy = Type::getInt32Ty(C->getContext());
420     else if (LoadTy->isDoubleTy())
421       MapTy = Type::getInt64Ty(C->getContext());
422     else if (LoadTy->isVectorTy()) {
423       MapTy = PointerType::getIntNTy(C->getContext(),
424                                      DL.getTypeAllocSizeInBits(LoadTy));
425     } else
426       return nullptr;
427 
428     C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
429     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
430       return FoldBitCast(Res, LoadTy, DL);
431     return nullptr;
432   }
433 
434   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
435   if (BytesLoaded > 32 || BytesLoaded == 0)
436     return nullptr;
437 
438   GlobalValue *GVal;
439   APInt Offset;
440   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, DL))
441     return nullptr;
442 
443   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
444   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
445       !GV->getInitializer()->getType()->isSized())
446     return nullptr;
447 
448   // If we're loading off the beginning of the global, some bytes may be valid,
449   // but we don't try to handle this.
450   if (Offset.isNegative())
451     return nullptr;
452 
453   // If we're not accessing anything in this constant, the result is undefined.
454   if (Offset.getZExtValue() >=
455       DL.getTypeAllocSize(GV->getInitializer()->getType()))
456     return UndefValue::get(IntType);
457 
458   unsigned char RawBytes[32] = {0};
459   if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
460                           BytesLoaded, DL))
461     return nullptr;
462 
463   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
464   if (DL.isLittleEndian()) {
465     ResultVal = RawBytes[BytesLoaded - 1];
466     for (unsigned i = 1; i != BytesLoaded; ++i) {
467       ResultVal <<= 8;
468       ResultVal |= RawBytes[BytesLoaded - 1 - i];
469     }
470   } else {
471     ResultVal = RawBytes[0];
472     for (unsigned i = 1; i != BytesLoaded; ++i) {
473       ResultVal <<= 8;
474       ResultVal |= RawBytes[i];
475     }
476   }
477 
478   return ConstantInt::get(IntType->getContext(), ResultVal);
479 }
480 
481 static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
482                                                 Type *DestTy,
483                                                 const DataLayout &DL) {
484   auto *SrcPtr = CE->getOperand(0);
485   auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
486   if (!SrcPtrTy)
487     return nullptr;
488   Type *SrcTy = SrcPtrTy->getPointerElementType();
489 
490   Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
491   if (!C)
492     return nullptr;
493 
494   do {
495     Type *SrcTy = C->getType();
496 
497     // If the type sizes are the same and a cast is legal, just directly
498     // cast the constant.
499     if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
500       Instruction::CastOps Cast = Instruction::BitCast;
501       // If we are going from a pointer to int or vice versa, we spell the cast
502       // differently.
503       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504         Cast = Instruction::IntToPtr;
505       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506         Cast = Instruction::PtrToInt;
507 
508       if (CastInst::castIsValid(Cast, C, DestTy))
509         return ConstantExpr::getCast(Cast, C, DestTy);
510     }
511 
512     // If this isn't an aggregate type, there is nothing we can do to drill down
513     // and find a bitcastable constant.
514     if (!SrcTy->isAggregateType())
515       return nullptr;
516 
517     // We're simulating a load through a pointer that was bitcast to point to
518     // a different type, so we can try to walk down through the initial
519     // elements of an aggregate to see if some part of th e aggregate is
520     // castable to implement the "load" semantic model.
521     C = C->getAggregateElement(0u);
522   } while (C);
523 
524   return nullptr;
525 }
526 
527 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
528                                              const DataLayout &DL) {
529   // First, try the easy cases:
530   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
531     if (GV->isConstant() && GV->hasDefinitiveInitializer())
532       return GV->getInitializer();
533 
534   if (auto *GA = dyn_cast<GlobalAlias>(C))
535     if (GA->getAliasee() && !GA->mayBeOverridden())
536       return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
537 
538   // If the loaded value isn't a constant expr, we can't handle it.
539   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
540   if (!CE)
541     return nullptr;
542 
543   if (CE->getOpcode() == Instruction::GetElementPtr) {
544     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
545       if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
546         if (Constant *V =
547              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
548           return V;
549       }
550     }
551   }
552 
553   if (CE->getOpcode() == Instruction::BitCast)
554     if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
555       return LoadedC;
556 
557   // Instead of loading constant c string, use corresponding integer value
558   // directly if string length is small enough.
559   StringRef Str;
560   if (getConstantStringInfo(CE, Str) && !Str.empty()) {
561     unsigned StrLen = Str.size();
562     unsigned NumBits = Ty->getPrimitiveSizeInBits();
563     // Replace load with immediate integer if the result is an integer or fp
564     // value.
565     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
566         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
567       APInt StrVal(NumBits, 0);
568       APInt SingleChar(NumBits, 0);
569       if (DL.isLittleEndian()) {
570         for (signed i = StrLen-1; i >= 0; i--) {
571           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
572           StrVal = (StrVal << 8) | SingleChar;
573         }
574       } else {
575         for (unsigned i = 0; i < StrLen; i++) {
576           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
577           StrVal = (StrVal << 8) | SingleChar;
578         }
579         // Append NULL at the end.
580         SingleChar = 0;
581         StrVal = (StrVal << 8) | SingleChar;
582       }
583 
584       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
585       if (Ty->isFloatingPointTy())
586         Res = ConstantExpr::getBitCast(Res, Ty);
587       return Res;
588     }
589   }
590 
591   // If this load comes from anywhere in a constant global, and if the global
592   // is all undef or zero, we know what it loads.
593   if (GlobalVariable *GV =
594           dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
595     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
596       if (GV->getInitializer()->isNullValue())
597         return Constant::getNullValue(Ty);
598       if (isa<UndefValue>(GV->getInitializer()))
599         return UndefValue::get(Ty);
600     }
601   }
602 
603   // Try hard to fold loads from bitcasted strange and non-type-safe things.
604   return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
605 }
606 
607 static Constant *ConstantFoldLoadInst(const LoadInst *LI,
608                                       const DataLayout &DL) {
609   if (LI->isVolatile()) return nullptr;
610 
611   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
612     return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
613 
614   return nullptr;
615 }
616 
617 /// One of Op0/Op1 is a constant expression.
618 /// Attempt to symbolically evaluate the result of a binary operator merging
619 /// these together.  If target data info is available, it is provided as DL,
620 /// otherwise DL is null.
621 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
622                                            Constant *Op1,
623                                            const DataLayout &DL) {
624   // SROA
625 
626   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
627   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
628   // bits.
629 
630   if (Opc == Instruction::And) {
631     unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
632     APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
633     APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
634     computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
635     computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
636     if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
637       // All the bits of Op0 that the 'and' could be masking are already zero.
638       return Op0;
639     }
640     if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
641       // All the bits of Op1 that the 'and' could be masking are already zero.
642       return Op1;
643     }
644 
645     APInt KnownZero = KnownZero0 | KnownZero1;
646     APInt KnownOne = KnownOne0 & KnownOne1;
647     if ((KnownZero | KnownOne).isAllOnesValue()) {
648       return ConstantInt::get(Op0->getType(), KnownOne);
649     }
650   }
651 
652   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
653   // constant.  This happens frequently when iterating over a global array.
654   if (Opc == Instruction::Sub) {
655     GlobalValue *GV1, *GV2;
656     APInt Offs1, Offs2;
657 
658     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
659       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
660         unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
661 
662         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
663         // PtrToInt may change the bitwidth so we have convert to the right size
664         // first.
665         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
666                                                 Offs2.zextOrTrunc(OpSize));
667       }
668   }
669 
670   return nullptr;
671 }
672 
673 /// If array indices are not pointer-sized integers, explicitly cast them so
674 /// that they aren't implicitly casted by the getelementptr.
675 static Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
676                                 Type *ResultTy, const DataLayout &DL,
677                                 const TargetLibraryInfo *TLI) {
678   Type *IntPtrTy = DL.getIntPtrType(ResultTy);
679 
680   bool Any = false;
681   SmallVector<Constant*, 32> NewIdxs;
682   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
683     if ((i == 1 ||
684          !isa<StructType>(GetElementPtrInst::getIndexedType(SrcElemTy,
685              Ops.slice(1, i - 1)))) &&
686         Ops[i]->getType() != IntPtrTy) {
687       Any = true;
688       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
689                                                                       true,
690                                                                       IntPtrTy,
691                                                                       true),
692                                               Ops[i], IntPtrTy));
693     } else
694       NewIdxs.push_back(Ops[i]);
695   }
696 
697   if (!Any)
698     return nullptr;
699 
700   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], NewIdxs);
701   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
702     if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
703       C = Folded;
704   }
705 
706   return C;
707 }
708 
709 /// Strip the pointer casts, but preserve the address space information.
710 static Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
711   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
712   PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
713   Ptr = Ptr->stripPointerCasts();
714   PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
715 
716   ElemTy = NewPtrTy->getPointerElementType();
717 
718   // Preserve the address space number of the pointer.
719   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
720     NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
721     Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
722   }
723   return Ptr;
724 }
725 
726 /// If we can symbolically evaluate the GEP constant expression, do so.
727 static Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
728                                          ArrayRef<Constant *> Ops,
729                                          const DataLayout &DL,
730                                          const TargetLibraryInfo *TLI) {
731   Type *SrcElemTy = GEP->getSourceElementType();
732   Type *ResElemTy = GEP->getResultElementType();
733   Type *ResTy = GEP->getType();
734   if (!SrcElemTy->isSized())
735     return nullptr;
736 
737   if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, DL, TLI))
738     return C;
739 
740   Constant *Ptr = Ops[0];
741   if (!Ptr->getType()->isPointerTy())
742     return nullptr;
743 
744   Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
745 
746   // If this is a constant expr gep that is effectively computing an
747   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
748   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
749     if (!isa<ConstantInt>(Ops[i])) {
750 
751       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
752       // "inttoptr (sub (ptrtoint Ptr), V)"
753       if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
754         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
755         assert((!CE || CE->getType() == IntPtrTy) &&
756                "CastGEPIndices didn't canonicalize index types!");
757         if (CE && CE->getOpcode() == Instruction::Sub &&
758             CE->getOperand(0)->isNullValue()) {
759           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
760           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
761           Res = ConstantExpr::getIntToPtr(Res, ResTy);
762           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
763             Res = ConstantFoldConstantExpression(ResCE, DL, TLI);
764           return Res;
765         }
766       }
767       return nullptr;
768     }
769 
770   unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
771   APInt Offset =
772       APInt(BitWidth,
773             DL.getIndexedOffsetInType(
774                 SrcElemTy,
775                 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
776   Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
777 
778   // If this is a GEP of a GEP, fold it all into a single GEP.
779   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
780     SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
781 
782     // Do not try the incorporate the sub-GEP if some index is not a number.
783     bool AllConstantInt = true;
784     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
785       if (!isa<ConstantInt>(NestedOps[i])) {
786         AllConstantInt = false;
787         break;
788       }
789     if (!AllConstantInt)
790       break;
791 
792     Ptr = cast<Constant>(GEP->getOperand(0));
793     SrcElemTy = GEP->getSourceElementType();
794     Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
795     Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
796   }
797 
798   // If the base value for this address is a literal integer value, fold the
799   // getelementptr to the resulting integer value casted to the pointer type.
800   APInt BasePtr(BitWidth, 0);
801   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
802     if (CE->getOpcode() == Instruction::IntToPtr) {
803       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
804         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
805     }
806   }
807 
808   if (Ptr->isNullValue() || BasePtr != 0) {
809     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
810     return ConstantExpr::getIntToPtr(C, ResTy);
811   }
812 
813   // Otherwise form a regular getelementptr. Recompute the indices so that
814   // we eliminate over-indexing of the notional static type array bounds.
815   // This makes it easy to determine if the getelementptr is "inbounds".
816   // Also, this helps GlobalOpt do SROA on GlobalVariables.
817   Type *Ty = Ptr->getType();
818   assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
819   SmallVector<Constant *, 32> NewIdxs;
820 
821   do {
822     if (!Ty->isStructTy()) {
823       if (Ty->isPointerTy()) {
824         // The only pointer indexing we'll do is on the first index of the GEP.
825         if (!NewIdxs.empty())
826           break;
827 
828         Ty = SrcElemTy;
829 
830         // Only handle pointers to sized types, not pointers to functions.
831         if (!Ty->isSized())
832           return nullptr;
833       } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
834         Ty = ATy->getElementType();
835       } else {
836         // We've reached some non-indexable type.
837         break;
838       }
839 
840       // Determine which element of the array the offset points into.
841       APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
842       if (ElemSize == 0)
843         // The element size is 0. This may be [0 x Ty]*, so just use a zero
844         // index for this level and proceed to the next level to see if it can
845         // accommodate the offset.
846         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
847       else {
848         // The element size is non-zero divide the offset by the element
849         // size (rounding down), to compute the index at this level.
850         APInt NewIdx = Offset.udiv(ElemSize);
851         Offset -= NewIdx * ElemSize;
852         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
853       }
854     } else {
855       StructType *STy = cast<StructType>(Ty);
856       // If we end up with an offset that isn't valid for this struct type, we
857       // can't re-form this GEP in a regular form, so bail out. The pointer
858       // operand likely went through casts that are necessary to make the GEP
859       // sensible.
860       const StructLayout &SL = *DL.getStructLayout(STy);
861       if (Offset.uge(SL.getSizeInBytes()))
862         break;
863 
864       // Determine which field of the struct the offset points into. The
865       // getZExtValue is fine as we've already ensured that the offset is
866       // within the range representable by the StructLayout API.
867       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
868       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
869                                          ElIdx));
870       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
871       Ty = STy->getTypeAtIndex(ElIdx);
872     }
873   } while (Ty != ResElemTy);
874 
875   // If we haven't used up the entire offset by descending the static
876   // type, then the offset is pointing into the middle of an indivisible
877   // member, so we can't simplify it.
878   if (Offset != 0)
879     return nullptr;
880 
881   // Create a GEP.
882   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs);
883   assert(C->getType()->getPointerElementType() == Ty &&
884          "Computed GetElementPtr has unexpected type!");
885 
886   // If we ended up indexing a member with a type that doesn't match
887   // the type of what the original indices indexed, add a cast.
888   if (Ty != ResElemTy)
889     C = FoldBitCast(C, ResTy, DL);
890 
891   return C;
892 }
893 
894 /// Attempt to constant fold an instruction with the
895 /// specified opcode and operands.  If successful, the constant result is
896 /// returned, if not, null is returned.  Note that this function can fail when
897 /// attempting to fold instructions like loads and stores, which have no
898 /// constant expression form.
899 ///
900 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
901 /// information, due to only being passed an opcode and operands. Constant
902 /// folding using this function strips this information.
903 ///
904 static Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE,
905                                               Type *DestTy,
906                                               unsigned Opcode,
907                                               ArrayRef<Constant *> Ops,
908                                               const DataLayout &DL,
909                                               const TargetLibraryInfo *TLI) {
910   // Handle easy binops first.
911   if (Instruction::isBinaryOp(Opcode))
912     return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
913 
914   if (Instruction::isCast(Opcode))
915     return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
916 
917   if(auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
918     if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
919       return C;
920 
921     return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(),
922                                           Ops[0], Ops.slice(1));
923   }
924 
925   switch (Opcode) {
926   default: return nullptr;
927   case Instruction::ICmp:
928   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
929   case Instruction::Call:
930     if (Function *F = dyn_cast<Function>(Ops.back()))
931       if (canConstantFoldCallTo(F))
932         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
933     return nullptr;
934   case Instruction::Select:
935     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
936   case Instruction::ExtractElement:
937     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
938   case Instruction::InsertElement:
939     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
940   case Instruction::ShuffleVector:
941     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
942   }
943 }
944 
945 
946 
947 //===----------------------------------------------------------------------===//
948 // Constant Folding public APIs
949 //===----------------------------------------------------------------------===//
950 
951 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
952                                         const TargetLibraryInfo *TLI) {
953   // Handle PHI nodes quickly here...
954   if (PHINode *PN = dyn_cast<PHINode>(I)) {
955     Constant *CommonValue = nullptr;
956 
957     for (Value *Incoming : PN->incoming_values()) {
958       // If the incoming value is undef then skip it.  Note that while we could
959       // skip the value if it is equal to the phi node itself we choose not to
960       // because that would break the rule that constant folding only applies if
961       // all operands are constants.
962       if (isa<UndefValue>(Incoming))
963         continue;
964       // If the incoming value is not a constant, then give up.
965       Constant *C = dyn_cast<Constant>(Incoming);
966       if (!C)
967         return nullptr;
968       // Fold the PHI's operands.
969       if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
970         C = ConstantFoldConstantExpression(NewC, DL, TLI);
971       // If the incoming value is a different constant to
972       // the one we saw previously, then give up.
973       if (CommonValue && C != CommonValue)
974         return nullptr;
975       CommonValue = C;
976     }
977 
978 
979     // If we reach here, all incoming values are the same constant or undef.
980     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
981   }
982 
983   // Scan the operand list, checking to see if they are all constants, if so,
984   // hand off to ConstantFoldInstOperandsImpl.
985   if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
986     return nullptr;
987 
988   SmallVector<Constant *, 8> Ops;
989   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
990     Constant *Op = cast<Constant>(*i);
991     // Fold the Instruction's operands.
992     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
993       Op = ConstantFoldConstantExpression(NewCE, DL, TLI);
994 
995     Ops.push_back(Op);
996   }
997 
998   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
999     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1000                                            DL, TLI);
1001 
1002   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
1003     return ConstantFoldLoadInst(LI, DL);
1004 
1005   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
1006     return ConstantExpr::getInsertValue(
1007                                 cast<Constant>(IVI->getAggregateOperand()),
1008                                 cast<Constant>(IVI->getInsertedValueOperand()),
1009                                 IVI->getIndices());
1010   }
1011 
1012   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
1013     return ConstantExpr::getExtractValue(
1014                                     cast<Constant>(EVI->getAggregateOperand()),
1015                                     EVI->getIndices());
1016   }
1017 
1018   return ConstantFoldInstOperands(I, Ops, DL, TLI);
1019 }
1020 
1021 static Constant *
1022 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout &DL,
1023                                    const TargetLibraryInfo *TLI,
1024                                    SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
1025   SmallVector<Constant *, 8> Ops;
1026   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
1027        ++i) {
1028     Constant *NewC = cast<Constant>(*i);
1029     // Recursively fold the ConstantExpr's operands. If we have already folded
1030     // a ConstantExpr, we don't have to process it again.
1031     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
1032       if (FoldedOps.insert(NewCE).second)
1033         NewC = ConstantFoldConstantExpressionImpl(NewCE, DL, TLI, FoldedOps);
1034     }
1035     Ops.push_back(NewC);
1036   }
1037 
1038   if (CE->isCompare())
1039     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1040                                            DL, TLI);
1041 
1042   return ConstantFoldInstOperandsImpl(CE, CE->getType(), CE->getOpcode(), Ops,
1043                                       DL, TLI);
1044 }
1045 
1046 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
1047                                                const DataLayout &DL,
1048                                                const TargetLibraryInfo *TLI) {
1049   SmallPtrSet<ConstantExpr *, 4> FoldedOps;
1050   return ConstantFoldConstantExpressionImpl(CE, DL, TLI, FoldedOps);
1051 }
1052 
1053 Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1054                                          ArrayRef<Constant *> Ops,
1055                                          const DataLayout &DL,
1056                                          const TargetLibraryInfo *TLI) {
1057   return ConstantFoldInstOperandsImpl(I, I->getType(), I->getOpcode(), Ops, DL,
1058                                       TLI);
1059 }
1060 
1061 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
1062                                          ArrayRef<Constant *> Ops,
1063                                          const DataLayout &DL,
1064                                          const TargetLibraryInfo *TLI) {
1065   assert(Opcode != Instruction::GetElementPtr && "Invalid for GEPs");
1066   return ConstantFoldInstOperandsImpl(nullptr, DestTy, Opcode, Ops, DL, TLI);
1067 }
1068 
1069 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1070                                                 Constant *Ops0, Constant *Ops1,
1071                                                 const DataLayout &DL,
1072                                                 const TargetLibraryInfo *TLI) {
1073   // fold: icmp (inttoptr x), null         -> icmp x, 0
1074   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1075   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1076   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1077   //
1078   // FIXME: The following comment is out of data and the DataLayout is here now.
1079   // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1080   // around to know if bit truncation is happening.
1081   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1082     if (Ops1->isNullValue()) {
1083       if (CE0->getOpcode() == Instruction::IntToPtr) {
1084         Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1085         // Convert the integer value to the right size to ensure we get the
1086         // proper extension or truncation.
1087         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1088                                                    IntPtrTy, false);
1089         Constant *Null = Constant::getNullValue(C->getType());
1090         return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1091       }
1092 
1093       // Only do this transformation if the int is intptrty in size, otherwise
1094       // there is a truncation or extension that we aren't modeling.
1095       if (CE0->getOpcode() == Instruction::PtrToInt) {
1096         Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1097         if (CE0->getType() == IntPtrTy) {
1098           Constant *C = CE0->getOperand(0);
1099           Constant *Null = Constant::getNullValue(C->getType());
1100           return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1101         }
1102       }
1103     }
1104 
1105     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1106       if (CE0->getOpcode() == CE1->getOpcode()) {
1107         if (CE0->getOpcode() == Instruction::IntToPtr) {
1108           Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1109 
1110           // Convert the integer value to the right size to ensure we get the
1111           // proper extension or truncation.
1112           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1113                                                       IntPtrTy, false);
1114           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1115                                                       IntPtrTy, false);
1116           return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1117         }
1118 
1119         // Only do this transformation if the int is intptrty in size, otherwise
1120         // there is a truncation or extension that we aren't modeling.
1121         if (CE0->getOpcode() == Instruction::PtrToInt) {
1122           Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1123           if (CE0->getType() == IntPtrTy &&
1124               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1125             return ConstantFoldCompareInstOperands(
1126                 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1127           }
1128         }
1129       }
1130     }
1131 
1132     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1133     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1134     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1135         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1136       Constant *LHS = ConstantFoldCompareInstOperands(
1137           Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1138       Constant *RHS = ConstantFoldCompareInstOperands(
1139           Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1140       unsigned OpC =
1141         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1142       return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1143     }
1144   }
1145 
1146   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1147 }
1148 
1149 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1150                                              Constant *RHS,
1151                                              const DataLayout &DL) {
1152   assert(Instruction::isBinaryOp(Opcode));
1153   if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1154     if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1155       return C;
1156 
1157   return ConstantExpr::get(Opcode, LHS, RHS);
1158 }
1159 
1160 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1161                                         Type *DestTy, const DataLayout &DL) {
1162   assert(Instruction::isCast(Opcode));
1163   switch (Opcode) {
1164   default:
1165     llvm_unreachable("Missing case");
1166   case Instruction::PtrToInt:
1167     // If the input is a inttoptr, eliminate the pair.  This requires knowing
1168     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1169     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1170       if (CE->getOpcode() == Instruction::IntToPtr) {
1171         Constant *Input = CE->getOperand(0);
1172         unsigned InWidth = Input->getType()->getScalarSizeInBits();
1173         unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1174         if (PtrWidth < InWidth) {
1175           Constant *Mask =
1176             ConstantInt::get(CE->getContext(),
1177                              APInt::getLowBitsSet(InWidth, PtrWidth));
1178           Input = ConstantExpr::getAnd(Input, Mask);
1179         }
1180         // Do a zext or trunc to get to the dest size.
1181         return ConstantExpr::getIntegerCast(Input, DestTy, false);
1182       }
1183     }
1184     return ConstantExpr::getCast(Opcode, C, DestTy);
1185   case Instruction::IntToPtr:
1186     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1187     // the int size is >= the ptr size and the address spaces are the same.
1188     // This requires knowing the width of a pointer, so it can't be done in
1189     // ConstantExpr::getCast.
1190     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1191       if (CE->getOpcode() == Instruction::PtrToInt) {
1192         Constant *SrcPtr = CE->getOperand(0);
1193         unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1194         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1195 
1196         if (MidIntSize >= SrcPtrSize) {
1197           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1198           if (SrcAS == DestTy->getPointerAddressSpace())
1199             return FoldBitCast(CE->getOperand(0), DestTy, DL);
1200         }
1201       }
1202     }
1203 
1204     return ConstantExpr::getCast(Opcode, C, DestTy);
1205   case Instruction::Trunc:
1206   case Instruction::ZExt:
1207   case Instruction::SExt:
1208   case Instruction::FPTrunc:
1209   case Instruction::FPExt:
1210   case Instruction::UIToFP:
1211   case Instruction::SIToFP:
1212   case Instruction::FPToUI:
1213   case Instruction::FPToSI:
1214   case Instruction::AddrSpaceCast:
1215       return ConstantExpr::getCast(Opcode, C, DestTy);
1216   case Instruction::BitCast:
1217     return FoldBitCast(C, DestTy, DL);
1218   }
1219 }
1220 
1221 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1222                                                        ConstantExpr *CE) {
1223   if (!CE->getOperand(1)->isNullValue())
1224     return nullptr;  // Do not allow stepping over the value!
1225 
1226   // Loop over all of the operands, tracking down which value we are
1227   // addressing.
1228   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1229     C = C->getAggregateElement(CE->getOperand(i));
1230     if (!C)
1231       return nullptr;
1232   }
1233   return C;
1234 }
1235 
1236 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1237                                                   ArrayRef<Constant*> Indices) {
1238   // Loop over all of the operands, tracking down which value we are
1239   // addressing.
1240   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1241     C = C->getAggregateElement(Indices[i]);
1242     if (!C)
1243       return nullptr;
1244   }
1245   return C;
1246 }
1247 
1248 
1249 //===----------------------------------------------------------------------===//
1250 //  Constant Folding for Calls
1251 //
1252 
1253 bool llvm::canConstantFoldCallTo(const Function *F) {
1254   switch (F->getIntrinsicID()) {
1255   case Intrinsic::fabs:
1256   case Intrinsic::minnum:
1257   case Intrinsic::maxnum:
1258   case Intrinsic::log:
1259   case Intrinsic::log2:
1260   case Intrinsic::log10:
1261   case Intrinsic::exp:
1262   case Intrinsic::exp2:
1263   case Intrinsic::floor:
1264   case Intrinsic::ceil:
1265   case Intrinsic::sqrt:
1266   case Intrinsic::sin:
1267   case Intrinsic::cos:
1268   case Intrinsic::trunc:
1269   case Intrinsic::rint:
1270   case Intrinsic::nearbyint:
1271   case Intrinsic::pow:
1272   case Intrinsic::powi:
1273   case Intrinsic::bswap:
1274   case Intrinsic::ctpop:
1275   case Intrinsic::ctlz:
1276   case Intrinsic::cttz:
1277   case Intrinsic::fma:
1278   case Intrinsic::fmuladd:
1279   case Intrinsic::copysign:
1280   case Intrinsic::round:
1281   case Intrinsic::sadd_with_overflow:
1282   case Intrinsic::uadd_with_overflow:
1283   case Intrinsic::ssub_with_overflow:
1284   case Intrinsic::usub_with_overflow:
1285   case Intrinsic::smul_with_overflow:
1286   case Intrinsic::umul_with_overflow:
1287   case Intrinsic::convert_from_fp16:
1288   case Intrinsic::convert_to_fp16:
1289   case Intrinsic::bitreverse:
1290   case Intrinsic::x86_sse_cvtss2si:
1291   case Intrinsic::x86_sse_cvtss2si64:
1292   case Intrinsic::x86_sse_cvttss2si:
1293   case Intrinsic::x86_sse_cvttss2si64:
1294   case Intrinsic::x86_sse2_cvtsd2si:
1295   case Intrinsic::x86_sse2_cvtsd2si64:
1296   case Intrinsic::x86_sse2_cvttsd2si:
1297   case Intrinsic::x86_sse2_cvttsd2si64:
1298     return true;
1299   default:
1300     return false;
1301   case 0: break;
1302   }
1303 
1304   if (!F->hasName())
1305     return false;
1306   StringRef Name = F->getName();
1307 
1308   // In these cases, the check of the length is required.  We don't want to
1309   // return true for a name like "cos\0blah" which strcmp would return equal to
1310   // "cos", but has length 8.
1311   switch (Name[0]) {
1312   default:
1313     return false;
1314   case 'a':
1315     return Name == "acos" || Name == "asin" || Name == "atan" ||
1316            Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1317            Name == "atanf" || Name == "atan2f";
1318   case 'c':
1319     return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1320            Name == "ceilf" || Name == "cosf" || Name == "coshf";
1321   case 'e':
1322     return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
1323   case 'f':
1324     return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1325            Name == "fabsf" || Name == "floorf" || Name == "fmodf";
1326   case 'l':
1327     return Name == "log" || Name == "log10" || Name == "logf" ||
1328            Name == "log10f";
1329   case 'p':
1330     return Name == "pow" || Name == "powf";
1331   case 's':
1332     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1333            Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
1334   case 't':
1335     return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
1336   }
1337 }
1338 
1339 static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1340   if (Ty->isHalfTy()) {
1341     APFloat APF(V);
1342     bool unused;
1343     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1344     return ConstantFP::get(Ty->getContext(), APF);
1345   }
1346   if (Ty->isFloatTy())
1347     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1348   if (Ty->isDoubleTy())
1349     return ConstantFP::get(Ty->getContext(), APFloat(V));
1350   llvm_unreachable("Can only constant fold half/float/double");
1351 
1352 }
1353 
1354 namespace {
1355 /// Clear the floating-point exception state.
1356 static inline void llvm_fenv_clearexcept() {
1357 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1358   feclearexcept(FE_ALL_EXCEPT);
1359 #endif
1360   errno = 0;
1361 }
1362 
1363 /// Test if a floating-point exception was raised.
1364 static inline bool llvm_fenv_testexcept() {
1365   int errno_val = errno;
1366   if (errno_val == ERANGE || errno_val == EDOM)
1367     return true;
1368 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1369   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1370     return true;
1371 #endif
1372   return false;
1373 }
1374 } // End namespace
1375 
1376 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1377                                 Type *Ty) {
1378   llvm_fenv_clearexcept();
1379   V = NativeFP(V);
1380   if (llvm_fenv_testexcept()) {
1381     llvm_fenv_clearexcept();
1382     return nullptr;
1383   }
1384 
1385   return GetConstantFoldFPValue(V, Ty);
1386 }
1387 
1388 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1389                                       double V, double W, Type *Ty) {
1390   llvm_fenv_clearexcept();
1391   V = NativeFP(V, W);
1392   if (llvm_fenv_testexcept()) {
1393     llvm_fenv_clearexcept();
1394     return nullptr;
1395   }
1396 
1397   return GetConstantFoldFPValue(V, Ty);
1398 }
1399 
1400 /// Attempt to fold an SSE floating point to integer conversion of a constant
1401 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1402 /// used (toward nearest, ties to even). This matches the behavior of the
1403 /// non-truncating SSE instructions in the default rounding mode. The desired
1404 /// integer type Ty is used to select how many bits are available for the
1405 /// result. Returns null if the conversion cannot be performed, otherwise
1406 /// returns the Constant value resulting from the conversion.
1407 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1408                                           bool roundTowardZero, Type *Ty) {
1409   // All of these conversion intrinsics form an integer of at most 64bits.
1410   unsigned ResultWidth = Ty->getIntegerBitWidth();
1411   assert(ResultWidth <= 64 &&
1412          "Can only constant fold conversions to 64 and 32 bit ints");
1413 
1414   uint64_t UIntVal;
1415   bool isExact = false;
1416   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1417                                               : APFloat::rmNearestTiesToEven;
1418   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1419                                                   /*isSigned=*/true, mode,
1420                                                   &isExact);
1421   if (status != APFloat::opOK && status != APFloat::opInexact)
1422     return nullptr;
1423   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1424 }
1425 
1426 static double getValueAsDouble(ConstantFP *Op) {
1427   Type *Ty = Op->getType();
1428 
1429   if (Ty->isFloatTy())
1430     return Op->getValueAPF().convertToFloat();
1431 
1432   if (Ty->isDoubleTy())
1433     return Op->getValueAPF().convertToDouble();
1434 
1435   bool unused;
1436   APFloat APF = Op->getValueAPF();
1437   APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1438   return APF.convertToDouble();
1439 }
1440 
1441 static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1442                                         Type *Ty, ArrayRef<Constant *> Operands,
1443                                         const TargetLibraryInfo *TLI) {
1444   if (Operands.size() == 1) {
1445     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1446       if (IntrinsicID == Intrinsic::convert_to_fp16) {
1447         APFloat Val(Op->getValueAPF());
1448 
1449         bool lost = false;
1450         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1451 
1452         return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1453       }
1454 
1455       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1456         return nullptr;
1457 
1458       if (IntrinsicID == Intrinsic::round) {
1459         APFloat V = Op->getValueAPF();
1460         V.roundToIntegral(APFloat::rmNearestTiesToAway);
1461         return ConstantFP::get(Ty->getContext(), V);
1462       }
1463 
1464       if (IntrinsicID == Intrinsic::floor) {
1465         APFloat V = Op->getValueAPF();
1466         V.roundToIntegral(APFloat::rmTowardNegative);
1467         return ConstantFP::get(Ty->getContext(), V);
1468       }
1469 
1470       if (IntrinsicID == Intrinsic::ceil) {
1471         APFloat V = Op->getValueAPF();
1472         V.roundToIntegral(APFloat::rmTowardPositive);
1473         return ConstantFP::get(Ty->getContext(), V);
1474       }
1475 
1476       if (IntrinsicID == Intrinsic::trunc) {
1477         APFloat V = Op->getValueAPF();
1478         V.roundToIntegral(APFloat::rmTowardZero);
1479         return ConstantFP::get(Ty->getContext(), V);
1480       }
1481 
1482       if (IntrinsicID == Intrinsic::rint) {
1483         APFloat V = Op->getValueAPF();
1484         V.roundToIntegral(APFloat::rmNearestTiesToEven);
1485         return ConstantFP::get(Ty->getContext(), V);
1486       }
1487 
1488       if (IntrinsicID == Intrinsic::nearbyint) {
1489         APFloat V = Op->getValueAPF();
1490         V.roundToIntegral(APFloat::rmNearestTiesToEven);
1491         return ConstantFP::get(Ty->getContext(), V);
1492       }
1493 
1494       /// We only fold functions with finite arguments. Folding NaN and inf is
1495       /// likely to be aborted with an exception anyway, and some host libms
1496       /// have known errors raising exceptions.
1497       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1498         return nullptr;
1499 
1500       /// Currently APFloat versions of these functions do not exist, so we use
1501       /// the host native double versions.  Float versions are not called
1502       /// directly but for all these it is true (float)(f((double)arg)) ==
1503       /// f(arg).  Long double not supported yet.
1504       double V = getValueAsDouble(Op);
1505 
1506       switch (IntrinsicID) {
1507         default: break;
1508         case Intrinsic::fabs:
1509           return ConstantFoldFP(fabs, V, Ty);
1510         case Intrinsic::log2:
1511           return ConstantFoldFP(Log2, V, Ty);
1512         case Intrinsic::log:
1513           return ConstantFoldFP(log, V, Ty);
1514         case Intrinsic::log10:
1515           return ConstantFoldFP(log10, V, Ty);
1516         case Intrinsic::exp:
1517           return ConstantFoldFP(exp, V, Ty);
1518         case Intrinsic::exp2:
1519           return ConstantFoldFP(exp2, V, Ty);
1520         case Intrinsic::sin:
1521           return ConstantFoldFP(sin, V, Ty);
1522         case Intrinsic::cos:
1523           return ConstantFoldFP(cos, V, Ty);
1524       }
1525 
1526       if (!TLI)
1527         return nullptr;
1528 
1529       switch (Name[0]) {
1530       case 'a':
1531         if ((Name == "acos" && TLI->has(LibFunc::acos)) ||
1532             (Name == "acosf" && TLI->has(LibFunc::acosf)))
1533           return ConstantFoldFP(acos, V, Ty);
1534         else if ((Name == "asin" && TLI->has(LibFunc::asin)) ||
1535                  (Name == "asinf" && TLI->has(LibFunc::asinf)))
1536           return ConstantFoldFP(asin, V, Ty);
1537         else if ((Name == "atan" && TLI->has(LibFunc::atan)) ||
1538                  (Name == "atanf" && TLI->has(LibFunc::atanf)))
1539           return ConstantFoldFP(atan, V, Ty);
1540         break;
1541       case 'c':
1542         if ((Name == "ceil" && TLI->has(LibFunc::ceil)) ||
1543             (Name == "ceilf" && TLI->has(LibFunc::ceilf)))
1544           return ConstantFoldFP(ceil, V, Ty);
1545         else if ((Name == "cos" && TLI->has(LibFunc::cos)) ||
1546                  (Name == "cosf" && TLI->has(LibFunc::cosf)))
1547           return ConstantFoldFP(cos, V, Ty);
1548         else if ((Name == "cosh" && TLI->has(LibFunc::cosh)) ||
1549                  (Name == "coshf" && TLI->has(LibFunc::coshf)))
1550           return ConstantFoldFP(cosh, V, Ty);
1551         break;
1552       case 'e':
1553         if ((Name == "exp" && TLI->has(LibFunc::exp)) ||
1554             (Name == "expf" && TLI->has(LibFunc::expf)))
1555           return ConstantFoldFP(exp, V, Ty);
1556         if ((Name == "exp2" && TLI->has(LibFunc::exp2)) ||
1557             (Name == "exp2f" && TLI->has(LibFunc::exp2f)))
1558           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1559           // C99 library.
1560           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1561         break;
1562       case 'f':
1563         if ((Name == "fabs" && TLI->has(LibFunc::fabs)) ||
1564             (Name == "fabsf" && TLI->has(LibFunc::fabsf)))
1565           return ConstantFoldFP(fabs, V, Ty);
1566         else if ((Name == "floor" && TLI->has(LibFunc::floor)) ||
1567                  (Name == "floorf" && TLI->has(LibFunc::floorf)))
1568           return ConstantFoldFP(floor, V, Ty);
1569         break;
1570       case 'l':
1571         if ((Name == "log" && V > 0 && TLI->has(LibFunc::log)) ||
1572             (Name == "logf" && V > 0 && TLI->has(LibFunc::logf)))
1573           return ConstantFoldFP(log, V, Ty);
1574         else if ((Name == "log10" && V > 0 && TLI->has(LibFunc::log10)) ||
1575                  (Name == "log10f" && V > 0 && TLI->has(LibFunc::log10f)))
1576           return ConstantFoldFP(log10, V, Ty);
1577         else if (IntrinsicID == Intrinsic::sqrt &&
1578                  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1579           if (V >= -0.0)
1580             return ConstantFoldFP(sqrt, V, Ty);
1581           else {
1582             // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1583             // all guarantee or favor returning NaN - the square root of a
1584             // negative number is not defined for the LLVM sqrt intrinsic.
1585             // This is because the intrinsic should only be emitted in place of
1586             // libm's sqrt function when using "no-nans-fp-math".
1587             return UndefValue::get(Ty);
1588           }
1589         }
1590         break;
1591       case 's':
1592         if ((Name == "sin" && TLI->has(LibFunc::sin)) ||
1593             (Name == "sinf" && TLI->has(LibFunc::sinf)))
1594           return ConstantFoldFP(sin, V, Ty);
1595         else if ((Name == "sinh" && TLI->has(LibFunc::sinh)) ||
1596                  (Name == "sinhf" && TLI->has(LibFunc::sinhf)))
1597           return ConstantFoldFP(sinh, V, Ty);
1598         else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt)) ||
1599                  (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf)))
1600           return ConstantFoldFP(sqrt, V, Ty);
1601         break;
1602       case 't':
1603         if ((Name == "tan" && TLI->has(LibFunc::tan)) ||
1604             (Name == "tanf" && TLI->has(LibFunc::tanf)))
1605           return ConstantFoldFP(tan, V, Ty);
1606         else if ((Name == "tanh" && TLI->has(LibFunc::tanh)) ||
1607                  (Name == "tanhf" && TLI->has(LibFunc::tanhf)))
1608           return ConstantFoldFP(tanh, V, Ty);
1609         break;
1610       default:
1611         break;
1612       }
1613       return nullptr;
1614     }
1615 
1616     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1617       switch (IntrinsicID) {
1618       case Intrinsic::bswap:
1619         return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1620       case Intrinsic::ctpop:
1621         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1622       case Intrinsic::bitreverse:
1623         return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1624       case Intrinsic::convert_from_fp16: {
1625         APFloat Val(APFloat::IEEEhalf, Op->getValue());
1626 
1627         bool lost = false;
1628         APFloat::opStatus status = Val.convert(
1629             Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
1630 
1631         // Conversion is always precise.
1632         (void)status;
1633         assert(status == APFloat::opOK && !lost &&
1634                "Precision lost during fp16 constfolding");
1635 
1636         return ConstantFP::get(Ty->getContext(), Val);
1637       }
1638       default:
1639         return nullptr;
1640       }
1641     }
1642 
1643     // Support ConstantVector in case we have an Undef in the top.
1644     if (isa<ConstantVector>(Operands[0]) ||
1645         isa<ConstantDataVector>(Operands[0])) {
1646       Constant *Op = cast<Constant>(Operands[0]);
1647       switch (IntrinsicID) {
1648       default: break;
1649       case Intrinsic::x86_sse_cvtss2si:
1650       case Intrinsic::x86_sse_cvtss2si64:
1651       case Intrinsic::x86_sse2_cvtsd2si:
1652       case Intrinsic::x86_sse2_cvtsd2si64:
1653         if (ConstantFP *FPOp =
1654               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1655           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1656                                           /*roundTowardZero=*/false, Ty);
1657       case Intrinsic::x86_sse_cvttss2si:
1658       case Intrinsic::x86_sse_cvttss2si64:
1659       case Intrinsic::x86_sse2_cvttsd2si:
1660       case Intrinsic::x86_sse2_cvttsd2si64:
1661         if (ConstantFP *FPOp =
1662               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1663           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1664                                           /*roundTowardZero=*/true, Ty);
1665       }
1666     }
1667 
1668     if (isa<UndefValue>(Operands[0])) {
1669       if (IntrinsicID == Intrinsic::bswap)
1670         return Operands[0];
1671       return nullptr;
1672     }
1673 
1674     return nullptr;
1675   }
1676 
1677   if (Operands.size() == 2) {
1678     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1679       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1680         return nullptr;
1681       double Op1V = getValueAsDouble(Op1);
1682 
1683       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1684         if (Op2->getType() != Op1->getType())
1685           return nullptr;
1686 
1687         double Op2V = getValueAsDouble(Op2);
1688         if (IntrinsicID == Intrinsic::pow) {
1689           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1690         }
1691         if (IntrinsicID == Intrinsic::copysign) {
1692           APFloat V1 = Op1->getValueAPF();
1693           const APFloat &V2 = Op2->getValueAPF();
1694           V1.copySign(V2);
1695           return ConstantFP::get(Ty->getContext(), V1);
1696         }
1697 
1698         if (IntrinsicID == Intrinsic::minnum) {
1699           const APFloat &C1 = Op1->getValueAPF();
1700           const APFloat &C2 = Op2->getValueAPF();
1701           return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1702         }
1703 
1704         if (IntrinsicID == Intrinsic::maxnum) {
1705           const APFloat &C1 = Op1->getValueAPF();
1706           const APFloat &C2 = Op2->getValueAPF();
1707           return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1708         }
1709 
1710         if (!TLI)
1711           return nullptr;
1712         if ((Name == "pow" && TLI->has(LibFunc::pow)) ||
1713             (Name == "powf" && TLI->has(LibFunc::powf)))
1714           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1715         if ((Name == "fmod" && TLI->has(LibFunc::fmod)) ||
1716             (Name == "fmodf" && TLI->has(LibFunc::fmodf)))
1717           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1718         if ((Name == "atan2" && TLI->has(LibFunc::atan2)) ||
1719             (Name == "atan2f" && TLI->has(LibFunc::atan2f)))
1720           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1721       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1722         if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1723           return ConstantFP::get(Ty->getContext(),
1724                                  APFloat((float)std::pow((float)Op1V,
1725                                                  (int)Op2C->getZExtValue())));
1726         if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1727           return ConstantFP::get(Ty->getContext(),
1728                                  APFloat((float)std::pow((float)Op1V,
1729                                                  (int)Op2C->getZExtValue())));
1730         if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1731           return ConstantFP::get(Ty->getContext(),
1732                                  APFloat((double)std::pow((double)Op1V,
1733                                                    (int)Op2C->getZExtValue())));
1734       }
1735       return nullptr;
1736     }
1737 
1738     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1739       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1740         switch (IntrinsicID) {
1741         default: break;
1742         case Intrinsic::sadd_with_overflow:
1743         case Intrinsic::uadd_with_overflow:
1744         case Intrinsic::ssub_with_overflow:
1745         case Intrinsic::usub_with_overflow:
1746         case Intrinsic::smul_with_overflow:
1747         case Intrinsic::umul_with_overflow: {
1748           APInt Res;
1749           bool Overflow;
1750           switch (IntrinsicID) {
1751           default: llvm_unreachable("Invalid case");
1752           case Intrinsic::sadd_with_overflow:
1753             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1754             break;
1755           case Intrinsic::uadd_with_overflow:
1756             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1757             break;
1758           case Intrinsic::ssub_with_overflow:
1759             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1760             break;
1761           case Intrinsic::usub_with_overflow:
1762             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1763             break;
1764           case Intrinsic::smul_with_overflow:
1765             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1766             break;
1767           case Intrinsic::umul_with_overflow:
1768             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1769             break;
1770           }
1771           Constant *Ops[] = {
1772             ConstantInt::get(Ty->getContext(), Res),
1773             ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1774           };
1775           return ConstantStruct::get(cast<StructType>(Ty), Ops);
1776         }
1777         case Intrinsic::cttz:
1778           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1779             return UndefValue::get(Ty);
1780           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1781         case Intrinsic::ctlz:
1782           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1783             return UndefValue::get(Ty);
1784           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1785         }
1786       }
1787 
1788       return nullptr;
1789     }
1790     return nullptr;
1791   }
1792 
1793   if (Operands.size() != 3)
1794     return nullptr;
1795 
1796   if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1797     if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1798       if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1799         switch (IntrinsicID) {
1800         default: break;
1801         case Intrinsic::fma:
1802         case Intrinsic::fmuladd: {
1803           APFloat V = Op1->getValueAPF();
1804           APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1805                                                    Op3->getValueAPF(),
1806                                                    APFloat::rmNearestTiesToEven);
1807           if (s != APFloat::opInvalidOp)
1808             return ConstantFP::get(Ty->getContext(), V);
1809 
1810           return nullptr;
1811         }
1812         }
1813       }
1814     }
1815   }
1816 
1817   return nullptr;
1818 }
1819 
1820 static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1821                                         VectorType *VTy,
1822                                         ArrayRef<Constant *> Operands,
1823                                         const TargetLibraryInfo *TLI) {
1824   SmallVector<Constant *, 4> Result(VTy->getNumElements());
1825   SmallVector<Constant *, 4> Lane(Operands.size());
1826   Type *Ty = VTy->getElementType();
1827 
1828   for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1829     // Gather a column of constants.
1830     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1831       Constant *Agg = Operands[J]->getAggregateElement(I);
1832       if (!Agg)
1833         return nullptr;
1834 
1835       Lane[J] = Agg;
1836     }
1837 
1838     // Use the regular scalar folding to simplify this column.
1839     Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1840     if (!Folded)
1841       return nullptr;
1842     Result[I] = Folded;
1843   }
1844 
1845   return ConstantVector::get(Result);
1846 }
1847 
1848 Constant *
1849 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1850                        const TargetLibraryInfo *TLI) {
1851   if (!F->hasName())
1852     return nullptr;
1853   StringRef Name = F->getName();
1854 
1855   Type *Ty = F->getReturnType();
1856 
1857   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1858     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1859 
1860   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1861 }
1862