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/Target/TargetLibraryInfo.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/FEnv.h"
40 //===----------------------------------------------------------------------===//
41 // Constant Folding internal helper functions
42 //===----------------------------------------------------------------------===//
44 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
45 /// TargetData. This always returns a non-null constant, but it may be a
46 /// ConstantExpr if unfoldable.
47 static Constant *FoldBitCast(Constant *C, Type *DestTy,
48 const TargetData &TD) {
49 // Catch the obvious splat cases.
50 if (C->isNullValue() && !DestTy->isX86_MMXTy())
51 return Constant::getNullValue(DestTy);
52 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
53 return Constant::getAllOnesValue(DestTy);
55 // The code below only handles casts to vectors currently.
56 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
58 return ConstantExpr::getBitCast(C, DestTy);
60 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
61 // vector so the code below can handle it uniformly.
62 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
63 Constant *Ops = C; // don't take the address of C!
64 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
67 // If this is a bitcast from constant vector -> vector, fold it.
68 // FIXME: Remove ConstantVector support.
69 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
70 return ConstantExpr::getBitCast(C, DestTy);
72 // If the element types match, VMCore can fold it.
73 unsigned NumDstElt = DestVTy->getNumElements();
74 unsigned NumSrcElt = C->getType()->getVectorNumElements();
75 if (NumDstElt == NumSrcElt)
76 return ConstantExpr::getBitCast(C, DestTy);
78 Type *SrcEltTy = C->getType()->getVectorElementType();
79 Type *DstEltTy = DestVTy->getElementType();
81 // Otherwise, we're changing the number of elements in a vector, which
82 // requires endianness information to do the right thing. For example,
83 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
84 // folds to (little endian):
85 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
86 // and to (big endian):
87 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
89 // First thing is first. We only want to think about integer here, so if
90 // we have something in FP form, recast it as integer.
91 if (DstEltTy->isFloatingPointTy()) {
92 // Fold to an vector of integers with same size as our FP type.
93 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
95 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
96 // Recursively handle this integer conversion, if possible.
97 C = FoldBitCast(C, DestIVTy, TD);
99 // Finally, VMCore can handle this now that #elts line up.
100 return ConstantExpr::getBitCast(C, DestTy);
103 // Okay, we know the destination is integer, if the input is FP, convert
104 // it to integer first.
105 if (SrcEltTy->isFloatingPointTy()) {
106 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
108 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
109 // Ask VMCore to do the conversion now that #elts line up.
110 C = ConstantExpr::getBitCast(C, SrcIVTy);
111 // If VMCore wasn't able to fold it, bail out.
112 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
113 !isa<ConstantDataVector>(C))
117 // Now we know that the input and output vectors are both integer vectors
118 // of the same size, and that their #elements is not the same. Do the
119 // conversion here, which depends on whether the input or output has
121 bool isLittleEndian = TD.isLittleEndian();
123 SmallVector<Constant*, 32> Result;
124 if (NumDstElt < NumSrcElt) {
125 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
126 Constant *Zero = Constant::getNullValue(DstEltTy);
127 unsigned Ratio = NumSrcElt/NumDstElt;
128 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
130 for (unsigned i = 0; i != NumDstElt; ++i) {
131 // Build each element of the result.
132 Constant *Elt = Zero;
133 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
134 for (unsigned j = 0; j != Ratio; ++j) {
135 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
136 if (!Src) // Reject constantexpr elements.
137 return ConstantExpr::getBitCast(C, DestTy);
139 // Zero extend the element to the right size.
140 Src = ConstantExpr::getZExt(Src, Elt->getType());
142 // Shift it to the right place, depending on endianness.
143 Src = ConstantExpr::getShl(Src,
144 ConstantInt::get(Src->getType(), ShiftAmt));
145 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
148 Elt = ConstantExpr::getOr(Elt, Src);
150 Result.push_back(Elt);
152 return ConstantVector::get(Result);
155 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
156 unsigned Ratio = NumDstElt/NumSrcElt;
157 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
159 // Loop over each source value, expanding into multiple results.
160 for (unsigned i = 0; i != NumSrcElt; ++i) {
161 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
162 if (!Src) // Reject constantexpr elements.
163 return ConstantExpr::getBitCast(C, DestTy);
165 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
166 for (unsigned j = 0; j != Ratio; ++j) {
167 // Shift the piece of the value into the right place, depending on
169 Constant *Elt = ConstantExpr::getLShr(Src,
170 ConstantInt::get(Src->getType(), ShiftAmt));
171 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
173 // Truncate and remember this piece.
174 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
178 return ConstantVector::get(Result);
182 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
183 /// from a global, return the global and the constant. Because of
184 /// constantexprs, this function is recursive.
185 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
186 int64_t &Offset, const TargetData &TD) {
187 // Trivial case, constant is the global.
188 if ((GV = dyn_cast<GlobalValue>(C))) {
193 // Otherwise, if this isn't a constant expr, bail out.
194 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
195 if (!CE) return false;
197 // Look through ptr->int and ptr->ptr casts.
198 if (CE->getOpcode() == Instruction::PtrToInt ||
199 CE->getOpcode() == Instruction::BitCast)
200 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
202 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
203 if (CE->getOpcode() == Instruction::GetElementPtr) {
204 // Cannot compute this if the element type of the pointer is missing size
206 if (!cast<PointerType>(CE->getOperand(0)->getType())
207 ->getElementType()->isSized())
210 // If the base isn't a global+constant, we aren't either.
211 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
214 // Otherwise, add any offset that our operands provide.
215 gep_type_iterator GTI = gep_type_begin(CE);
216 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
217 i != e; ++i, ++GTI) {
218 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
219 if (!CI) return false; // Index isn't a simple constant?
220 if (CI->isZero()) continue; // Not adding anything.
222 if (StructType *ST = dyn_cast<StructType>(*GTI)) {
224 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
226 SequentialType *SQT = cast<SequentialType>(*GTI);
227 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
236 /// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
237 /// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
238 /// pointer to copy results into and BytesLeft is the number of bytes left in
239 /// the CurPtr buffer. TD is the target data.
240 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
241 unsigned char *CurPtr, unsigned BytesLeft,
242 const TargetData &TD) {
243 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
244 "Out of range access");
246 // If this element is zero or undefined, we can just return since *CurPtr is
248 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
251 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
252 if (CI->getBitWidth() > 64 ||
253 (CI->getBitWidth() & 7) != 0)
256 uint64_t Val = CI->getZExtValue();
257 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
259 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
260 CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
266 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
267 if (CFP->getType()->isDoubleTy()) {
268 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
269 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
271 if (CFP->getType()->isFloatTy()){
272 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
273 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
278 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
279 const StructLayout *SL = TD.getStructLayout(CS->getType());
280 unsigned Index = SL->getElementContainingOffset(ByteOffset);
281 uint64_t CurEltOffset = SL->getElementOffset(Index);
282 ByteOffset -= CurEltOffset;
285 // If the element access is to the element itself and not to tail padding,
286 // read the bytes from the element.
287 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
289 if (ByteOffset < EltSize &&
290 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
296 // Check to see if we read from the last struct element, if so we're done.
297 if (Index == CS->getType()->getNumElements())
300 // If we read all of the bytes we needed from this element we're done.
301 uint64_t NextEltOffset = SL->getElementOffset(Index);
303 if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
306 // Move to the next element of the struct.
307 CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
308 BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
310 CurEltOffset = NextEltOffset;
315 // FIXME: Remove ConstantVector
316 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
317 isa<ConstantDataSequential>(C)) {
318 Type *EltTy = cast<SequentialType>(C->getType())->getElementType();
319 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
320 uint64_t Index = ByteOffset / EltSize;
321 uint64_t Offset = ByteOffset - Index * EltSize;
323 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
324 NumElts = AT->getNumElements();
326 NumElts = cast<VectorType>(C->getType())->getNumElements();
328 for (; Index != NumElts; ++Index) {
329 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
332 if (EltSize >= BytesLeft)
336 BytesLeft -= EltSize;
342 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
343 if (CE->getOpcode() == Instruction::IntToPtr &&
344 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext()))
345 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
349 // Otherwise, unknown initializer type.
353 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
354 const TargetData &TD) {
355 Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
356 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
358 // If this isn't an integer load we can't fold it directly.
360 // If this is a float/double load, we can try folding it as an int32/64 load
361 // and then bitcast the result. This can be useful for union cases. Note
362 // that address spaces don't matter here since we're not going to result in
363 // an actual new load.
365 if (LoadTy->isFloatTy())
366 MapTy = Type::getInt32PtrTy(C->getContext());
367 else if (LoadTy->isDoubleTy())
368 MapTy = Type::getInt64PtrTy(C->getContext());
369 else if (LoadTy->isVectorTy()) {
370 MapTy = IntegerType::get(C->getContext(),
371 TD.getTypeAllocSizeInBits(LoadTy));
372 MapTy = PointerType::getUnqual(MapTy);
376 C = FoldBitCast(C, MapTy, TD);
377 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
378 return FoldBitCast(Res, LoadTy, TD);
382 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
383 if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
387 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
390 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
391 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
392 !GV->getInitializer()->getType()->isSized())
395 // If we're loading off the beginning of the global, some bytes may be valid,
396 // but we don't try to handle this.
397 if (Offset < 0) return 0;
399 // If we're not accessing anything in this constant, the result is undefined.
400 if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
401 return UndefValue::get(IntType);
403 unsigned char RawBytes[32] = {0};
404 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
408 APInt ResultVal = APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1]);
409 for (unsigned i = 1; i != BytesLoaded; ++i) {
411 ResultVal |= RawBytes[BytesLoaded-1-i];
414 return ConstantInt::get(IntType->getContext(), ResultVal);
417 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
418 /// produce if it is constant and determinable. If this is not determinable,
420 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
421 const TargetData *TD) {
422 // First, try the easy cases:
423 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
424 if (GV->isConstant() && GV->hasDefinitiveInitializer())
425 return GV->getInitializer();
427 // If the loaded value isn't a constant expr, we can't handle it.
428 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
431 if (CE->getOpcode() == Instruction::GetElementPtr) {
432 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
433 if (GV->isConstant() && GV->hasDefinitiveInitializer())
435 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
439 // Instead of loading constant c string, use corresponding integer value
440 // directly if string length is small enough.
442 if (TD && GetConstantStringInfo(CE, Str) && !Str.empty()) {
443 unsigned StrLen = Str.length();
444 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
445 unsigned NumBits = Ty->getPrimitiveSizeInBits();
446 // Replace load with immediate integer if the result is an integer or fp
448 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
449 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
450 APInt StrVal(NumBits, 0);
451 APInt SingleChar(NumBits, 0);
452 if (TD->isLittleEndian()) {
453 for (signed i = StrLen-1; i >= 0; i--) {
454 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
455 StrVal = (StrVal << 8) | SingleChar;
458 for (unsigned i = 0; i < StrLen; i++) {
459 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
460 StrVal = (StrVal << 8) | SingleChar;
462 // Append NULL at the end.
464 StrVal = (StrVal << 8) | SingleChar;
467 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
468 if (Ty->isFloatingPointTy())
469 Res = ConstantExpr::getBitCast(Res, Ty);
474 // If this load comes from anywhere in a constant global, and if the global
475 // is all undef or zero, we know what it loads.
476 if (GlobalVariable *GV =
477 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
478 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
479 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
480 if (GV->getInitializer()->isNullValue())
481 return Constant::getNullValue(ResTy);
482 if (isa<UndefValue>(GV->getInitializer()))
483 return UndefValue::get(ResTy);
487 // Try hard to fold loads from bitcasted strange and non-type-safe things. We
488 // currently don't do any of this for big endian systems. It can be
489 // generalized in the future if someone is interested.
490 if (TD && TD->isLittleEndian())
491 return FoldReinterpretLoadFromConstPtr(CE, *TD);
495 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
496 if (LI->isVolatile()) return 0;
498 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
499 return ConstantFoldLoadFromConstPtr(C, TD);
504 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
505 /// Attempt to symbolically evaluate the result of a binary operator merging
506 /// these together. If target data info is available, it is provided as TD,
507 /// otherwise TD is null.
508 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
509 Constant *Op1, const TargetData *TD){
512 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
513 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
517 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
518 // constant. This happens frequently when iterating over a global array.
519 if (Opc == Instruction::Sub && TD) {
520 GlobalValue *GV1, *GV2;
521 int64_t Offs1, Offs2;
523 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
524 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
526 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
527 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
534 /// CastGEPIndices - If array indices are not pointer-sized integers,
535 /// explicitly cast them so that they aren't implicitly casted by the
537 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
538 Type *ResultTy, const TargetData *TD,
539 const TargetLibraryInfo *TLI) {
541 Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
544 SmallVector<Constant*, 32> NewIdxs;
545 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
547 !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
548 Ops.slice(1, i-1)))) &&
549 Ops[i]->getType() != IntPtrTy) {
551 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
557 NewIdxs.push_back(Ops[i]);
562 ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
563 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
564 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
569 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
570 /// constant expression, do so.
571 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
572 Type *ResultTy, const TargetData *TD,
573 const TargetLibraryInfo *TLI) {
574 Constant *Ptr = Ops[0];
575 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized() ||
576 !Ptr->getType()->isPointerTy())
579 Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
581 // If this is a constant expr gep that is effectively computing an
582 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
583 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
584 if (!isa<ConstantInt>(Ops[i])) {
586 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
587 // "inttoptr (sub (ptrtoint Ptr), V)"
588 if (Ops.size() == 2 &&
589 cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
590 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
591 assert((CE == 0 || CE->getType() == IntPtrTy) &&
592 "CastGEPIndices didn't canonicalize index types!");
593 if (CE && CE->getOpcode() == Instruction::Sub &&
594 CE->getOperand(0)->isNullValue()) {
595 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
596 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
597 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
598 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
599 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
606 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
608 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
609 makeArrayRef((Value **)Ops.data() + 1,
611 Ptr = cast<Constant>(Ptr->stripPointerCasts());
613 // If this is a GEP of a GEP, fold it all into a single GEP.
614 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
615 SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
617 // Do not try the incorporate the sub-GEP if some index is not a number.
618 bool AllConstantInt = true;
619 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
620 if (!isa<ConstantInt>(NestedOps[i])) {
621 AllConstantInt = false;
627 Ptr = cast<Constant>(GEP->getOperand(0));
628 Offset += APInt(BitWidth,
629 TD->getIndexedOffset(Ptr->getType(), NestedOps));
630 Ptr = cast<Constant>(Ptr->stripPointerCasts());
633 // If the base value for this address is a literal integer value, fold the
634 // getelementptr to the resulting integer value casted to the pointer type.
635 APInt BasePtr(BitWidth, 0);
636 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
637 if (CE->getOpcode() == Instruction::IntToPtr)
638 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
639 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
640 if (Ptr->isNullValue() || BasePtr != 0) {
641 Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
642 return ConstantExpr::getIntToPtr(C, ResultTy);
645 // Otherwise form a regular getelementptr. Recompute the indices so that
646 // we eliminate over-indexing of the notional static type array bounds.
647 // This makes it easy to determine if the getelementptr is "inbounds".
648 // Also, this helps GlobalOpt do SROA on GlobalVariables.
649 Type *Ty = Ptr->getType();
650 SmallVector<Constant*, 32> NewIdxs;
652 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
653 if (ATy->isPointerTy()) {
654 // The only pointer indexing we'll do is on the first index of the GEP.
655 if (!NewIdxs.empty())
658 // Only handle pointers to sized types, not pointers to functions.
659 if (!ATy->getElementType()->isSized())
663 // Determine which element of the array the offset points into.
664 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
665 IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
667 // The element size is 0. This may be [0 x Ty]*, so just use a zero
668 // index for this level and proceed to the next level to see if it can
669 // accommodate the offset.
670 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
672 // The element size is non-zero divide the offset by the element
673 // size (rounding down), to compute the index at this level.
674 APInt NewIdx = Offset.udiv(ElemSize);
675 Offset -= NewIdx * ElemSize;
676 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
678 Ty = ATy->getElementType();
679 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
680 // Determine which field of the struct the offset points into. The
681 // getZExtValue is at least as safe as the StructLayout API because we
682 // know the offset is within the struct at this point.
683 const StructLayout &SL = *TD->getStructLayout(STy);
684 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
685 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
687 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
688 Ty = STy->getTypeAtIndex(ElIdx);
690 // We've reached some non-indexable type.
693 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
695 // If we haven't used up the entire offset by descending the static
696 // type, then the offset is pointing into the middle of an indivisible
697 // member, so we can't simplify it.
703 ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
704 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
705 "Computed GetElementPtr has unexpected type!");
707 // If we ended up indexing a member with a type that doesn't match
708 // the type of what the original indices indexed, add a cast.
709 if (Ty != cast<PointerType>(ResultTy)->getElementType())
710 C = FoldBitCast(C, ResultTy, *TD);
717 //===----------------------------------------------------------------------===//
718 // Constant Folding public APIs
719 //===----------------------------------------------------------------------===//
721 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
722 /// If successful, the constant result is returned, if not, null is returned.
723 /// Note that this fails if not all of the operands are constant. Otherwise,
724 /// this function can only fail when attempting to fold instructions like loads
725 /// and stores, which have no constant expression form.
726 Constant *llvm::ConstantFoldInstruction(Instruction *I,
727 const TargetData *TD,
728 const TargetLibraryInfo *TLI) {
729 // Handle PHI nodes quickly here...
730 if (PHINode *PN = dyn_cast<PHINode>(I)) {
731 Constant *CommonValue = 0;
733 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
734 Value *Incoming = PN->getIncomingValue(i);
735 // If the incoming value is undef then skip it. Note that while we could
736 // skip the value if it is equal to the phi node itself we choose not to
737 // because that would break the rule that constant folding only applies if
738 // all operands are constants.
739 if (isa<UndefValue>(Incoming))
741 // If the incoming value is not a constant, or is a different constant to
742 // the one we saw previously, then give up.
743 Constant *C = dyn_cast<Constant>(Incoming);
744 if (!C || (CommonValue && C != CommonValue))
749 // If we reach here, all incoming values are the same constant or undef.
750 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
753 // Scan the operand list, checking to see if they are all constants, if so,
754 // hand off to ConstantFoldInstOperands.
755 SmallVector<Constant*, 8> Ops;
756 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
757 if (Constant *Op = dyn_cast<Constant>(*i))
760 return 0; // All operands not constant!
762 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
763 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
766 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
767 return ConstantFoldLoadInst(LI, TD);
769 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
770 return ConstantExpr::getInsertValue(
771 cast<Constant>(IVI->getAggregateOperand()),
772 cast<Constant>(IVI->getInsertedValueOperand()),
775 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
776 return ConstantExpr::getExtractValue(
777 cast<Constant>(EVI->getAggregateOperand()),
780 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
783 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
784 /// using the specified TargetData. If successful, the constant result is
785 /// result is returned, if not, null is returned.
786 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
787 const TargetData *TD,
788 const TargetLibraryInfo *TLI) {
789 SmallVector<Constant*, 8> Ops;
790 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end();
792 Constant *NewC = cast<Constant>(*i);
793 // Recursively fold the ConstantExpr's operands.
794 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC))
795 NewC = ConstantFoldConstantExpression(NewCE, TD, TLI);
800 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
802 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
805 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
806 /// specified opcode and operands. If successful, the constant result is
807 /// returned, if not, null is returned. Note that this function can fail when
808 /// attempting to fold instructions like loads and stores, which have no
809 /// constant expression form.
811 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
812 /// information, due to only being passed an opcode and operands. Constant
813 /// folding using this function strips this information.
815 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
816 ArrayRef<Constant *> Ops,
817 const TargetData *TD,
818 const TargetLibraryInfo *TLI) {
819 // Handle easy binops first.
820 if (Instruction::isBinaryOp(Opcode)) {
821 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
822 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
825 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
830 case Instruction::ICmp:
831 case Instruction::FCmp: assert(0 && "Invalid for compares");
832 case Instruction::Call:
833 if (Function *F = dyn_cast<Function>(Ops.back()))
834 if (canConstantFoldCallTo(F))
835 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
837 case Instruction::PtrToInt:
838 // If the input is a inttoptr, eliminate the pair. This requires knowing
839 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
840 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
841 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
842 Constant *Input = CE->getOperand(0);
843 unsigned InWidth = Input->getType()->getScalarSizeInBits();
844 if (TD->getPointerSizeInBits() < InWidth) {
846 ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
847 TD->getPointerSizeInBits()));
848 Input = ConstantExpr::getAnd(Input, Mask);
850 // Do a zext or trunc to get to the dest size.
851 return ConstantExpr::getIntegerCast(Input, DestTy, false);
854 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
855 case Instruction::IntToPtr:
856 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
857 // the int size is >= the ptr size. This requires knowing the width of a
858 // pointer, so it can't be done in ConstantExpr::getCast.
859 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
861 TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
862 CE->getOpcode() == Instruction::PtrToInt)
863 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
865 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
866 case Instruction::Trunc:
867 case Instruction::ZExt:
868 case Instruction::SExt:
869 case Instruction::FPTrunc:
870 case Instruction::FPExt:
871 case Instruction::UIToFP:
872 case Instruction::SIToFP:
873 case Instruction::FPToUI:
874 case Instruction::FPToSI:
875 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
876 case Instruction::BitCast:
878 return FoldBitCast(Ops[0], DestTy, *TD);
879 return ConstantExpr::getBitCast(Ops[0], DestTy);
880 case Instruction::Select:
881 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
882 case Instruction::ExtractElement:
883 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
884 case Instruction::InsertElement:
885 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
886 case Instruction::ShuffleVector:
887 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
888 case Instruction::GetElementPtr:
889 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
891 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
894 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
898 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
899 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
900 /// returns a constant expression of the specified operands.
902 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
903 Constant *Ops0, Constant *Ops1,
904 const TargetData *TD,
905 const TargetLibraryInfo *TLI) {
906 // fold: icmp (inttoptr x), null -> icmp x, 0
907 // fold: icmp (ptrtoint x), 0 -> icmp x, null
908 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
909 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
911 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
912 // around to know if bit truncation is happening.
913 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
914 if (TD && Ops1->isNullValue()) {
915 Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
916 if (CE0->getOpcode() == Instruction::IntToPtr) {
917 // Convert the integer value to the right size to ensure we get the
918 // proper extension or truncation.
919 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
921 Constant *Null = Constant::getNullValue(C->getType());
922 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
925 // Only do this transformation if the int is intptrty in size, otherwise
926 // there is a truncation or extension that we aren't modeling.
927 if (CE0->getOpcode() == Instruction::PtrToInt &&
928 CE0->getType() == IntPtrTy) {
929 Constant *C = CE0->getOperand(0);
930 Constant *Null = Constant::getNullValue(C->getType());
931 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
935 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
936 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
937 Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
939 if (CE0->getOpcode() == Instruction::IntToPtr) {
940 // Convert the integer value to the right size to ensure we get the
941 // proper extension or truncation.
942 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
944 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
946 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
949 // Only do this transformation if the int is intptrty in size, otherwise
950 // there is a truncation or extension that we aren't modeling.
951 if ((CE0->getOpcode() == Instruction::PtrToInt &&
952 CE0->getType() == IntPtrTy &&
953 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
954 return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
955 CE1->getOperand(0), TD, TLI);
959 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
960 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
961 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
962 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
964 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
967 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
970 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
971 Constant *Ops[] = { LHS, RHS };
972 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
976 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
980 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
981 /// getelementptr constantexpr, return the constant value being addressed by the
982 /// constant expression, or null if something is funny and we can't decide.
983 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
985 if (!CE->getOperand(1)->isNullValue())
986 return 0; // Do not allow stepping over the value!
988 // Loop over all of the operands, tracking down which value we are
990 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
991 C = C->getAggregateElement(CE->getOperand(i));
992 if (C == 0) return 0;
997 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
998 /// indices (with an *implied* zero pointer index that is not in the list),
999 /// return the constant value being addressed by a virtual load, or null if
1000 /// something is funny and we can't decide.
1001 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1002 ArrayRef<Constant*> Indices) {
1003 // Loop over all of the operands, tracking down which value we are
1005 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1006 C = C->getAggregateElement(Indices[i]);
1007 if (C == 0) return 0;
1013 //===----------------------------------------------------------------------===//
1014 // Constant Folding for Calls
1017 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1018 /// the specified function.
1020 llvm::canConstantFoldCallTo(const Function *F) {
1021 switch (F->getIntrinsicID()) {
1022 case Intrinsic::sqrt:
1023 case Intrinsic::pow:
1024 case Intrinsic::powi:
1025 case Intrinsic::bswap:
1026 case Intrinsic::ctpop:
1027 case Intrinsic::ctlz:
1028 case Intrinsic::cttz:
1029 case Intrinsic::sadd_with_overflow:
1030 case Intrinsic::uadd_with_overflow:
1031 case Intrinsic::ssub_with_overflow:
1032 case Intrinsic::usub_with_overflow:
1033 case Intrinsic::smul_with_overflow:
1034 case Intrinsic::umul_with_overflow:
1035 case Intrinsic::convert_from_fp16:
1036 case Intrinsic::convert_to_fp16:
1037 case Intrinsic::x86_sse_cvtss2si:
1038 case Intrinsic::x86_sse_cvtss2si64:
1039 case Intrinsic::x86_sse_cvttss2si:
1040 case Intrinsic::x86_sse_cvttss2si64:
1041 case Intrinsic::x86_sse2_cvtsd2si:
1042 case Intrinsic::x86_sse2_cvtsd2si64:
1043 case Intrinsic::x86_sse2_cvttsd2si:
1044 case Intrinsic::x86_sse2_cvttsd2si64:
1051 if (!F->hasName()) return false;
1052 StringRef Name = F->getName();
1054 // In these cases, the check of the length is required. We don't want to
1055 // return true for a name like "cos\0blah" which strcmp would return equal to
1056 // "cos", but has length 8.
1058 default: return false;
1060 return Name == "acos" || Name == "asin" ||
1061 Name == "atan" || Name == "atan2";
1063 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1065 return Name == "exp" || Name == "exp2";
1067 return Name == "fabs" || Name == "fmod" || Name == "floor";
1069 return Name == "log" || Name == "log10";
1071 return Name == "pow";
1073 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1074 Name == "sinf" || Name == "sqrtf";
1076 return Name == "tan" || Name == "tanh";
1080 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1082 sys::llvm_fenv_clearexcept();
1084 if (sys::llvm_fenv_testexcept()) {
1085 sys::llvm_fenv_clearexcept();
1089 if (Ty->isFloatTy())
1090 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1091 if (Ty->isDoubleTy())
1092 return ConstantFP::get(Ty->getContext(), APFloat(V));
1093 llvm_unreachable("Can only constant fold float/double");
1096 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1097 double V, double W, Type *Ty) {
1098 sys::llvm_fenv_clearexcept();
1100 if (sys::llvm_fenv_testexcept()) {
1101 sys::llvm_fenv_clearexcept();
1105 if (Ty->isFloatTy())
1106 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1107 if (Ty->isDoubleTy())
1108 return ConstantFP::get(Ty->getContext(), APFloat(V));
1109 llvm_unreachable("Can only constant fold float/double");
1112 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1113 /// conversion of a constant floating point. If roundTowardZero is false, the
1114 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1115 /// the behavior of the non-truncating SSE instructions in the default rounding
1116 /// mode. The desired integer type Ty is used to select how many bits are
1117 /// available for the result. Returns null if the conversion cannot be
1118 /// performed, otherwise returns the Constant value resulting from the
1120 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1121 bool roundTowardZero, Type *Ty) {
1122 // All of these conversion intrinsics form an integer of at most 64bits.
1123 unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
1124 assert(ResultWidth <= 64 &&
1125 "Can only constant fold conversions to 64 and 32 bit ints");
1128 bool isExact = false;
1129 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1130 : APFloat::rmNearestTiesToEven;
1131 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1132 /*isSigned=*/true, mode,
1134 if (status != APFloat::opOK && status != APFloat::opInexact)
1136 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1139 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1140 /// with the specified arguments, returning null if unsuccessful.
1142 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1143 const TargetLibraryInfo *TLI) {
1144 if (!F->hasName()) return 0;
1145 StringRef Name = F->getName();
1147 Type *Ty = F->getReturnType();
1148 if (Operands.size() == 1) {
1149 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1150 if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1151 APFloat Val(Op->getValueAPF());
1154 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1156 return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1161 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1164 /// We only fold functions with finite arguments. Folding NaN and inf is
1165 /// likely to be aborted with an exception anyway, and some host libms
1166 /// have known errors raising exceptions.
1167 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1170 /// Currently APFloat versions of these functions do not exist, so we use
1171 /// the host native double versions. Float versions are not called
1172 /// directly but for all these it is true (float)(f((double)arg)) ==
1173 /// f(arg). Long double not supported yet.
1174 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
1175 Op->getValueAPF().convertToDouble();
1178 if (Name == "acos" && TLI->has(LibFunc::acos))
1179 return ConstantFoldFP(acos, V, Ty);
1180 else if (Name == "asin" && TLI->has(LibFunc::asin))
1181 return ConstantFoldFP(asin, V, Ty);
1182 else if (Name == "atan" && TLI->has(LibFunc::atan))
1183 return ConstantFoldFP(atan, V, Ty);
1186 if (Name == "ceil" && TLI->has(LibFunc::ceil))
1187 return ConstantFoldFP(ceil, V, Ty);
1188 else if (Name == "cos" && TLI->has(LibFunc::cos))
1189 return ConstantFoldFP(cos, V, Ty);
1190 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1191 return ConstantFoldFP(cosh, V, Ty);
1192 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1193 return ConstantFoldFP(cos, V, Ty);
1196 if (Name == "exp" && TLI->has(LibFunc::exp))
1197 return ConstantFoldFP(exp, V, Ty);
1199 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1200 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1202 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1206 if (Name == "fabs" && TLI->has(LibFunc::fabs))
1207 return ConstantFoldFP(fabs, V, Ty);
1208 else if (Name == "floor" && TLI->has(LibFunc::floor))
1209 return ConstantFoldFP(floor, V, Ty);
1212 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1213 return ConstantFoldFP(log, V, Ty);
1214 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1215 return ConstantFoldFP(log10, V, Ty);
1216 else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1217 (Ty->isFloatTy() || Ty->isDoubleTy())) {
1219 return ConstantFoldFP(sqrt, V, Ty);
1221 return Constant::getNullValue(Ty);
1225 if (Name == "sin" && TLI->has(LibFunc::sin))
1226 return ConstantFoldFP(sin, V, Ty);
1227 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1228 return ConstantFoldFP(sinh, V, Ty);
1229 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1230 return ConstantFoldFP(sqrt, V, Ty);
1231 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1232 return ConstantFoldFP(sqrt, V, Ty);
1233 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1234 return ConstantFoldFP(sin, V, Ty);
1237 if (Name == "tan" && TLI->has(LibFunc::tan))
1238 return ConstantFoldFP(tan, V, Ty);
1239 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1240 return ConstantFoldFP(tanh, V, Ty);
1248 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1249 switch (F->getIntrinsicID()) {
1250 case Intrinsic::bswap:
1251 return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1252 case Intrinsic::ctpop:
1253 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1254 case Intrinsic::convert_from_fp16: {
1255 APFloat Val(Op->getValue());
1258 APFloat::opStatus status =
1259 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1261 // Conversion is always precise.
1263 assert(status == APFloat::opOK && !lost &&
1264 "Precision lost during fp16 constfolding");
1266 return ConstantFP::get(F->getContext(), Val);
1273 // Support ConstantVector in case we have an Undef in the top.
1274 if (isa<ConstantVector>(Operands[0]) ||
1275 isa<ConstantDataVector>(Operands[0])) {
1276 Constant *Op = cast<Constant>(Operands[0]);
1277 switch (F->getIntrinsicID()) {
1279 case Intrinsic::x86_sse_cvtss2si:
1280 case Intrinsic::x86_sse_cvtss2si64:
1281 case Intrinsic::x86_sse2_cvtsd2si:
1282 case Intrinsic::x86_sse2_cvtsd2si64:
1283 if (ConstantFP *FPOp =
1284 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1285 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1286 /*roundTowardZero=*/false, Ty);
1287 case Intrinsic::x86_sse_cvttss2si:
1288 case Intrinsic::x86_sse_cvttss2si64:
1289 case Intrinsic::x86_sse2_cvttsd2si:
1290 case Intrinsic::x86_sse2_cvttsd2si64:
1291 if (ConstantFP *FPOp =
1292 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1293 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1294 /*roundTowardZero=*/true, Ty);
1298 if (isa<UndefValue>(Operands[0])) {
1299 if (F->getIntrinsicID() == Intrinsic::bswap)
1307 if (Operands.size() == 2) {
1308 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1309 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1311 double Op1V = Ty->isFloatTy() ?
1312 (double)Op1->getValueAPF().convertToFloat() :
1313 Op1->getValueAPF().convertToDouble();
1314 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1315 if (Op2->getType() != Op1->getType())
1318 double Op2V = Ty->isFloatTy() ?
1319 (double)Op2->getValueAPF().convertToFloat():
1320 Op2->getValueAPF().convertToDouble();
1322 if (F->getIntrinsicID() == Intrinsic::pow) {
1323 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1327 if (Name == "pow" && TLI->has(LibFunc::pow))
1328 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1329 if (Name == "fmod" && TLI->has(LibFunc::fmod))
1330 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1331 if (Name == "atan2" && TLI->has(LibFunc::atan2))
1332 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1333 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1334 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
1335 return ConstantFP::get(F->getContext(),
1336 APFloat((float)std::pow((float)Op1V,
1337 (int)Op2C->getZExtValue())));
1338 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
1339 return ConstantFP::get(F->getContext(),
1340 APFloat((double)std::pow((double)Op1V,
1341 (int)Op2C->getZExtValue())));
1346 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1347 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1348 switch (F->getIntrinsicID()) {
1350 case Intrinsic::sadd_with_overflow:
1351 case Intrinsic::uadd_with_overflow:
1352 case Intrinsic::ssub_with_overflow:
1353 case Intrinsic::usub_with_overflow:
1354 case Intrinsic::smul_with_overflow:
1355 case Intrinsic::umul_with_overflow: {
1358 switch (F->getIntrinsicID()) {
1359 default: assert(0 && "Invalid case");
1360 case Intrinsic::sadd_with_overflow:
1361 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1363 case Intrinsic::uadd_with_overflow:
1364 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1366 case Intrinsic::ssub_with_overflow:
1367 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1369 case Intrinsic::usub_with_overflow:
1370 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1372 case Intrinsic::smul_with_overflow:
1373 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1375 case Intrinsic::umul_with_overflow:
1376 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1380 ConstantInt::get(F->getContext(), Res),
1381 ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1383 return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
1385 case Intrinsic::cttz:
1386 // FIXME: This should check for Op2 == 1, and become unreachable if
1388 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1389 case Intrinsic::ctlz:
1390 // FIXME: This should check for Op2 == 1, and become unreachable if
1392 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());