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 VMCore ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // TargetData information. These functions cannot go in VMCore due to library
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/FEnv.h"
39 //===----------------------------------------------------------------------===//
40 // Constant Folding internal helper functions
41 //===----------------------------------------------------------------------===//
43 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
44 /// TargetData. This always returns a non-null constant, but it may be a
45 /// ConstantExpr if unfoldable.
46 static Constant *FoldBitCast(Constant *C, Type *DestTy,
47 const TargetData &TD) {
48 // Catch the obvious splat cases.
49 if (C->isNullValue() && !DestTy->isX86_MMXTy())
50 return Constant::getNullValue(DestTy);
51 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
52 return Constant::getAllOnesValue(DestTy);
54 // Bitcast of Bitcast can be done using a single cast.
55 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
56 if (CE && CE->getOpcode() == Instruction::BitCast) {
57 return ConstantExpr::getBitCast(CE->getOperand(0), DestTy);
60 // The code below only handles casts to vectors currently.
61 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
63 return ConstantExpr::getBitCast(C, DestTy);
65 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
66 // vector so the code below can handle it uniformly.
67 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
68 Constant *Ops = C; // don't take the address of C!
69 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
72 // If this is a bitcast from constant vector -> vector, fold it.
73 ConstantVector *CV = dyn_cast<ConstantVector>(C);
75 return ConstantExpr::getBitCast(C, DestTy);
77 // If the element types match, VMCore can fold it.
78 unsigned NumDstElt = DestVTy->getNumElements();
79 unsigned NumSrcElt = CV->getNumOperands();
80 if (NumDstElt == NumSrcElt)
81 return ConstantExpr::getBitCast(C, DestTy);
83 Type *SrcEltTy = CV->getType()->getElementType();
84 Type *DstEltTy = DestVTy->getElementType();
86 // Otherwise, we're changing the number of elements in a vector, which
87 // requires endianness information to do the right thing. For example,
88 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
89 // folds to (little endian):
90 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
91 // and to (big endian):
92 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
94 // First thing is first. We only want to think about integer here, so if
95 // we have something in FP form, recast it as integer.
96 if (DstEltTy->isFloatingPointTy()) {
97 // Fold to an vector of integers with same size as our FP type.
98 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
100 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
101 // Recursively handle this integer conversion, if possible.
102 C = FoldBitCast(C, DestIVTy, TD);
103 if (!C) return ConstantExpr::getBitCast(C, DestTy);
105 // Finally, VMCore can handle this now that #elts line up.
106 return ConstantExpr::getBitCast(C, DestTy);
109 // Okay, we know the destination is integer, if the input is FP, convert
110 // it to integer first.
111 if (SrcEltTy->isFloatingPointTy()) {
112 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
114 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
115 // Ask VMCore to do the conversion now that #elts line up.
116 C = ConstantExpr::getBitCast(C, SrcIVTy);
117 CV = dyn_cast<ConstantVector>(C);
118 if (!CV) // If VMCore wasn't able to fold it, bail out.
122 // Now we know that the input and output vectors are both integer vectors
123 // of the same size, and that their #elements is not the same. Do the
124 // conversion here, which depends on whether the input or output has
126 bool isLittleEndian = TD.isLittleEndian();
128 SmallVector<Constant*, 32> Result;
129 if (NumDstElt < NumSrcElt) {
130 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
131 Constant *Zero = Constant::getNullValue(DstEltTy);
132 unsigned Ratio = NumSrcElt/NumDstElt;
133 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
135 for (unsigned i = 0; i != NumDstElt; ++i) {
136 // Build each element of the result.
137 Constant *Elt = Zero;
138 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
139 for (unsigned j = 0; j != Ratio; ++j) {
140 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
141 if (!Src) // Reject constantexpr elements.
142 return ConstantExpr::getBitCast(C, DestTy);
144 // Zero extend the element to the right size.
145 Src = ConstantExpr::getZExt(Src, Elt->getType());
147 // Shift it to the right place, depending on endianness.
148 Src = ConstantExpr::getShl(Src,
149 ConstantInt::get(Src->getType(), ShiftAmt));
150 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
153 Elt = ConstantExpr::getOr(Elt, Src);
155 Result.push_back(Elt);
158 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
159 unsigned Ratio = NumDstElt/NumSrcElt;
160 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
162 // Loop over each source value, expanding into multiple results.
163 for (unsigned i = 0; i != NumSrcElt; ++i) {
164 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
165 if (!Src) // Reject constantexpr elements.
166 return ConstantExpr::getBitCast(C, DestTy);
168 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
169 for (unsigned j = 0; j != Ratio; ++j) {
170 // Shift the piece of the value into the right place, depending on
172 Constant *Elt = ConstantExpr::getLShr(Src,
173 ConstantInt::get(Src->getType(), ShiftAmt));
174 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
176 // Truncate and remember this piece.
177 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
182 return ConstantVector::get(Result);
186 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
187 /// from a global, return the global and the constant. Because of
188 /// constantexprs, this function is recursive.
189 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
190 int64_t &Offset, const TargetData &TD) {
191 // Trivial case, constant is the global.
192 if ((GV = dyn_cast<GlobalValue>(C))) {
197 // Otherwise, if this isn't a constant expr, bail out.
198 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
199 if (!CE) return false;
201 // Look through ptr->int and ptr->ptr casts.
202 if (CE->getOpcode() == Instruction::PtrToInt ||
203 CE->getOpcode() == Instruction::BitCast)
204 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
206 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
207 if (CE->getOpcode() == Instruction::GetElementPtr) {
208 // Cannot compute this if the element type of the pointer is missing size
210 if (!cast<PointerType>(CE->getOperand(0)->getType())
211 ->getElementType()->isSized())
214 // If the base isn't a global+constant, we aren't either.
215 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
218 // Otherwise, add any offset that our operands provide.
219 gep_type_iterator GTI = gep_type_begin(CE);
220 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
221 i != e; ++i, ++GTI) {
222 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
223 if (!CI) return false; // Index isn't a simple constant?
224 if (CI->isZero()) continue; // Not adding anything.
226 if (StructType *ST = dyn_cast<StructType>(*GTI)) {
228 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
230 SequentialType *SQT = cast<SequentialType>(*GTI);
231 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
240 /// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
241 /// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
242 /// pointer to copy results into and BytesLeft is the number of bytes left in
243 /// the CurPtr buffer. TD is the target data.
244 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
245 unsigned char *CurPtr, unsigned BytesLeft,
246 const TargetData &TD) {
247 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
248 "Out of range access");
250 // If this element is zero or undefined, we can just return since *CurPtr is
252 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
255 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
256 if (CI->getBitWidth() > 64 ||
257 (CI->getBitWidth() & 7) != 0)
260 uint64_t Val = CI->getZExtValue();
261 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
263 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
264 CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
270 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
271 if (CFP->getType()->isDoubleTy()) {
272 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
273 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
275 if (CFP->getType()->isFloatTy()){
276 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
277 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
282 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
283 const StructLayout *SL = TD.getStructLayout(CS->getType());
284 unsigned Index = SL->getElementContainingOffset(ByteOffset);
285 uint64_t CurEltOffset = SL->getElementOffset(Index);
286 ByteOffset -= CurEltOffset;
289 // If the element access is to the element itself and not to tail padding,
290 // read the bytes from the element.
291 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
293 if (ByteOffset < EltSize &&
294 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
300 // Check to see if we read from the last struct element, if so we're done.
301 if (Index == CS->getType()->getNumElements())
304 // If we read all of the bytes we needed from this element we're done.
305 uint64_t NextEltOffset = SL->getElementOffset(Index);
307 if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
310 // Move to the next element of the struct.
311 CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
312 BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
314 CurEltOffset = NextEltOffset;
319 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
320 uint64_t EltSize = TD.getTypeAllocSize(CA->getType()->getElementType());
321 uint64_t Index = ByteOffset / EltSize;
322 uint64_t Offset = ByteOffset - Index * EltSize;
323 for (; Index != CA->getType()->getNumElements(); ++Index) {
324 if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
327 if (EltSize >= BytesLeft)
331 BytesLeft -= EltSize;
337 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
338 uint64_t EltSize = TD.getTypeAllocSize(CV->getType()->getElementType());
339 uint64_t Index = ByteOffset / EltSize;
340 uint64_t Offset = ByteOffset - Index * EltSize;
341 for (; Index != CV->getType()->getNumElements(); ++Index) {
342 if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
345 if (EltSize >= BytesLeft)
349 BytesLeft -= EltSize;
355 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
356 if (CE->getOpcode() == Instruction::IntToPtr &&
357 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext()))
358 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
362 // Otherwise, unknown initializer type.
366 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
367 const TargetData &TD) {
368 Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
369 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
371 // If this isn't an integer load we can't fold it directly.
373 // If this is a float/double load, we can try folding it as an int32/64 load
374 // and then bitcast the result. This can be useful for union cases. Note
375 // that address spaces don't matter here since we're not going to result in
376 // an actual new load.
378 if (LoadTy->isFloatTy())
379 MapTy = Type::getInt32PtrTy(C->getContext());
380 else if (LoadTy->isDoubleTy())
381 MapTy = Type::getInt64PtrTy(C->getContext());
382 else if (LoadTy->isVectorTy()) {
383 MapTy = IntegerType::get(C->getContext(),
384 TD.getTypeAllocSizeInBits(LoadTy));
385 MapTy = PointerType::getUnqual(MapTy);
389 C = FoldBitCast(C, MapTy, TD);
390 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
391 return FoldBitCast(Res, LoadTy, TD);
395 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
396 if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
400 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
403 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
404 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
405 !GV->getInitializer()->getType()->isSized())
408 // If we're loading off the beginning of the global, some bytes may be valid,
409 // but we don't try to handle this.
410 if (Offset < 0) return 0;
412 // If we're not accessing anything in this constant, the result is undefined.
413 if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
414 return UndefValue::get(IntType);
416 unsigned char RawBytes[32] = {0};
417 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
421 APInt ResultVal = APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1]);
422 for (unsigned i = 1; i != BytesLoaded; ++i) {
424 ResultVal |= RawBytes[BytesLoaded-1-i];
427 return ConstantInt::get(IntType->getContext(), ResultVal);
430 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
431 /// produce if it is constant and determinable. If this is not determinable,
433 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
434 const TargetData *TD) {
435 // First, try the easy cases:
436 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
437 if (GV->isConstant() && GV->hasDefinitiveInitializer())
438 return GV->getInitializer();
440 // If the loaded value isn't a constant expr, we can't handle it.
441 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
444 if (CE->getOpcode() == Instruction::GetElementPtr) {
445 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
446 if (GV->isConstant() && GV->hasDefinitiveInitializer())
448 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
452 // Instead of loading constant c string, use corresponding integer value
453 // directly if string length is small enough.
455 if (TD && GetConstantStringInfo(CE, Str) && !Str.empty()) {
456 unsigned StrLen = Str.length();
457 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
458 unsigned NumBits = Ty->getPrimitiveSizeInBits();
459 // Replace load with immediate integer if the result is an integer or fp
461 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
462 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
463 APInt StrVal(NumBits, 0);
464 APInt SingleChar(NumBits, 0);
465 if (TD->isLittleEndian()) {
466 for (signed i = StrLen-1; i >= 0; i--) {
467 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
468 StrVal = (StrVal << 8) | SingleChar;
471 for (unsigned i = 0; i < StrLen; i++) {
472 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
473 StrVal = (StrVal << 8) | SingleChar;
475 // Append NULL at the end.
477 StrVal = (StrVal << 8) | SingleChar;
480 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
481 if (Ty->isFloatingPointTy())
482 Res = ConstantExpr::getBitCast(Res, Ty);
487 // If this load comes from anywhere in a constant global, and if the global
488 // is all undef or zero, we know what it loads.
489 if (GlobalVariable *GV =
490 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
491 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
492 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
493 if (GV->getInitializer()->isNullValue())
494 return Constant::getNullValue(ResTy);
495 if (isa<UndefValue>(GV->getInitializer()))
496 return UndefValue::get(ResTy);
500 // Try hard to fold loads from bitcasted strange and non-type-safe things. We
501 // currently don't do any of this for big endian systems. It can be
502 // generalized in the future if someone is interested.
503 if (TD && TD->isLittleEndian())
504 return FoldReinterpretLoadFromConstPtr(CE, *TD);
508 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
509 if (LI->isVolatile()) return 0;
511 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
512 return ConstantFoldLoadFromConstPtr(C, TD);
517 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
518 /// Attempt to symbolically evaluate the result of a binary operator merging
519 /// these together. If target data info is available, it is provided as TD,
520 /// otherwise TD is null.
521 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
522 Constant *Op1, const TargetData *TD){
525 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
526 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
530 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
531 // constant. This happens frequently when iterating over a global array.
532 if (Opc == Instruction::Sub && TD) {
533 GlobalValue *GV1, *GV2;
534 int64_t Offs1, Offs2;
536 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
537 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
539 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
540 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
547 /// CastGEPIndices - If array indices are not pointer-sized integers,
548 /// explicitly cast them so that they aren't implicitly casted by the
550 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
552 const TargetData *TD) {
554 Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
557 SmallVector<Constant*, 32> NewIdxs;
558 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
560 !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
561 Ops.slice(1, i-1)))) &&
562 Ops[i]->getType() != IntPtrTy) {
564 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
570 NewIdxs.push_back(Ops[i]);
575 ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
577 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
582 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
583 /// constant expression, do so.
584 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
586 const TargetData *TD) {
587 Constant *Ptr = Ops[0];
588 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
591 Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
593 // If this is a constant expr gep that is effectively computing an
594 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
595 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
596 if (!isa<ConstantInt>(Ops[i])) {
598 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
599 // "inttoptr (sub (ptrtoint Ptr), V)"
600 if (Ops.size() == 2 &&
601 cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
602 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
603 assert((CE == 0 || CE->getType() == IntPtrTy) &&
604 "CastGEPIndices didn't canonicalize index types!");
605 if (CE && CE->getOpcode() == Instruction::Sub &&
606 CE->getOperand(0)->isNullValue()) {
607 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
608 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
609 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
610 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
611 Res = ConstantFoldConstantExpression(ResCE, TD);
618 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
620 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
621 makeArrayRef((Value **)Ops.data() + 1,
623 Ptr = cast<Constant>(Ptr->stripPointerCasts());
625 // If this is a GEP of a GEP, fold it all into a single GEP.
626 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
627 SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
629 // Do not try the incorporate the sub-GEP if some index is not a number.
630 bool AllConstantInt = true;
631 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
632 if (!isa<ConstantInt>(NestedOps[i])) {
633 AllConstantInt = false;
639 Ptr = cast<Constant>(GEP->getOperand(0));
640 Offset += APInt(BitWidth,
641 TD->getIndexedOffset(Ptr->getType(), NestedOps));
642 Ptr = cast<Constant>(Ptr->stripPointerCasts());
645 // If the base value for this address is a literal integer value, fold the
646 // getelementptr to the resulting integer value casted to the pointer type.
647 APInt BasePtr(BitWidth, 0);
648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
649 if (CE->getOpcode() == Instruction::IntToPtr)
650 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
651 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
652 if (Ptr->isNullValue() || BasePtr != 0) {
653 Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
654 return ConstantExpr::getIntToPtr(C, ResultTy);
657 // Otherwise form a regular getelementptr. Recompute the indices so that
658 // we eliminate over-indexing of the notional static type array bounds.
659 // This makes it easy to determine if the getelementptr is "inbounds".
660 // Also, this helps GlobalOpt do SROA on GlobalVariables.
661 Type *Ty = Ptr->getType();
662 SmallVector<Constant*, 32> NewIdxs;
664 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
665 if (ATy->isPointerTy()) {
666 // The only pointer indexing we'll do is on the first index of the GEP.
667 if (!NewIdxs.empty())
670 // Only handle pointers to sized types, not pointers to functions.
671 if (!ATy->getElementType()->isSized())
675 // Determine which element of the array the offset points into.
676 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
677 IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
679 // The element size is 0. This may be [0 x Ty]*, so just use a zero
680 // index for this level and proceed to the next level to see if it can
681 // accommodate the offset.
682 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
684 // The element size is non-zero divide the offset by the element
685 // size (rounding down), to compute the index at this level.
686 APInt NewIdx = Offset.udiv(ElemSize);
687 Offset -= NewIdx * ElemSize;
688 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
690 Ty = ATy->getElementType();
691 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
692 // Determine which field of the struct the offset points into. The
693 // getZExtValue is at least as safe as the StructLayout API because we
694 // know the offset is within the struct at this point.
695 const StructLayout &SL = *TD->getStructLayout(STy);
696 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
697 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
699 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
700 Ty = STy->getTypeAtIndex(ElIdx);
702 // We've reached some non-indexable type.
705 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
707 // If we haven't used up the entire offset by descending the static
708 // type, then the offset is pointing into the middle of an indivisible
709 // member, so we can't simplify it.
715 ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
716 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
717 "Computed GetElementPtr has unexpected type!");
719 // If we ended up indexing a member with a type that doesn't match
720 // the type of what the original indices indexed, add a cast.
721 if (Ty != cast<PointerType>(ResultTy)->getElementType())
722 C = FoldBitCast(C, ResultTy, *TD);
729 //===----------------------------------------------------------------------===//
730 // Constant Folding public APIs
731 //===----------------------------------------------------------------------===//
733 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
734 /// If successful, the constant result is returned, if not, null is returned.
735 /// Note that this fails if not all of the operands are constant. Otherwise,
736 /// this function can only fail when attempting to fold instructions like loads
737 /// and stores, which have no constant expression form.
738 Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
739 // Handle PHI nodes quickly here...
740 if (PHINode *PN = dyn_cast<PHINode>(I)) {
741 Constant *CommonValue = 0;
743 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
744 Value *Incoming = PN->getIncomingValue(i);
745 // If the incoming value is undef then skip it. Note that while we could
746 // skip the value if it is equal to the phi node itself we choose not to
747 // because that would break the rule that constant folding only applies if
748 // all operands are constants.
749 if (isa<UndefValue>(Incoming))
751 // If the incoming value is not a constant, or is a different constant to
752 // the one we saw previously, then give up.
753 Constant *C = dyn_cast<Constant>(Incoming);
754 if (!C || (CommonValue && C != CommonValue))
759 // If we reach here, all incoming values are the same constant or undef.
760 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
763 // Scan the operand list, checking to see if they are all constants, if so,
764 // hand off to ConstantFoldInstOperands.
765 SmallVector<Constant*, 8> Ops;
766 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
767 if (Constant *Op = dyn_cast<Constant>(*i))
770 return 0; // All operands not constant!
772 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
773 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
776 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
777 return ConstantFoldLoadInst(LI, TD);
779 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
780 return ConstantExpr::getInsertValue(
781 cast<Constant>(IVI->getAggregateOperand()),
782 cast<Constant>(IVI->getInsertedValueOperand()),
785 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
786 return ConstantExpr::getExtractValue(
787 cast<Constant>(EVI->getAggregateOperand()),
790 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
793 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
794 /// using the specified TargetData. If successful, the constant result is
795 /// result is returned, if not, null is returned.
796 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
797 const TargetData *TD) {
798 SmallVector<Constant*, 8> Ops;
799 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end();
801 Constant *NewC = cast<Constant>(*i);
802 // Recursively fold the ConstantExpr's operands.
803 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC))
804 NewC = ConstantFoldConstantExpression(NewCE, TD);
809 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
811 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD);
814 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
815 /// specified opcode and operands. If successful, the constant result is
816 /// returned, if not, null is returned. Note that this function can fail when
817 /// attempting to fold instructions like loads and stores, which have no
818 /// constant expression form.
820 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
821 /// information, due to only being passed an opcode and operands. Constant
822 /// folding using this function strips this information.
824 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
825 ArrayRef<Constant *> Ops,
826 const TargetData *TD) {
827 // Handle easy binops first.
828 if (Instruction::isBinaryOp(Opcode)) {
829 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
830 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
833 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
838 case Instruction::ICmp:
839 case Instruction::FCmp: assert(0 && "Invalid for compares");
840 case Instruction::Call:
841 if (Function *F = dyn_cast<Function>(Ops.back()))
842 if (canConstantFoldCallTo(F))
843 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1));
845 case Instruction::PtrToInt:
846 // If the input is a inttoptr, eliminate the pair. This requires knowing
847 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
848 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
849 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
850 Constant *Input = CE->getOperand(0);
851 unsigned InWidth = Input->getType()->getScalarSizeInBits();
852 if (TD->getPointerSizeInBits() < InWidth) {
854 ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
855 TD->getPointerSizeInBits()));
856 Input = ConstantExpr::getAnd(Input, Mask);
858 // Do a zext or trunc to get to the dest size.
859 return ConstantExpr::getIntegerCast(Input, DestTy, false);
862 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
863 case Instruction::IntToPtr:
864 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
865 // the int size is >= the ptr size. This requires knowing the width of a
866 // pointer, so it can't be done in ConstantExpr::getCast.
867 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
869 TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
870 CE->getOpcode() == Instruction::PtrToInt)
871 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
873 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
874 case Instruction::Trunc:
875 case Instruction::ZExt:
876 case Instruction::SExt:
877 case Instruction::FPTrunc:
878 case Instruction::FPExt:
879 case Instruction::UIToFP:
880 case Instruction::SIToFP:
881 case Instruction::FPToUI:
882 case Instruction::FPToSI:
883 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
884 case Instruction::BitCast:
886 return FoldBitCast(Ops[0], DestTy, *TD);
887 return ConstantExpr::getBitCast(Ops[0], DestTy);
888 case Instruction::Select:
889 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
890 case Instruction::ExtractElement:
891 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
892 case Instruction::InsertElement:
893 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
894 case Instruction::ShuffleVector:
895 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
896 case Instruction::GetElementPtr:
897 if (Constant *C = CastGEPIndices(Ops, DestTy, TD))
899 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD))
902 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
906 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
907 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
908 /// returns a constant expression of the specified operands.
910 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
911 Constant *Ops0, Constant *Ops1,
912 const TargetData *TD) {
913 // fold: icmp (inttoptr x), null -> icmp x, 0
914 // fold: icmp (ptrtoint x), 0 -> icmp x, null
915 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
916 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
918 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
919 // around to know if bit truncation is happening.
920 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
921 if (TD && Ops1->isNullValue()) {
922 Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
923 if (CE0->getOpcode() == Instruction::IntToPtr) {
924 // Convert the integer value to the right size to ensure we get the
925 // proper extension or truncation.
926 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
928 Constant *Null = Constant::getNullValue(C->getType());
929 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
932 // Only do this transformation if the int is intptrty in size, otherwise
933 // there is a truncation or extension that we aren't modeling.
934 if (CE0->getOpcode() == Instruction::PtrToInt &&
935 CE0->getType() == IntPtrTy) {
936 Constant *C = CE0->getOperand(0);
937 Constant *Null = Constant::getNullValue(C->getType());
938 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
942 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
943 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
944 Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
946 if (CE0->getOpcode() == Instruction::IntToPtr) {
947 // Convert the integer value to the right size to ensure we get the
948 // proper extension or truncation.
949 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
951 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
953 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD);
956 // Only do this transformation if the int is intptrty in size, otherwise
957 // there is a truncation or extension that we aren't modeling.
958 if ((CE0->getOpcode() == Instruction::PtrToInt &&
959 CE0->getType() == IntPtrTy &&
960 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
961 return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
962 CE1->getOperand(0), TD);
966 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
967 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
968 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
969 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
971 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,TD);
973 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,TD);
975 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
976 Constant *Ops[] = { LHS, RHS };
977 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD);
981 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
985 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
986 /// getelementptr constantexpr, return the constant value being addressed by the
987 /// constant expression, or null if something is funny and we can't decide.
988 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
990 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
991 return 0; // Do not allow stepping over the value!
993 // Loop over all of the operands, tracking down which value we are
995 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
996 for (++I; I != E; ++I)
997 if (StructType *STy = dyn_cast<StructType>(*I)) {
998 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
999 assert(CU->getZExtValue() < STy->getNumElements() &&
1000 "Struct index out of range!");
1001 unsigned El = (unsigned)CU->getZExtValue();
1002 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1003 C = CS->getOperand(El);
1004 } else if (isa<ConstantAggregateZero>(C)) {
1005 C = Constant::getNullValue(STy->getElementType(El));
1006 } else if (isa<UndefValue>(C)) {
1007 C = UndefValue::get(STy->getElementType(El));
1011 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
1012 if (ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
1013 if (CI->getZExtValue() >= ATy->getNumElements())
1015 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
1016 C = CA->getOperand(CI->getZExtValue());
1017 else if (isa<ConstantAggregateZero>(C))
1018 C = Constant::getNullValue(ATy->getElementType());
1019 else if (isa<UndefValue>(C))
1020 C = UndefValue::get(ATy->getElementType());
1023 } else if (VectorType *VTy = dyn_cast<VectorType>(*I)) {
1024 if (CI->getZExtValue() >= VTy->getNumElements())
1026 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
1027 C = CP->getOperand(CI->getZExtValue());
1028 else if (isa<ConstantAggregateZero>(C))
1029 C = Constant::getNullValue(VTy->getElementType());
1030 else if (isa<UndefValue>(C))
1031 C = UndefValue::get(VTy->getElementType());
1044 //===----------------------------------------------------------------------===//
1045 // Constant Folding for Calls
1048 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1049 /// the specified function.
1051 llvm::canConstantFoldCallTo(const Function *F) {
1052 switch (F->getIntrinsicID()) {
1053 case Intrinsic::sqrt:
1054 case Intrinsic::powi:
1055 case Intrinsic::bswap:
1056 case Intrinsic::ctpop:
1057 case Intrinsic::ctlz:
1058 case Intrinsic::cttz:
1059 case Intrinsic::sadd_with_overflow:
1060 case Intrinsic::uadd_with_overflow:
1061 case Intrinsic::ssub_with_overflow:
1062 case Intrinsic::usub_with_overflow:
1063 case Intrinsic::smul_with_overflow:
1064 case Intrinsic::umul_with_overflow:
1065 case Intrinsic::convert_from_fp16:
1066 case Intrinsic::convert_to_fp16:
1067 case Intrinsic::x86_sse_cvtss2si:
1068 case Intrinsic::x86_sse_cvtss2si64:
1069 case Intrinsic::x86_sse_cvttss2si:
1070 case Intrinsic::x86_sse_cvttss2si64:
1071 case Intrinsic::x86_sse2_cvtsd2si:
1072 case Intrinsic::x86_sse2_cvtsd2si64:
1073 case Intrinsic::x86_sse2_cvttsd2si:
1074 case Intrinsic::x86_sse2_cvttsd2si64:
1081 if (!F->hasName()) return false;
1082 StringRef Name = F->getName();
1084 // In these cases, the check of the length is required. We don't want to
1085 // return true for a name like "cos\0blah" which strcmp would return equal to
1086 // "cos", but has length 8.
1088 default: return false;
1090 return Name == "acos" || Name == "asin" ||
1091 Name == "atan" || Name == "atan2";
1093 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1095 return Name == "exp" || Name == "exp2";
1097 return Name == "fabs" || Name == "fmod" || Name == "floor";
1099 return Name == "log" || Name == "log10";
1101 return Name == "pow";
1103 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1104 Name == "sinf" || Name == "sqrtf";
1106 return Name == "tan" || Name == "tanh";
1110 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1112 sys::llvm_fenv_clearexcept();
1114 if (sys::llvm_fenv_testexcept()) {
1115 sys::llvm_fenv_clearexcept();
1119 if (Ty->isFloatTy())
1120 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1121 if (Ty->isDoubleTy())
1122 return ConstantFP::get(Ty->getContext(), APFloat(V));
1123 llvm_unreachable("Can only constant fold float/double");
1124 return 0; // dummy return to suppress warning
1127 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1128 double V, double W, Type *Ty) {
1129 sys::llvm_fenv_clearexcept();
1131 if (sys::llvm_fenv_testexcept()) {
1132 sys::llvm_fenv_clearexcept();
1136 if (Ty->isFloatTy())
1137 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1138 if (Ty->isDoubleTy())
1139 return ConstantFP::get(Ty->getContext(), APFloat(V));
1140 llvm_unreachable("Can only constant fold float/double");
1141 return 0; // dummy return to suppress warning
1144 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1145 /// conversion of a constant floating point. If roundTowardZero is false, the
1146 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1147 /// the behavior of the non-truncating SSE instructions in the default rounding
1148 /// mode. The desired integer type Ty is used to select how many bits are
1149 /// available for the result. Returns null if the conversion cannot be
1150 /// performed, otherwise returns the Constant value resulting from the
1152 static Constant *ConstantFoldConvertToInt(ConstantFP *Op, bool roundTowardZero,
1154 assert(Op && "Called with NULL operand");
1155 APFloat Val(Op->getValueAPF());
1157 // All of these conversion intrinsics form an integer of at most 64bits.
1158 unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
1159 assert(ResultWidth <= 64 &&
1160 "Can only constant fold conversions to 64 and 32 bit ints");
1163 bool isExact = false;
1164 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1165 : APFloat::rmNearestTiesToEven;
1166 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1167 /*isSigned=*/true, mode,
1169 if (status != APFloat::opOK && status != APFloat::opInexact)
1171 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1174 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1175 /// with the specified arguments, returning null if unsuccessful.
1177 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands) {
1178 if (!F->hasName()) return 0;
1179 StringRef Name = F->getName();
1181 Type *Ty = F->getReturnType();
1182 if (Operands.size() == 1) {
1183 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1184 if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1185 APFloat Val(Op->getValueAPF());
1188 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1190 return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1193 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1196 /// We only fold functions with finite arguments. Folding NaN and inf is
1197 /// likely to be aborted with an exception anyway, and some host libms
1198 /// have known errors raising exceptions.
1199 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1202 /// Currently APFloat versions of these functions do not exist, so we use
1203 /// the host native double versions. Float versions are not called
1204 /// directly but for all these it is true (float)(f((double)arg)) ==
1205 /// f(arg). Long double not supported yet.
1206 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
1207 Op->getValueAPF().convertToDouble();
1211 return ConstantFoldFP(acos, V, Ty);
1212 else if (Name == "asin")
1213 return ConstantFoldFP(asin, V, Ty);
1214 else if (Name == "atan")
1215 return ConstantFoldFP(atan, V, Ty);
1219 return ConstantFoldFP(ceil, V, Ty);
1220 else if (Name == "cos")
1221 return ConstantFoldFP(cos, V, Ty);
1222 else if (Name == "cosh")
1223 return ConstantFoldFP(cosh, V, Ty);
1224 else if (Name == "cosf")
1225 return ConstantFoldFP(cos, V, Ty);
1229 return ConstantFoldFP(exp, V, Ty);
1231 if (Name == "exp2") {
1232 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1234 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1239 return ConstantFoldFP(fabs, V, Ty);
1240 else if (Name == "floor")
1241 return ConstantFoldFP(floor, V, Ty);
1244 if (Name == "log" && V > 0)
1245 return ConstantFoldFP(log, V, Ty);
1246 else if (Name == "log10" && V > 0)
1247 return ConstantFoldFP(log10, V, Ty);
1248 else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1249 (Ty->isFloatTy() || Ty->isDoubleTy())) {
1251 return ConstantFoldFP(sqrt, V, Ty);
1253 return Constant::getNullValue(Ty);
1258 return ConstantFoldFP(sin, V, Ty);
1259 else if (Name == "sinh")
1260 return ConstantFoldFP(sinh, V, Ty);
1261 else if (Name == "sqrt" && V >= 0)
1262 return ConstantFoldFP(sqrt, V, Ty);
1263 else if (Name == "sqrtf" && V >= 0)
1264 return ConstantFoldFP(sqrt, V, Ty);
1265 else if (Name == "sinf")
1266 return ConstantFoldFP(sin, V, Ty);
1270 return ConstantFoldFP(tan, V, Ty);
1271 else if (Name == "tanh")
1272 return ConstantFoldFP(tanh, V, Ty);
1280 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1281 switch (F->getIntrinsicID()) {
1282 case Intrinsic::bswap:
1283 return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1284 case Intrinsic::ctpop:
1285 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1286 case Intrinsic::cttz:
1287 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
1288 case Intrinsic::ctlz:
1289 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
1290 case Intrinsic::convert_from_fp16: {
1291 APFloat Val(Op->getValue());
1294 APFloat::opStatus status =
1295 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1297 // Conversion is always precise.
1299 assert(status == APFloat::opOK && !lost &&
1300 "Precision lost during fp16 constfolding");
1302 return ConstantFP::get(F->getContext(), Val);
1309 if (ConstantVector *Op = dyn_cast<ConstantVector>(Operands[0])) {
1310 switch (F->getIntrinsicID()) {
1312 case Intrinsic::x86_sse_cvtss2si:
1313 case Intrinsic::x86_sse_cvtss2si64:
1314 case Intrinsic::x86_sse2_cvtsd2si:
1315 case Intrinsic::x86_sse2_cvtsd2si64:
1316 if (ConstantFP *FPOp = dyn_cast<ConstantFP>(Op->getOperand(0)))
1317 return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=*/false, Ty);
1318 case Intrinsic::x86_sse_cvttss2si:
1319 case Intrinsic::x86_sse_cvttss2si64:
1320 case Intrinsic::x86_sse2_cvttsd2si:
1321 case Intrinsic::x86_sse2_cvttsd2si64:
1322 if (ConstantFP *FPOp = dyn_cast<ConstantFP>(Op->getOperand(0)))
1323 return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=*/true, Ty);
1327 if (isa<UndefValue>(Operands[0])) {
1328 if (F->getIntrinsicID() == Intrinsic::bswap)
1336 if (Operands.size() == 2) {
1337 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1338 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1340 double Op1V = Ty->isFloatTy() ?
1341 (double)Op1->getValueAPF().convertToFloat() :
1342 Op1->getValueAPF().convertToDouble();
1343 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1344 if (Op2->getType() != Op1->getType())
1347 double Op2V = Ty->isFloatTy() ?
1348 (double)Op2->getValueAPF().convertToFloat():
1349 Op2->getValueAPF().convertToDouble();
1352 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1354 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1355 if (Name == "atan2")
1356 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1357 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1358 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
1359 return ConstantFP::get(F->getContext(),
1360 APFloat((float)std::pow((float)Op1V,
1361 (int)Op2C->getZExtValue())));
1362 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
1363 return ConstantFP::get(F->getContext(),
1364 APFloat((double)std::pow((double)Op1V,
1365 (int)Op2C->getZExtValue())));
1371 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1372 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1373 switch (F->getIntrinsicID()) {
1375 case Intrinsic::sadd_with_overflow:
1376 case Intrinsic::uadd_with_overflow:
1377 case Intrinsic::ssub_with_overflow:
1378 case Intrinsic::usub_with_overflow:
1379 case Intrinsic::smul_with_overflow:
1380 case Intrinsic::umul_with_overflow: {
1383 switch (F->getIntrinsicID()) {
1384 default: assert(0 && "Invalid case");
1385 case Intrinsic::sadd_with_overflow:
1386 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1388 case Intrinsic::uadd_with_overflow:
1389 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1391 case Intrinsic::ssub_with_overflow:
1392 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1394 case Intrinsic::usub_with_overflow:
1395 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1397 case Intrinsic::smul_with_overflow:
1398 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1400 case Intrinsic::umul_with_overflow:
1401 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1405 ConstantInt::get(F->getContext(), Res),
1406 ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1408 return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);