1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines routines for folding instructions into constants.
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
17 //===----------------------------------------------------------------------===//
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/ValueTracking.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FEnv.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Target/TargetLibraryInfo.h"
41 //===----------------------------------------------------------------------===//
42 // Constant Folding internal helper functions
43 //===----------------------------------------------------------------------===//
45 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
46 /// DataLayout. This always returns a non-null constant, but it may be a
47 /// ConstantExpr if unfoldable.
48 static Constant *FoldBitCast(Constant *C, Type *DestTy,
49 const DataLayout &TD) {
50 // Catch the obvious splat cases.
51 if (C->isNullValue() && !DestTy->isX86_MMXTy())
52 return Constant::getNullValue(DestTy);
53 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
54 return Constant::getAllOnesValue(DestTy);
56 // Handle a vector->integer cast.
57 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
58 VectorType *VTy = dyn_cast<VectorType>(C->getType());
60 return ConstantExpr::getBitCast(C, DestTy);
62 unsigned NumSrcElts = VTy->getNumElements();
63 Type *SrcEltTy = VTy->getElementType();
65 // If the vector is a vector of floating point, convert it to vector of int
66 // to simplify things.
67 if (SrcEltTy->isFloatingPointTy()) {
68 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
70 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
71 // Ask IR to do the conversion now that #elts line up.
72 C = ConstantExpr::getBitCast(C, SrcIVTy);
75 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
77 return ConstantExpr::getBitCast(C, DestTy);
79 // Now that we know that the input value is a vector of integers, just shift
80 // and insert them into our result.
81 unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
82 APInt Result(IT->getBitWidth(), 0);
83 for (unsigned i = 0; i != NumSrcElts; ++i) {
85 if (TD.isLittleEndian())
86 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
88 Result |= CDV->getElementAsInteger(i);
91 return ConstantInt::get(IT, Result);
94 // The code below only handles casts to vectors currently.
95 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
97 return ConstantExpr::getBitCast(C, DestTy);
99 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
100 // vector so the code below can handle it uniformly.
101 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
102 Constant *Ops = C; // don't take the address of C!
103 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
106 // If this is a bitcast from constant vector -> vector, fold it.
107 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
108 return ConstantExpr::getBitCast(C, DestTy);
110 // If the element types match, IR can fold it.
111 unsigned NumDstElt = DestVTy->getNumElements();
112 unsigned NumSrcElt = C->getType()->getVectorNumElements();
113 if (NumDstElt == NumSrcElt)
114 return ConstantExpr::getBitCast(C, DestTy);
116 Type *SrcEltTy = C->getType()->getVectorElementType();
117 Type *DstEltTy = DestVTy->getElementType();
119 // Otherwise, we're changing the number of elements in a vector, which
120 // requires endianness information to do the right thing. For example,
121 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
122 // folds to (little endian):
123 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
124 // and to (big endian):
125 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
127 // First thing is first. We only want to think about integer here, so if
128 // we have something in FP form, recast it as integer.
129 if (DstEltTy->isFloatingPointTy()) {
130 // Fold to an vector of integers with same size as our FP type.
131 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
133 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
134 // Recursively handle this integer conversion, if possible.
135 C = FoldBitCast(C, DestIVTy, TD);
137 // Finally, IR can handle this now that #elts line up.
138 return ConstantExpr::getBitCast(C, DestTy);
141 // Okay, we know the destination is integer, if the input is FP, convert
142 // it to integer first.
143 if (SrcEltTy->isFloatingPointTy()) {
144 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
146 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
147 // Ask IR to do the conversion now that #elts line up.
148 C = ConstantExpr::getBitCast(C, SrcIVTy);
149 // If IR wasn't able to fold it, bail out.
150 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
151 !isa<ConstantDataVector>(C))
155 // Now we know that the input and output vectors are both integer vectors
156 // of the same size, and that their #elements is not the same. Do the
157 // conversion here, which depends on whether the input or output has
159 bool isLittleEndian = TD.isLittleEndian();
161 SmallVector<Constant*, 32> Result;
162 if (NumDstElt < NumSrcElt) {
163 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
164 Constant *Zero = Constant::getNullValue(DstEltTy);
165 unsigned Ratio = NumSrcElt/NumDstElt;
166 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
168 for (unsigned i = 0; i != NumDstElt; ++i) {
169 // Build each element of the result.
170 Constant *Elt = Zero;
171 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
172 for (unsigned j = 0; j != Ratio; ++j) {
173 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
174 if (!Src) // Reject constantexpr elements.
175 return ConstantExpr::getBitCast(C, DestTy);
177 // Zero extend the element to the right size.
178 Src = ConstantExpr::getZExt(Src, Elt->getType());
180 // Shift it to the right place, depending on endianness.
181 Src = ConstantExpr::getShl(Src,
182 ConstantInt::get(Src->getType(), ShiftAmt));
183 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
186 Elt = ConstantExpr::getOr(Elt, Src);
188 Result.push_back(Elt);
190 return ConstantVector::get(Result);
193 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
194 unsigned Ratio = NumDstElt/NumSrcElt;
195 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
197 // Loop over each source value, expanding into multiple results.
198 for (unsigned i = 0; i != NumSrcElt; ++i) {
199 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
200 if (!Src) // Reject constantexpr elements.
201 return ConstantExpr::getBitCast(C, DestTy);
203 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
204 for (unsigned j = 0; j != Ratio; ++j) {
205 // Shift the piece of the value into the right place, depending on
207 Constant *Elt = ConstantExpr::getLShr(Src,
208 ConstantInt::get(Src->getType(), ShiftAmt));
209 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
211 // Truncate and remember this piece.
212 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
216 return ConstantVector::get(Result);
220 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
221 /// from a global, return the global and the constant. Because of
222 /// constantexprs, this function is recursive.
223 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
224 APInt &Offset, const DataLayout &TD) {
225 // Trivial case, constant is the global.
226 if ((GV = dyn_cast<GlobalValue>(C))) {
227 Offset.clearAllBits();
231 // Otherwise, if this isn't a constant expr, bail out.
232 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
233 if (!CE) return false;
235 // Look through ptr->int and ptr->ptr casts.
236 if (CE->getOpcode() == Instruction::PtrToInt ||
237 CE->getOpcode() == Instruction::BitCast)
238 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
240 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
241 if (GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
242 // If the base isn't a global+constant, we aren't either.
243 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
246 // Otherwise, add any offset that our operands provide.
247 return GEP->accumulateConstantOffset(TD, Offset);
253 /// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
254 /// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
255 /// pointer to copy results into and BytesLeft is the number of bytes left in
256 /// the CurPtr buffer. TD is the target data.
257 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
258 unsigned char *CurPtr, unsigned BytesLeft,
259 const DataLayout &TD) {
260 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
261 "Out of range access");
263 // If this element is zero or undefined, we can just return since *CurPtr is
265 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
268 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
269 if (CI->getBitWidth() > 64 ||
270 (CI->getBitWidth() & 7) != 0)
273 uint64_t Val = CI->getZExtValue();
274 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
276 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
278 if (!TD.isLittleEndian())
279 n = IntBytes - n - 1;
280 CurPtr[i] = (unsigned char)(Val >> (n * 8));
286 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
287 if (CFP->getType()->isDoubleTy()) {
288 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
289 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
291 if (CFP->getType()->isFloatTy()){
292 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
293 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
295 if (CFP->getType()->isHalfTy()){
296 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
297 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
302 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
303 const StructLayout *SL = TD.getStructLayout(CS->getType());
304 unsigned Index = SL->getElementContainingOffset(ByteOffset);
305 uint64_t CurEltOffset = SL->getElementOffset(Index);
306 ByteOffset -= CurEltOffset;
309 // If the element access is to the element itself and not to tail padding,
310 // read the bytes from the element.
311 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
313 if (ByteOffset < EltSize &&
314 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
320 // Check to see if we read from the last struct element, if so we're done.
321 if (Index == CS->getType()->getNumElements())
324 // If we read all of the bytes we needed from this element we're done.
325 uint64_t NextEltOffset = SL->getElementOffset(Index);
327 if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
330 // Move to the next element of the struct.
331 CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
332 BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
334 CurEltOffset = NextEltOffset;
339 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
340 isa<ConstantDataSequential>(C)) {
341 Type *EltTy = cast<SequentialType>(C->getType())->getElementType();
342 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
343 uint64_t Index = ByteOffset / EltSize;
344 uint64_t Offset = ByteOffset - Index * EltSize;
346 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
347 NumElts = AT->getNumElements();
349 NumElts = cast<VectorType>(C->getType())->getNumElements();
351 for (; Index != NumElts; ++Index) {
352 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
356 uint64_t BytesWritten = EltSize - Offset;
357 assert(BytesWritten <= EltSize && "Not indexing into this element?");
358 if (BytesWritten >= BytesLeft)
362 BytesLeft -= BytesWritten;
363 CurPtr += BytesWritten;
368 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
369 if (CE->getOpcode() == Instruction::IntToPtr &&
370 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext())) {
371 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
376 // Otherwise, unknown initializer type.
380 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
381 const DataLayout &TD) {
382 Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
383 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
385 // If this isn't an integer load we can't fold it directly.
387 // If this is a float/double load, we can try folding it as an int32/64 load
388 // and then bitcast the result. This can be useful for union cases. Note
389 // that address spaces don't matter here since we're not going to result in
390 // an actual new load.
392 if (LoadTy->isHalfTy())
393 MapTy = Type::getInt16PtrTy(C->getContext());
394 else if (LoadTy->isFloatTy())
395 MapTy = Type::getInt32PtrTy(C->getContext());
396 else if (LoadTy->isDoubleTy())
397 MapTy = Type::getInt64PtrTy(C->getContext());
398 else if (LoadTy->isVectorTy()) {
399 MapTy = IntegerType::get(C->getContext(),
400 TD.getTypeAllocSizeInBits(LoadTy));
401 MapTy = PointerType::getUnqual(MapTy);
405 C = FoldBitCast(C, MapTy, TD);
406 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
407 return FoldBitCast(Res, LoadTy, TD);
411 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
412 if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
415 APInt Offset(TD.getPointerSizeInBits(), 0);
416 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
419 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
420 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
421 !GV->getInitializer()->getType()->isSized())
424 // If we're loading off the beginning of the global, some bytes may be valid,
425 // but we don't try to handle this.
426 if (Offset.isNegative()) return 0;
428 // If we're not accessing anything in this constant, the result is undefined.
429 if (Offset.getZExtValue() >=
430 TD.getTypeAllocSize(GV->getInitializer()->getType()))
431 return UndefValue::get(IntType);
433 unsigned char RawBytes[32] = {0};
434 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
438 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
439 if (TD.isLittleEndian()) {
440 ResultVal = RawBytes[BytesLoaded - 1];
441 for (unsigned i = 1; i != BytesLoaded; ++i) {
443 ResultVal |= RawBytes[BytesLoaded - 1 - i];
446 ResultVal = RawBytes[0];
447 for (unsigned i = 1; i != BytesLoaded; ++i) {
449 ResultVal |= RawBytes[i];
453 return ConstantInt::get(IntType->getContext(), ResultVal);
456 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
457 /// produce if it is constant and determinable. If this is not determinable,
459 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
460 const DataLayout *TD) {
461 // First, try the easy cases:
462 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
463 if (GV->isConstant() && GV->hasDefinitiveInitializer())
464 return GV->getInitializer();
466 // If the loaded value isn't a constant expr, we can't handle it.
467 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
471 if (CE->getOpcode() == Instruction::GetElementPtr) {
472 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
473 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
475 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
481 // Instead of loading constant c string, use corresponding integer value
482 // directly if string length is small enough.
484 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
485 unsigned StrLen = Str.size();
486 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
487 unsigned NumBits = Ty->getPrimitiveSizeInBits();
488 // Replace load with immediate integer if the result is an integer or fp
490 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
491 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
492 APInt StrVal(NumBits, 0);
493 APInt SingleChar(NumBits, 0);
494 if (TD->isLittleEndian()) {
495 for (signed i = StrLen-1; i >= 0; i--) {
496 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
497 StrVal = (StrVal << 8) | SingleChar;
500 for (unsigned i = 0; i < StrLen; i++) {
501 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
502 StrVal = (StrVal << 8) | SingleChar;
504 // Append NULL at the end.
506 StrVal = (StrVal << 8) | SingleChar;
509 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
510 if (Ty->isFloatingPointTy())
511 Res = ConstantExpr::getBitCast(Res, Ty);
516 // If this load comes from anywhere in a constant global, and if the global
517 // is all undef or zero, we know what it loads.
518 if (GlobalVariable *GV =
519 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
520 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
521 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
522 if (GV->getInitializer()->isNullValue())
523 return Constant::getNullValue(ResTy);
524 if (isa<UndefValue>(GV->getInitializer()))
525 return UndefValue::get(ResTy);
529 // Try hard to fold loads from bitcasted strange and non-type-safe things.
531 return FoldReinterpretLoadFromConstPtr(CE, *TD);
535 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
536 if (LI->isVolatile()) return 0;
538 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
539 return ConstantFoldLoadFromConstPtr(C, TD);
544 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
545 /// Attempt to symbolically evaluate the result of a binary operator merging
546 /// these together. If target data info is available, it is provided as DL,
547 /// otherwise DL is null.
548 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
549 Constant *Op1, const DataLayout *DL){
552 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
553 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
557 if (Opc == Instruction::And && DL) {
558 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
559 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
560 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
561 ComputeMaskedBits(Op0, KnownZero0, KnownOne0, DL);
562 ComputeMaskedBits(Op1, KnownZero1, KnownOne1, DL);
563 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
564 // All the bits of Op0 that the 'and' could be masking are already zero.
567 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
568 // All the bits of Op1 that the 'and' could be masking are already zero.
572 APInt KnownZero = KnownZero0 | KnownZero1;
573 APInt KnownOne = KnownOne0 & KnownOne1;
574 if ((KnownZero | KnownOne).isAllOnesValue()) {
575 return ConstantInt::get(Op0->getType(), KnownOne);
579 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
580 // constant. This happens frequently when iterating over a global array.
581 if (Opc == Instruction::Sub && DL) {
582 GlobalValue *GV1, *GV2;
583 unsigned PtrSize = DL->getPointerSizeInBits();
584 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
585 APInt Offs1(PtrSize, 0), Offs2(PtrSize, 0);
587 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
588 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
590 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
591 // PtrToInt may change the bitwidth so we have convert to the right size
593 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
594 Offs2.zextOrTrunc(OpSize));
601 /// CastGEPIndices - If array indices are not pointer-sized integers,
602 /// explicitly cast them so that they aren't implicitly casted by the
604 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
605 Type *ResultTy, const DataLayout *TD,
606 const TargetLibraryInfo *TLI) {
608 Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
611 SmallVector<Constant*, 32> NewIdxs;
612 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
614 !isa<StructType>(GetElementPtrInst::getIndexedType(
616 Ops.slice(1, i - 1)))) &&
617 Ops[i]->getType() != IntPtrTy) {
619 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
625 NewIdxs.push_back(Ops[i]);
631 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
633 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
640 /// Strip the pointer casts, but preserve the address space information.
641 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
642 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
643 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
644 Ptr = cast<Constant>(Ptr->stripPointerCasts());
645 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
647 // Preserve the address space number of the pointer.
648 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
649 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
650 OldPtrTy->getAddressSpace());
651 Ptr = ConstantExpr::getBitCast(Ptr, NewPtrTy);
656 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
657 /// constant expression, do so.
658 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
659 Type *ResultTy, const DataLayout *TD,
660 const TargetLibraryInfo *TLI) {
661 Constant *Ptr = Ops[0];
662 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized() ||
663 !Ptr->getType()->isPointerTy())
666 Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
668 // If this is a constant expr gep that is effectively computing an
669 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
670 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
671 if (!isa<ConstantInt>(Ops[i])) {
673 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
674 // "inttoptr (sub (ptrtoint Ptr), V)"
675 if (Ops.size() == 2 &&
676 cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
677 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
678 assert((CE == 0 || CE->getType() == IntPtrTy) &&
679 "CastGEPIndices didn't canonicalize index types!");
680 if (CE && CE->getOpcode() == Instruction::Sub &&
681 CE->getOperand(0)->isNullValue()) {
682 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
683 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
684 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
685 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
686 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
693 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
695 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
696 makeArrayRef((Value *const*)
699 Ptr = StripPtrCastKeepAS(Ptr);
701 // If this is a GEP of a GEP, fold it all into a single GEP.
702 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
703 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
705 // Do not try the incorporate the sub-GEP if some index is not a number.
706 bool AllConstantInt = true;
707 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
708 if (!isa<ConstantInt>(NestedOps[i])) {
709 AllConstantInt = false;
715 Ptr = cast<Constant>(GEP->getOperand(0));
716 Offset += APInt(BitWidth,
717 TD->getIndexedOffset(Ptr->getType(), NestedOps));
718 Ptr = StripPtrCastKeepAS(Ptr);
721 // If the base value for this address is a literal integer value, fold the
722 // getelementptr to the resulting integer value casted to the pointer type.
723 APInt BasePtr(BitWidth, 0);
724 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
725 if (CE->getOpcode() == Instruction::IntToPtr) {
726 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
727 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
731 if (Ptr->isNullValue() || BasePtr != 0) {
732 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
733 return ConstantExpr::getIntToPtr(C, ResultTy);
736 // Otherwise form a regular getelementptr. Recompute the indices so that
737 // we eliminate over-indexing of the notional static type array bounds.
738 // This makes it easy to determine if the getelementptr is "inbounds".
739 // Also, this helps GlobalOpt do SROA on GlobalVariables.
740 Type *Ty = Ptr->getType();
741 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
742 SmallVector<Constant*, 32> NewIdxs;
744 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
745 if (ATy->isPointerTy()) {
746 // The only pointer indexing we'll do is on the first index of the GEP.
747 if (!NewIdxs.empty())
750 // Only handle pointers to sized types, not pointers to functions.
751 if (!ATy->getElementType()->isSized())
755 // Determine which element of the array the offset points into.
756 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
757 IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
759 // The element size is 0. This may be [0 x Ty]*, so just use a zero
760 // index for this level and proceed to the next level to see if it can
761 // accommodate the offset.
762 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
764 // The element size is non-zero divide the offset by the element
765 // size (rounding down), to compute the index at this level.
766 APInt NewIdx = Offset.udiv(ElemSize);
767 Offset -= NewIdx * ElemSize;
768 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
770 Ty = ATy->getElementType();
771 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
772 // If we end up with an offset that isn't valid for this struct type, we
773 // can't re-form this GEP in a regular form, so bail out. The pointer
774 // operand likely went through casts that are necessary to make the GEP
776 const StructLayout &SL = *TD->getStructLayout(STy);
777 if (Offset.uge(SL.getSizeInBytes()))
780 // Determine which field of the struct the offset points into. The
781 // getZExtValue is fine as we've already ensured that the offset is
782 // within the range representable by the StructLayout API.
783 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
784 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
786 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
787 Ty = STy->getTypeAtIndex(ElIdx);
789 // We've reached some non-indexable type.
792 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
794 // If we haven't used up the entire offset by descending the static
795 // type, then the offset is pointing into the middle of an indivisible
796 // member, so we can't simplify it.
801 Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
802 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
803 "Computed GetElementPtr has unexpected type!");
805 // If we ended up indexing a member with a type that doesn't match
806 // the type of what the original indices indexed, add a cast.
807 if (Ty != cast<PointerType>(ResultTy)->getElementType())
808 C = FoldBitCast(C, ResultTy, *TD);
815 //===----------------------------------------------------------------------===//
816 // Constant Folding public APIs
817 //===----------------------------------------------------------------------===//
819 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
820 /// If successful, the constant result is returned, if not, null is returned.
821 /// Note that this fails if not all of the operands are constant. Otherwise,
822 /// this function can only fail when attempting to fold instructions like loads
823 /// and stores, which have no constant expression form.
824 Constant *llvm::ConstantFoldInstruction(Instruction *I,
825 const DataLayout *TD,
826 const TargetLibraryInfo *TLI) {
827 // Handle PHI nodes quickly here...
828 if (PHINode *PN = dyn_cast<PHINode>(I)) {
829 Constant *CommonValue = 0;
831 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
832 Value *Incoming = PN->getIncomingValue(i);
833 // If the incoming value is undef then skip it. Note that while we could
834 // skip the value if it is equal to the phi node itself we choose not to
835 // because that would break the rule that constant folding only applies if
836 // all operands are constants.
837 if (isa<UndefValue>(Incoming))
839 // If the incoming value is not a constant, then give up.
840 Constant *C = dyn_cast<Constant>(Incoming);
843 // Fold the PHI's operands.
844 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
845 C = ConstantFoldConstantExpression(NewC, TD, TLI);
846 // If the incoming value is a different constant to
847 // the one we saw previously, then give up.
848 if (CommonValue && C != CommonValue)
854 // If we reach here, all incoming values are the same constant or undef.
855 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
858 // Scan the operand list, checking to see if they are all constants, if so,
859 // hand off to ConstantFoldInstOperands.
860 SmallVector<Constant*, 8> Ops;
861 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
862 Constant *Op = dyn_cast<Constant>(*i);
864 return 0; // All operands not constant!
866 // Fold the Instruction's operands.
867 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
868 Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
873 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
874 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
877 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
878 return ConstantFoldLoadInst(LI, TD);
880 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
881 return ConstantExpr::getInsertValue(
882 cast<Constant>(IVI->getAggregateOperand()),
883 cast<Constant>(IVI->getInsertedValueOperand()),
887 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
888 return ConstantExpr::getExtractValue(
889 cast<Constant>(EVI->getAggregateOperand()),
893 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
897 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
898 const TargetLibraryInfo *TLI,
899 SmallPtrSet<ConstantExpr *, 4> &FoldedOps) {
900 SmallVector<Constant *, 8> Ops;
901 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
903 Constant *NewC = cast<Constant>(*i);
904 // Recursively fold the ConstantExpr's operands. If we have already folded
905 // a ConstantExpr, we don't have to process it again.
906 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
907 if (FoldedOps.insert(NewCE))
908 NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
914 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
916 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
919 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
920 /// using the specified DataLayout. If successful, the constant result is
921 /// result is returned, if not, null is returned.
922 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
923 const DataLayout *TD,
924 const TargetLibraryInfo *TLI) {
925 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
926 return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
929 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
930 /// specified opcode and operands. If successful, the constant result is
931 /// returned, if not, null is returned. Note that this function can fail when
932 /// attempting to fold instructions like loads and stores, which have no
933 /// constant expression form.
935 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
936 /// information, due to only being passed an opcode and operands. Constant
937 /// folding using this function strips this information.
939 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
940 ArrayRef<Constant *> Ops,
941 const DataLayout *TD,
942 const TargetLibraryInfo *TLI) {
943 // Handle easy binops first.
944 if (Instruction::isBinaryOp(Opcode)) {
945 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
946 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
950 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
955 case Instruction::ICmp:
956 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
957 case Instruction::Call:
958 if (Function *F = dyn_cast<Function>(Ops.back()))
959 if (canConstantFoldCallTo(F))
960 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
962 case Instruction::PtrToInt:
963 // If the input is a inttoptr, eliminate the pair. This requires knowing
964 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
965 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
966 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
967 Constant *Input = CE->getOperand(0);
968 unsigned InWidth = Input->getType()->getScalarSizeInBits();
969 if (TD->getPointerSizeInBits() < InWidth) {
971 ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
972 TD->getPointerSizeInBits()));
973 Input = ConstantExpr::getAnd(Input, Mask);
975 // Do a zext or trunc to get to the dest size.
976 return ConstantExpr::getIntegerCast(Input, DestTy, false);
979 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
980 case Instruction::IntToPtr:
981 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
982 // the int size is >= the ptr size. This requires knowing the width of a
983 // pointer, so it can't be done in ConstantExpr::getCast.
984 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
986 TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
987 CE->getOpcode() == Instruction::PtrToInt)
988 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
990 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
991 case Instruction::Trunc:
992 case Instruction::ZExt:
993 case Instruction::SExt:
994 case Instruction::FPTrunc:
995 case Instruction::FPExt:
996 case Instruction::UIToFP:
997 case Instruction::SIToFP:
998 case Instruction::FPToUI:
999 case Instruction::FPToSI:
1000 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1001 case Instruction::BitCast:
1003 return FoldBitCast(Ops[0], DestTy, *TD);
1004 return ConstantExpr::getBitCast(Ops[0], DestTy);
1005 case Instruction::Select:
1006 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1007 case Instruction::ExtractElement:
1008 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1009 case Instruction::InsertElement:
1010 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1011 case Instruction::ShuffleVector:
1012 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1013 case Instruction::GetElementPtr:
1014 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
1016 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
1019 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
1023 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
1024 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
1025 /// returns a constant expression of the specified operands.
1027 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1028 Constant *Ops0, Constant *Ops1,
1029 const DataLayout *TD,
1030 const TargetLibraryInfo *TLI) {
1031 // fold: icmp (inttoptr x), null -> icmp x, 0
1032 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1033 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1034 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1036 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1037 // around to know if bit truncation is happening.
1038 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1039 if (TD && Ops1->isNullValue()) {
1040 Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
1041 if (CE0->getOpcode() == Instruction::IntToPtr) {
1042 // Convert the integer value to the right size to ensure we get the
1043 // proper extension or truncation.
1044 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1046 Constant *Null = Constant::getNullValue(C->getType());
1047 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1050 // Only do this transformation if the int is intptrty in size, otherwise
1051 // there is a truncation or extension that we aren't modeling.
1052 if (CE0->getOpcode() == Instruction::PtrToInt &&
1053 CE0->getType() == IntPtrTy) {
1054 Constant *C = CE0->getOperand(0);
1055 Constant *Null = Constant::getNullValue(C->getType());
1056 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1060 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1061 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
1062 Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
1064 if (CE0->getOpcode() == Instruction::IntToPtr) {
1065 // Convert the integer value to the right size to ensure we get the
1066 // proper extension or truncation.
1067 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1069 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1071 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
1074 // Only do this transformation if the int is intptrty in size, otherwise
1075 // there is a truncation or extension that we aren't modeling.
1076 if ((CE0->getOpcode() == Instruction::PtrToInt &&
1077 CE0->getType() == IntPtrTy &&
1078 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
1079 return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
1080 CE1->getOperand(0), TD, TLI);
1084 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1085 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1086 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1087 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1089 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1092 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1095 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1096 Constant *Ops[] = { LHS, RHS };
1097 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
1101 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1105 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1106 /// getelementptr constantexpr, return the constant value being addressed by the
1107 /// constant expression, or null if something is funny and we can't decide.
1108 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1110 if (!CE->getOperand(1)->isNullValue())
1111 return 0; // Do not allow stepping over the value!
1113 // Loop over all of the operands, tracking down which value we are
1115 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1116 C = C->getAggregateElement(CE->getOperand(i));
1123 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1124 /// indices (with an *implied* zero pointer index that is not in the list),
1125 /// return the constant value being addressed by a virtual load, or null if
1126 /// something is funny and we can't decide.
1127 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1128 ArrayRef<Constant*> Indices) {
1129 // Loop over all of the operands, tracking down which value we are
1131 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1132 C = C->getAggregateElement(Indices[i]);
1140 //===----------------------------------------------------------------------===//
1141 // Constant Folding for Calls
1144 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1145 /// the specified function.
1146 bool llvm::canConstantFoldCallTo(const Function *F) {
1147 switch (F->getIntrinsicID()) {
1148 case Intrinsic::fabs:
1149 case Intrinsic::log:
1150 case Intrinsic::log2:
1151 case Intrinsic::log10:
1152 case Intrinsic::exp:
1153 case Intrinsic::exp2:
1154 case Intrinsic::floor:
1155 case Intrinsic::sqrt:
1156 case Intrinsic::pow:
1157 case Intrinsic::powi:
1158 case Intrinsic::bswap:
1159 case Intrinsic::ctpop:
1160 case Intrinsic::ctlz:
1161 case Intrinsic::cttz:
1162 case Intrinsic::sadd_with_overflow:
1163 case Intrinsic::uadd_with_overflow:
1164 case Intrinsic::ssub_with_overflow:
1165 case Intrinsic::usub_with_overflow:
1166 case Intrinsic::smul_with_overflow:
1167 case Intrinsic::umul_with_overflow:
1168 case Intrinsic::convert_from_fp16:
1169 case Intrinsic::convert_to_fp16:
1170 case Intrinsic::x86_sse_cvtss2si:
1171 case Intrinsic::x86_sse_cvtss2si64:
1172 case Intrinsic::x86_sse_cvttss2si:
1173 case Intrinsic::x86_sse_cvttss2si64:
1174 case Intrinsic::x86_sse2_cvtsd2si:
1175 case Intrinsic::x86_sse2_cvtsd2si64:
1176 case Intrinsic::x86_sse2_cvttsd2si:
1177 case Intrinsic::x86_sse2_cvttsd2si64:
1186 StringRef Name = F->getName();
1188 // In these cases, the check of the length is required. We don't want to
1189 // return true for a name like "cos\0blah" which strcmp would return equal to
1190 // "cos", but has length 8.
1192 default: return false;
1194 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
1196 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1198 return Name == "exp" || Name == "exp2";
1200 return Name == "fabs" || Name == "fmod" || Name == "floor";
1202 return Name == "log" || Name == "log10";
1204 return Name == "pow";
1206 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1207 Name == "sinf" || Name == "sqrtf";
1209 return Name == "tan" || Name == "tanh";
1213 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1215 sys::llvm_fenv_clearexcept();
1217 if (sys::llvm_fenv_testexcept()) {
1218 sys::llvm_fenv_clearexcept();
1222 if (Ty->isHalfTy()) {
1225 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1226 return ConstantFP::get(Ty->getContext(), APF);
1228 if (Ty->isFloatTy())
1229 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1230 if (Ty->isDoubleTy())
1231 return ConstantFP::get(Ty->getContext(), APFloat(V));
1232 llvm_unreachable("Can only constant fold half/float/double");
1235 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1236 double V, double W, Type *Ty) {
1237 sys::llvm_fenv_clearexcept();
1239 if (sys::llvm_fenv_testexcept()) {
1240 sys::llvm_fenv_clearexcept();
1244 if (Ty->isHalfTy()) {
1247 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1248 return ConstantFP::get(Ty->getContext(), APF);
1250 if (Ty->isFloatTy())
1251 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1252 if (Ty->isDoubleTy())
1253 return ConstantFP::get(Ty->getContext(), APFloat(V));
1254 llvm_unreachable("Can only constant fold half/float/double");
1257 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1258 /// conversion of a constant floating point. If roundTowardZero is false, the
1259 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1260 /// the behavior of the non-truncating SSE instructions in the default rounding
1261 /// mode. The desired integer type Ty is used to select how many bits are
1262 /// available for the result. Returns null if the conversion cannot be
1263 /// performed, otherwise returns the Constant value resulting from the
1265 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1266 bool roundTowardZero, Type *Ty) {
1267 // All of these conversion intrinsics form an integer of at most 64bits.
1268 unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
1269 assert(ResultWidth <= 64 &&
1270 "Can only constant fold conversions to 64 and 32 bit ints");
1273 bool isExact = false;
1274 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1275 : APFloat::rmNearestTiesToEven;
1276 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1277 /*isSigned=*/true, mode,
1279 if (status != APFloat::opOK && status != APFloat::opInexact)
1281 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1284 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1285 /// with the specified arguments, returning null if unsuccessful.
1287 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1288 const TargetLibraryInfo *TLI) {
1291 StringRef Name = F->getName();
1293 Type *Ty = F->getReturnType();
1294 if (Operands.size() == 1) {
1295 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1296 if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1297 APFloat Val(Op->getValueAPF());
1300 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1302 return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1307 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1310 /// We only fold functions with finite arguments. Folding NaN and inf is
1311 /// likely to be aborted with an exception anyway, and some host libms
1312 /// have known errors raising exceptions.
1313 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1316 /// Currently APFloat versions of these functions do not exist, so we use
1317 /// the host native double versions. Float versions are not called
1318 /// directly but for all these it is true (float)(f((double)arg)) ==
1319 /// f(arg). Long double not supported yet.
1321 if (Ty->isFloatTy())
1322 V = Op->getValueAPF().convertToFloat();
1323 else if (Ty->isDoubleTy())
1324 V = Op->getValueAPF().convertToDouble();
1327 APFloat APF = Op->getValueAPF();
1328 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1329 V = APF.convertToDouble();
1332 switch (F->getIntrinsicID()) {
1334 case Intrinsic::fabs:
1335 return ConstantFoldFP(fabs, V, Ty);
1337 case Intrinsic::log2:
1338 return ConstantFoldFP(log2, V, Ty);
1341 case Intrinsic::log:
1342 return ConstantFoldFP(log, V, Ty);
1345 case Intrinsic::log10:
1346 return ConstantFoldFP(log10, V, Ty);
1349 case Intrinsic::exp:
1350 return ConstantFoldFP(exp, V, Ty);
1353 case Intrinsic::exp2:
1354 return ConstantFoldFP(exp2, V, Ty);
1356 case Intrinsic::floor:
1357 return ConstantFoldFP(floor, V, Ty);
1362 if (Name == "acos" && TLI->has(LibFunc::acos))
1363 return ConstantFoldFP(acos, V, Ty);
1364 else if (Name == "asin" && TLI->has(LibFunc::asin))
1365 return ConstantFoldFP(asin, V, Ty);
1366 else if (Name == "atan" && TLI->has(LibFunc::atan))
1367 return ConstantFoldFP(atan, V, Ty);
1370 if (Name == "ceil" && TLI->has(LibFunc::ceil))
1371 return ConstantFoldFP(ceil, V, Ty);
1372 else if (Name == "cos" && TLI->has(LibFunc::cos))
1373 return ConstantFoldFP(cos, V, Ty);
1374 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1375 return ConstantFoldFP(cosh, V, Ty);
1376 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1377 return ConstantFoldFP(cos, V, Ty);
1380 if (Name == "exp" && TLI->has(LibFunc::exp))
1381 return ConstantFoldFP(exp, V, Ty);
1383 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1384 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1386 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1390 if (Name == "fabs" && TLI->has(LibFunc::fabs))
1391 return ConstantFoldFP(fabs, V, Ty);
1392 else if (Name == "floor" && TLI->has(LibFunc::floor))
1393 return ConstantFoldFP(floor, V, Ty);
1396 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1397 return ConstantFoldFP(log, V, Ty);
1398 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1399 return ConstantFoldFP(log10, V, Ty);
1400 else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1401 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1403 return ConstantFoldFP(sqrt, V, Ty);
1405 return Constant::getNullValue(Ty);
1409 if (Name == "sin" && TLI->has(LibFunc::sin))
1410 return ConstantFoldFP(sin, V, Ty);
1411 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1412 return ConstantFoldFP(sinh, V, Ty);
1413 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1414 return ConstantFoldFP(sqrt, V, Ty);
1415 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1416 return ConstantFoldFP(sqrt, V, Ty);
1417 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1418 return ConstantFoldFP(sin, V, Ty);
1421 if (Name == "tan" && TLI->has(LibFunc::tan))
1422 return ConstantFoldFP(tan, V, Ty);
1423 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1424 return ConstantFoldFP(tanh, V, Ty);
1432 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1433 switch (F->getIntrinsicID()) {
1434 case Intrinsic::bswap:
1435 return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1436 case Intrinsic::ctpop:
1437 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1438 case Intrinsic::convert_from_fp16: {
1439 APFloat Val(APFloat::IEEEhalf, Op->getValue());
1442 APFloat::opStatus status =
1443 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1445 // Conversion is always precise.
1447 assert(status == APFloat::opOK && !lost &&
1448 "Precision lost during fp16 constfolding");
1450 return ConstantFP::get(F->getContext(), Val);
1457 // Support ConstantVector in case we have an Undef in the top.
1458 if (isa<ConstantVector>(Operands[0]) ||
1459 isa<ConstantDataVector>(Operands[0])) {
1460 Constant *Op = cast<Constant>(Operands[0]);
1461 switch (F->getIntrinsicID()) {
1463 case Intrinsic::x86_sse_cvtss2si:
1464 case Intrinsic::x86_sse_cvtss2si64:
1465 case Intrinsic::x86_sse2_cvtsd2si:
1466 case Intrinsic::x86_sse2_cvtsd2si64:
1467 if (ConstantFP *FPOp =
1468 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1469 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1470 /*roundTowardZero=*/false, Ty);
1471 case Intrinsic::x86_sse_cvttss2si:
1472 case Intrinsic::x86_sse_cvttss2si64:
1473 case Intrinsic::x86_sse2_cvttsd2si:
1474 case Intrinsic::x86_sse2_cvttsd2si64:
1475 if (ConstantFP *FPOp =
1476 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1477 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1478 /*roundTowardZero=*/true, Ty);
1482 if (isa<UndefValue>(Operands[0])) {
1483 if (F->getIntrinsicID() == Intrinsic::bswap)
1491 if (Operands.size() == 2) {
1492 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1493 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1496 if (Ty->isFloatTy())
1497 Op1V = Op1->getValueAPF().convertToFloat();
1498 else if (Ty->isDoubleTy())
1499 Op1V = Op1->getValueAPF().convertToDouble();
1502 APFloat APF = Op1->getValueAPF();
1503 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1504 Op1V = APF.convertToDouble();
1507 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1508 if (Op2->getType() != Op1->getType())
1512 if (Ty->isFloatTy())
1513 Op2V = Op2->getValueAPF().convertToFloat();
1514 else if (Ty->isDoubleTy())
1515 Op2V = Op2->getValueAPF().convertToDouble();
1518 APFloat APF = Op2->getValueAPF();
1519 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1520 Op2V = APF.convertToDouble();
1523 if (F->getIntrinsicID() == Intrinsic::pow) {
1524 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1528 if (Name == "pow" && TLI->has(LibFunc::pow))
1529 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1530 if (Name == "fmod" && TLI->has(LibFunc::fmod))
1531 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1532 if (Name == "atan2" && TLI->has(LibFunc::atan2))
1533 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1534 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1535 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isHalfTy())
1536 return ConstantFP::get(F->getContext(),
1537 APFloat((float)std::pow((float)Op1V,
1538 (int)Op2C->getZExtValue())));
1539 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
1540 return ConstantFP::get(F->getContext(),
1541 APFloat((float)std::pow((float)Op1V,
1542 (int)Op2C->getZExtValue())));
1543 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
1544 return ConstantFP::get(F->getContext(),
1545 APFloat((double)std::pow((double)Op1V,
1546 (int)Op2C->getZExtValue())));
1551 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1552 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1553 switch (F->getIntrinsicID()) {
1555 case Intrinsic::sadd_with_overflow:
1556 case Intrinsic::uadd_with_overflow:
1557 case Intrinsic::ssub_with_overflow:
1558 case Intrinsic::usub_with_overflow:
1559 case Intrinsic::smul_with_overflow:
1560 case Intrinsic::umul_with_overflow: {
1563 switch (F->getIntrinsicID()) {
1564 default: llvm_unreachable("Invalid case");
1565 case Intrinsic::sadd_with_overflow:
1566 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1568 case Intrinsic::uadd_with_overflow:
1569 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1571 case Intrinsic::ssub_with_overflow:
1572 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1574 case Intrinsic::usub_with_overflow:
1575 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1577 case Intrinsic::smul_with_overflow:
1578 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1580 case Intrinsic::umul_with_overflow:
1581 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1585 ConstantInt::get(F->getContext(), Res),
1586 ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1588 return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
1590 case Intrinsic::cttz:
1591 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1592 return UndefValue::get(Ty);
1593 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1594 case Intrinsic::ctlz:
1595 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1596 return UndefValue::get(Ty);
1597 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());