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/LLVMContext.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"
38 //===----------------------------------------------------------------------===//
39 // Constant Folding internal helper functions
40 //===----------------------------------------------------------------------===//
42 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
43 /// from a global, return the global and the constant. Because of
44 /// constantexprs, this function is recursive.
45 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
46 int64_t &Offset, const TargetData &TD) {
47 // Trivial case, constant is the global.
48 if ((GV = dyn_cast<GlobalValue>(C))) {
53 // Otherwise, if this isn't a constant expr, bail out.
54 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
55 if (!CE) return false;
57 // Look through ptr->int and ptr->ptr casts.
58 if (CE->getOpcode() == Instruction::PtrToInt ||
59 CE->getOpcode() == Instruction::BitCast)
60 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
62 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
63 if (CE->getOpcode() == Instruction::GetElementPtr) {
64 // Cannot compute this if the element type of the pointer is missing size
66 if (!cast<PointerType>(CE->getOperand(0)->getType())
67 ->getElementType()->isSized())
70 // If the base isn't a global+constant, we aren't either.
71 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
74 // Otherwise, add any offset that our operands provide.
75 gep_type_iterator GTI = gep_type_begin(CE);
76 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
78 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
79 if (!CI) return false; // Index isn't a simple constant?
80 if (CI->getZExtValue() == 0) continue; // Not adding anything.
82 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
84 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
86 const SequentialType *SQT = cast<SequentialType>(*GTI);
87 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
96 /// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
97 /// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
98 /// pointer to copy results into and BytesLeft is the number of bytes left in
99 /// the CurPtr buffer. TD is the target data.
100 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
101 unsigned char *CurPtr, unsigned BytesLeft,
102 const TargetData &TD) {
103 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
104 "Out of range access");
106 // If this element is zero or undefined, we can just return since *CurPtr is
108 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
111 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
112 if (CI->getBitWidth() > 64 ||
113 (CI->getBitWidth() & 7) != 0)
116 uint64_t Val = CI->getZExtValue();
117 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
119 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
120 CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
126 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
127 if (CFP->getType()->isDoubleTy()) {
128 C = ConstantExpr::getBitCast(C, Type::getInt64Ty(C->getContext()));
129 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
131 if (CFP->getType()->isFloatTy()){
132 C = ConstantExpr::getBitCast(C, Type::getInt32Ty(C->getContext()));
133 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
138 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
139 const StructLayout *SL = TD.getStructLayout(CS->getType());
140 unsigned Index = SL->getElementContainingOffset(ByteOffset);
141 uint64_t CurEltOffset = SL->getElementOffset(Index);
142 ByteOffset -= CurEltOffset;
145 // If the element access is to the element itself and not to tail padding,
146 // read the bytes from the element.
147 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
149 if (ByteOffset < EltSize &&
150 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
156 // Check to see if we read from the last struct element, if so we're done.
157 if (Index == CS->getType()->getNumElements())
160 // If we read all of the bytes we needed from this element we're done.
161 uint64_t NextEltOffset = SL->getElementOffset(Index);
163 if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
166 // Move to the next element of the struct.
167 CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
168 BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
170 CurEltOffset = NextEltOffset;
175 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
176 uint64_t EltSize = TD.getTypeAllocSize(CA->getType()->getElementType());
177 uint64_t Index = ByteOffset / EltSize;
178 uint64_t Offset = ByteOffset - Index * EltSize;
179 for (; Index != CA->getType()->getNumElements(); ++Index) {
180 if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
183 if (EltSize >= BytesLeft)
187 BytesLeft -= EltSize;
193 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
194 uint64_t EltSize = TD.getTypeAllocSize(CV->getType()->getElementType());
195 uint64_t Index = ByteOffset / EltSize;
196 uint64_t Offset = ByteOffset - Index * EltSize;
197 for (; Index != CV->getType()->getNumElements(); ++Index) {
198 if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
201 if (EltSize >= BytesLeft)
205 BytesLeft -= EltSize;
211 // Otherwise, unknown initializer type.
215 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
216 const TargetData &TD) {
217 const Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
218 const IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
220 // If this isn't an integer load we can't fold it directly.
222 // If this is a float/double load, we can try folding it as an int32/64 load
223 // and then bitcast the result. This can be useful for union cases. Note
224 // that address spaces don't matter here since we're not going to result in
225 // an actual new load.
227 if (LoadTy->isFloatTy())
228 MapTy = Type::getInt32PtrTy(C->getContext());
229 else if (LoadTy->isDoubleTy())
230 MapTy = Type::getInt64PtrTy(C->getContext());
231 else if (isa<VectorType>(LoadTy)) {
232 MapTy = IntegerType::get(C->getContext(),
233 TD.getTypeAllocSizeInBits(LoadTy));
234 MapTy = PointerType::getUnqual(MapTy);
238 C = ConstantExpr::getBitCast(C, MapTy);
239 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
240 return ConstantExpr::getBitCast(Res, LoadTy);
244 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
245 if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
249 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
252 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
253 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
254 !GV->getInitializer()->getType()->isSized())
257 // If we're loading off the beginning of the global, some bytes may be valid,
258 // but we don't try to handle this.
259 if (Offset < 0) return 0;
261 // If we're not accessing anything in this constant, the result is undefined.
262 if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
263 return UndefValue::get(IntType);
265 unsigned char RawBytes[32] = {0};
266 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
270 APInt ResultVal(IntType->getBitWidth(), 0);
271 for (unsigned i = 0; i != BytesLoaded; ++i) {
273 ResultVal |= APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1-i]);
276 return ConstantInt::get(IntType->getContext(), ResultVal);
279 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
280 /// produce if it is constant and determinable. If this is not determinable,
282 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
283 const TargetData *TD) {
284 // First, try the easy cases:
285 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
286 if (GV->isConstant() && GV->hasDefinitiveInitializer())
287 return GV->getInitializer();
289 // If the loaded value isn't a constant expr, we can't handle it.
290 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
293 if (CE->getOpcode() == Instruction::GetElementPtr) {
294 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
295 if (GV->isConstant() && GV->hasDefinitiveInitializer())
297 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
301 // Instead of loading constant c string, use corresponding integer value
302 // directly if string length is small enough.
304 if (TD && GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
305 unsigned StrLen = Str.length();
306 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
307 unsigned NumBits = Ty->getPrimitiveSizeInBits();
308 // Replace LI with immediate integer store.
309 if ((NumBits >> 3) == StrLen + 1) {
310 APInt StrVal(NumBits, 0);
311 APInt SingleChar(NumBits, 0);
312 if (TD->isLittleEndian()) {
313 for (signed i = StrLen-1; i >= 0; i--) {
314 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
315 StrVal = (StrVal << 8) | SingleChar;
318 for (unsigned i = 0; i < StrLen; i++) {
319 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
320 StrVal = (StrVal << 8) | SingleChar;
322 // Append NULL at the end.
324 StrVal = (StrVal << 8) | SingleChar;
326 return ConstantInt::get(CE->getContext(), StrVal);
330 // If this load comes from anywhere in a constant global, and if the global
331 // is all undef or zero, we know what it loads.
332 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getUnderlyingObject())){
333 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
334 const Type *ResTy = cast<PointerType>(C->getType())->getElementType();
335 if (GV->getInitializer()->isNullValue())
336 return Constant::getNullValue(ResTy);
337 if (isa<UndefValue>(GV->getInitializer()))
338 return UndefValue::get(ResTy);
342 // Try hard to fold loads from bitcasted strange and non-type-safe things. We
343 // currently don't do any of this for big endian systems. It can be
344 // generalized in the future if someone is interested.
345 if (TD && TD->isLittleEndian())
346 return FoldReinterpretLoadFromConstPtr(CE, *TD);
350 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
351 if (LI->isVolatile()) return 0;
353 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
354 return ConstantFoldLoadFromConstPtr(C, TD);
359 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
360 /// Attempt to symbolically evaluate the result of a binary operator merging
361 /// these together. If target data info is available, it is provided as TD,
362 /// otherwise TD is null.
363 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
364 Constant *Op1, const TargetData *TD,
365 LLVMContext &Context){
368 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
369 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
373 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
374 // constant. This happens frequently when iterating over a global array.
375 if (Opc == Instruction::Sub && TD) {
376 GlobalValue *GV1, *GV2;
377 int64_t Offs1, Offs2;
379 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
380 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
382 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
383 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
390 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
391 /// constant expression, do so.
392 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
393 const Type *ResultTy,
394 LLVMContext &Context,
395 const TargetData *TD) {
396 Constant *Ptr = Ops[0];
397 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
400 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
401 APInt BasePtr(BitWidth, 0);
402 bool BaseIsInt = true;
403 if (!Ptr->isNullValue()) {
404 // If this is a inttoptr from a constant int, we can fold this as the base,
405 // otherwise we can't.
406 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
407 if (CE->getOpcode() == Instruction::IntToPtr)
408 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
409 BasePtr = Base->getValue();
410 BasePtr.zextOrTrunc(BitWidth);
417 // If this is a constant expr gep that is effectively computing an
418 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
419 for (unsigned i = 1; i != NumOps; ++i)
420 if (!isa<ConstantInt>(Ops[i]))
423 APInt Offset = APInt(BitWidth,
424 TD->getIndexedOffset(Ptr->getType(),
425 (Value**)Ops+1, NumOps-1));
426 // If the base value for this address is a literal integer value, fold the
427 // getelementptr to the resulting integer value casted to the pointer type.
429 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
430 return ConstantExpr::getIntToPtr(C, ResultTy);
433 // Otherwise form a regular getelementptr. Recompute the indices so that
434 // we eliminate over-indexing of the notional static type array bounds.
435 // This makes it easy to determine if the getelementptr is "inbounds".
436 // Also, this helps GlobalOpt do SROA on GlobalVariables.
437 const Type *Ty = Ptr->getType();
438 SmallVector<Constant*, 32> NewIdxs;
440 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
441 // The only pointer indexing we'll do is on the first index of the GEP.
442 if (isa<PointerType>(ATy) && !NewIdxs.empty())
444 // Determine which element of the array the offset points into.
445 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
448 APInt NewIdx = Offset.udiv(ElemSize);
449 Offset -= NewIdx * ElemSize;
450 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
451 Ty = ATy->getElementType();
452 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
453 // Determine which field of the struct the offset points into. The
454 // getZExtValue is at least as safe as the StructLayout API because we
455 // know the offset is within the struct at this point.
456 const StructLayout &SL = *TD->getStructLayout(STy);
457 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
458 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
459 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
460 Ty = STy->getTypeAtIndex(ElIdx);
462 // We've reached some non-indexable type.
465 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
467 // If we haven't used up the entire offset by descending the static
468 // type, then the offset is pointing into the middle of an indivisible
469 // member, so we can't simplify it.
475 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
476 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
477 "Computed GetElementPtr has unexpected type!");
479 // If we ended up indexing a member with a type that doesn't match
480 // the type of what the original indices indexed, add a cast.
481 if (Ty != cast<PointerType>(ResultTy)->getElementType())
482 C = ConstantExpr::getBitCast(C, ResultTy);
487 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
488 /// TargetData. This always returns a non-null constant, but it may be a
489 /// ConstantExpr if unfoldable.
490 static Constant *FoldBitCast(Constant *C, const Type *DestTy,
491 const TargetData &TD, LLVMContext &Context) {
492 // If this is a bitcast from constant vector -> vector, fold it.
493 ConstantVector *CV = dyn_cast<ConstantVector>(C);
495 return ConstantExpr::getBitCast(C, DestTy);
497 const VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
499 return ConstantExpr::getBitCast(C, DestTy);
501 // If the element types match, VMCore can fold it.
502 unsigned NumDstElt = DestVTy->getNumElements();
503 unsigned NumSrcElt = CV->getNumOperands();
504 if (NumDstElt == NumSrcElt)
505 return ConstantExpr::getBitCast(C, DestTy);
507 const Type *SrcEltTy = CV->getType()->getElementType();
508 const Type *DstEltTy = DestVTy->getElementType();
510 // Otherwise, we're changing the number of elements in a vector, which
511 // requires endianness information to do the right thing. For example,
512 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
513 // folds to (little endian):
514 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
515 // and to (big endian):
516 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
518 // First thing is first. We only want to think about integer here, so if
519 // we have something in FP form, recast it as integer.
520 if (DstEltTy->isFloatingPoint()) {
521 // Fold to an vector of integers with same size as our FP type.
522 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
523 const Type *DestIVTy = VectorType::get(
524 IntegerType::get(Context, FPWidth), NumDstElt);
525 // Recursively handle this integer conversion, if possible.
526 C = FoldBitCast(C, DestIVTy, TD, Context);
527 if (!C) return ConstantExpr::getBitCast(C, DestTy);
529 // Finally, VMCore can handle this now that #elts line up.
530 return ConstantExpr::getBitCast(C, DestTy);
533 // Okay, we know the destination is integer, if the input is FP, convert
534 // it to integer first.
535 if (SrcEltTy->isFloatingPoint()) {
536 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
537 const Type *SrcIVTy = VectorType::get(
538 IntegerType::get(Context, FPWidth), NumSrcElt);
539 // Ask VMCore to do the conversion now that #elts line up.
540 C = ConstantExpr::getBitCast(C, SrcIVTy);
541 CV = dyn_cast<ConstantVector>(C);
542 if (!CV) // If VMCore wasn't able to fold it, bail out.
546 // Now we know that the input and output vectors are both integer vectors
547 // of the same size, and that their #elements is not the same. Do the
548 // conversion here, which depends on whether the input or output has
550 bool isLittleEndian = TD.isLittleEndian();
552 SmallVector<Constant*, 32> Result;
553 if (NumDstElt < NumSrcElt) {
554 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
555 Constant *Zero = Constant::getNullValue(DstEltTy);
556 unsigned Ratio = NumSrcElt/NumDstElt;
557 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
559 for (unsigned i = 0; i != NumDstElt; ++i) {
560 // Build each element of the result.
561 Constant *Elt = Zero;
562 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
563 for (unsigned j = 0; j != Ratio; ++j) {
564 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
565 if (!Src) // Reject constantexpr elements.
566 return ConstantExpr::getBitCast(C, DestTy);
568 // Zero extend the element to the right size.
569 Src = ConstantExpr::getZExt(Src, Elt->getType());
571 // Shift it to the right place, depending on endianness.
572 Src = ConstantExpr::getShl(Src,
573 ConstantInt::get(Src->getType(), ShiftAmt));
574 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
577 Elt = ConstantExpr::getOr(Elt, Src);
579 Result.push_back(Elt);
582 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
583 unsigned Ratio = NumDstElt/NumSrcElt;
584 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
586 // Loop over each source value, expanding into multiple results.
587 for (unsigned i = 0; i != NumSrcElt; ++i) {
588 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
589 if (!Src) // Reject constantexpr elements.
590 return ConstantExpr::getBitCast(C, DestTy);
592 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
593 for (unsigned j = 0; j != Ratio; ++j) {
594 // Shift the piece of the value into the right place, depending on
596 Constant *Elt = ConstantExpr::getLShr(Src,
597 ConstantInt::get(Src->getType(), ShiftAmt));
598 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
600 // Truncate and remember this piece.
601 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
606 return ConstantVector::get(Result.data(), Result.size());
610 //===----------------------------------------------------------------------===//
611 // Constant Folding public APIs
612 //===----------------------------------------------------------------------===//
615 /// ConstantFoldInstruction - Attempt to constant fold the specified
616 /// instruction. If successful, the constant result is returned, if not, null
617 /// is returned. Note that this function can only fail when attempting to fold
618 /// instructions like loads and stores, which have no constant expression form.
620 Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
621 const TargetData *TD) {
622 if (PHINode *PN = dyn_cast<PHINode>(I)) {
623 if (PN->getNumIncomingValues() == 0)
624 return UndefValue::get(PN->getType());
626 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
627 if (Result == 0) return 0;
629 // Handle PHI nodes specially here...
630 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
631 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
632 return 0; // Not all the same incoming constants...
634 // If we reach here, all incoming values are the same constant.
638 // Scan the operand list, checking to see if they are all constants, if so,
639 // hand off to ConstantFoldInstOperands.
640 SmallVector<Constant*, 8> Ops;
641 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
642 if (Constant *Op = dyn_cast<Constant>(*i))
645 return 0; // All operands not constant!
647 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
648 return ConstantFoldCompareInstOperands(CI->getPredicate(),
649 Ops.data(), Ops.size(),
652 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
653 return ConstantFoldLoadInst(LI, TD);
655 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
656 Ops.data(), Ops.size(), Context, TD);
659 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
660 /// using the specified TargetData. If successful, the constant result is
661 /// result is returned, if not, null is returned.
662 Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
663 LLVMContext &Context,
664 const TargetData *TD) {
665 SmallVector<Constant*, 8> Ops;
666 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
667 Ops.push_back(cast<Constant>(*i));
670 return ConstantFoldCompareInstOperands(CE->getPredicate(),
671 Ops.data(), Ops.size(),
673 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
674 Ops.data(), Ops.size(), Context, TD);
677 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
678 /// specified opcode and operands. If successful, the constant result is
679 /// returned, if not, null is returned. Note that this function can fail when
680 /// attempting to fold instructions like loads and stores, which have no
681 /// constant expression form.
683 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
684 Constant* const* Ops, unsigned NumOps,
685 LLVMContext &Context,
686 const TargetData *TD) {
687 // Handle easy binops first.
688 if (Instruction::isBinaryOp(Opcode)) {
689 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
690 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
694 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
699 case Instruction::Call:
700 if (Function *F = dyn_cast<Function>(Ops[0]))
701 if (canConstantFoldCallTo(F))
702 return ConstantFoldCall(F, Ops+1, NumOps-1);
704 case Instruction::ICmp:
705 case Instruction::FCmp:
706 llvm_unreachable("This function is invalid for compares: no predicate specified");
707 case Instruction::PtrToInt:
708 // If the input is a inttoptr, eliminate the pair. This requires knowing
709 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
710 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
711 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
712 Constant *Input = CE->getOperand(0);
713 unsigned InWidth = Input->getType()->getScalarSizeInBits();
714 if (TD->getPointerSizeInBits() < InWidth) {
716 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
717 TD->getPointerSizeInBits()));
718 Input = ConstantExpr::getAnd(Input, Mask);
720 // Do a zext or trunc to get to the dest size.
721 return ConstantExpr::getIntegerCast(Input, DestTy, false);
724 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
725 case Instruction::IntToPtr:
726 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
727 // the int size is >= the ptr size. This requires knowing the width of a
728 // pointer, so it can't be done in ConstantExpr::getCast.
729 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
731 TD->getPointerSizeInBits() <=
732 CE->getType()->getScalarSizeInBits()) {
733 if (CE->getOpcode() == Instruction::PtrToInt) {
734 Constant *Input = CE->getOperand(0);
735 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
736 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
738 // If there's a constant offset added to the integer value before
739 // it is casted back to a pointer, see if the expression can be
740 // converted into a GEP.
741 if (CE->getOpcode() == Instruction::Add)
742 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
743 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
744 if (R->getOpcode() == Instruction::PtrToInt)
745 if (GlobalVariable *GV =
746 dyn_cast<GlobalVariable>(R->getOperand(0))) {
747 const PointerType *GVTy = cast<PointerType>(GV->getType());
748 if (const ArrayType *AT =
749 dyn_cast<ArrayType>(GVTy->getElementType())) {
750 const Type *ElTy = AT->getElementType();
751 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
752 APInt PSA(L->getValue().getBitWidth(), AllocSize);
753 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
754 L->getValue().urem(PSA) == 0) {
755 APInt ElemIdx = L->getValue().udiv(PSA);
756 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
757 AT->getNumElements()))) {
758 Constant *Index[] = {
759 Constant::getNullValue(CE->getType()),
760 ConstantInt::get(Context, ElemIdx)
763 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
770 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
771 case Instruction::Trunc:
772 case Instruction::ZExt:
773 case Instruction::SExt:
774 case Instruction::FPTrunc:
775 case Instruction::FPExt:
776 case Instruction::UIToFP:
777 case Instruction::SIToFP:
778 case Instruction::FPToUI:
779 case Instruction::FPToSI:
780 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
781 case Instruction::BitCast:
783 return FoldBitCast(Ops[0], DestTy, *TD, Context);
784 return ConstantExpr::getBitCast(Ops[0], DestTy);
785 case Instruction::Select:
786 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
787 case Instruction::ExtractElement:
788 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
789 case Instruction::InsertElement:
790 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
791 case Instruction::ShuffleVector:
792 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
793 case Instruction::GetElementPtr:
794 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
797 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
801 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
802 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
803 /// returns a constant expression of the specified operands.
805 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
806 Constant*const * Ops,
808 LLVMContext &Context,
809 const TargetData *TD) {
810 // fold: icmp (inttoptr x), null -> icmp x, 0
811 // fold: icmp (ptrtoint x), 0 -> icmp x, null
812 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
813 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
815 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
816 // around to know if bit truncation is happening.
817 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
818 if (TD && Ops[1]->isNullValue()) {
819 const Type *IntPtrTy = TD->getIntPtrType(Context);
820 if (CE0->getOpcode() == Instruction::IntToPtr) {
821 // Convert the integer value to the right size to ensure we get the
822 // proper extension or truncation.
823 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
825 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
826 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
830 // Only do this transformation if the int is intptrty in size, otherwise
831 // there is a truncation or extension that we aren't modeling.
832 if (CE0->getOpcode() == Instruction::PtrToInt &&
833 CE0->getType() == IntPtrTy) {
834 Constant *C = CE0->getOperand(0);
835 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
837 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
842 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
843 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
844 const Type *IntPtrTy = TD->getIntPtrType(Context);
846 if (CE0->getOpcode() == Instruction::IntToPtr) {
847 // Convert the integer value to the right size to ensure we get the
848 // proper extension or truncation.
849 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
851 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
853 Constant *NewOps[] = { C0, C1 };
854 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
858 // Only do this transformation if the int is intptrty in size, otherwise
859 // there is a truncation or extension that we aren't modeling.
860 if ((CE0->getOpcode() == Instruction::PtrToInt &&
861 CE0->getType() == IntPtrTy &&
862 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
863 Constant *NewOps[] = {
864 CE0->getOperand(0), CE1->getOperand(0)
866 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
872 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
876 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
877 /// getelementptr constantexpr, return the constant value being addressed by the
878 /// constant expression, or null if something is funny and we can't decide.
879 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
881 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
882 return 0; // Do not allow stepping over the value!
884 // Loop over all of the operands, tracking down which value we are
886 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
887 for (++I; I != E; ++I)
888 if (const StructType *STy = dyn_cast<StructType>(*I)) {
889 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
890 assert(CU->getZExtValue() < STy->getNumElements() &&
891 "Struct index out of range!");
892 unsigned El = (unsigned)CU->getZExtValue();
893 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
894 C = CS->getOperand(El);
895 } else if (isa<ConstantAggregateZero>(C)) {
896 C = Constant::getNullValue(STy->getElementType(El));
897 } else if (isa<UndefValue>(C)) {
898 C = UndefValue::get(STy->getElementType(El));
902 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
903 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
904 if (CI->getZExtValue() >= ATy->getNumElements())
906 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
907 C = CA->getOperand(CI->getZExtValue());
908 else if (isa<ConstantAggregateZero>(C))
909 C = Constant::getNullValue(ATy->getElementType());
910 else if (isa<UndefValue>(C))
911 C = UndefValue::get(ATy->getElementType());
914 } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
915 if (CI->getZExtValue() >= VTy->getNumElements())
917 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
918 C = CP->getOperand(CI->getZExtValue());
919 else if (isa<ConstantAggregateZero>(C))
920 C = Constant::getNullValue(VTy->getElementType());
921 else if (isa<UndefValue>(C))
922 C = UndefValue::get(VTy->getElementType());
935 //===----------------------------------------------------------------------===//
936 // Constant Folding for Calls
939 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
940 /// the specified function.
942 llvm::canConstantFoldCallTo(const Function *F) {
943 switch (F->getIntrinsicID()) {
944 case Intrinsic::sqrt:
945 case Intrinsic::powi:
946 case Intrinsic::bswap:
947 case Intrinsic::ctpop:
948 case Intrinsic::ctlz:
949 case Intrinsic::cttz:
950 case Intrinsic::uadd_with_overflow:
951 case Intrinsic::usub_with_overflow:
952 case Intrinsic::sadd_with_overflow:
953 case Intrinsic::ssub_with_overflow:
960 if (!F->hasName()) return false;
961 StringRef Name = F->getName();
963 // In these cases, the check of the length is required. We don't want to
964 // return true for a name like "cos\0blah" which strcmp would return equal to
965 // "cos", but has length 8.
967 default: return false;
969 return Name == "acos" || Name == "asin" ||
970 Name == "atan" || Name == "atan2";
972 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
974 return Name == "exp";
976 return Name == "fabs" || Name == "fmod" || Name == "floor";
978 return Name == "log" || Name == "log10";
980 return Name == "pow";
982 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
983 Name == "sinf" || Name == "sqrtf";
985 return Name == "tan" || Name == "tanh";
989 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
990 const Type *Ty, LLVMContext &Context) {
999 return ConstantFP::get(Context, APFloat((float)V));
1000 if (Ty->isDoubleTy())
1001 return ConstantFP::get(Context, APFloat(V));
1002 llvm_unreachable("Can only constant fold float/double");
1003 return 0; // dummy return to suppress warning
1006 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1009 LLVMContext &Context) {
1017 if (Ty->isFloatTy())
1018 return ConstantFP::get(Context, APFloat((float)V));
1019 if (Ty->isDoubleTy())
1020 return ConstantFP::get(Context, APFloat(V));
1021 llvm_unreachable("Can only constant fold float/double");
1022 return 0; // dummy return to suppress warning
1025 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1026 /// with the specified arguments, returning null if unsuccessful.
1028 llvm::ConstantFoldCall(Function *F,
1029 Constant *const *Operands, unsigned NumOperands) {
1030 if (!F->hasName()) return 0;
1031 LLVMContext &Context = F->getContext();
1032 StringRef Name = F->getName();
1034 const Type *Ty = F->getReturnType();
1035 if (NumOperands == 1) {
1036 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1037 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1039 /// Currently APFloat versions of these functions do not exist, so we use
1040 /// the host native double versions. Float versions are not called
1041 /// directly but for all these it is true (float)(f((double)arg)) ==
1042 /// f(arg). Long double not supported yet.
1043 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
1044 Op->getValueAPF().convertToDouble();
1048 return ConstantFoldFP(acos, V, Ty, Context);
1049 else if (Name == "asin")
1050 return ConstantFoldFP(asin, V, Ty, Context);
1051 else if (Name == "atan")
1052 return ConstantFoldFP(atan, V, Ty, Context);
1056 return ConstantFoldFP(ceil, V, Ty, Context);
1057 else if (Name == "cos")
1058 return ConstantFoldFP(cos, V, Ty, Context);
1059 else if (Name == "cosh")
1060 return ConstantFoldFP(cosh, V, Ty, Context);
1061 else if (Name == "cosf")
1062 return ConstantFoldFP(cos, V, Ty, Context);
1066 return ConstantFoldFP(exp, V, Ty, Context);
1070 return ConstantFoldFP(fabs, V, Ty, Context);
1071 else if (Name == "floor")
1072 return ConstantFoldFP(floor, V, Ty, Context);
1075 if (Name == "log" && V > 0)
1076 return ConstantFoldFP(log, V, Ty, Context);
1077 else if (Name == "log10" && V > 0)
1078 return ConstantFoldFP(log10, V, Ty, Context);
1079 else if (Name == "llvm.sqrt.f32" ||
1080 Name == "llvm.sqrt.f64") {
1082 return ConstantFoldFP(sqrt, V, Ty, Context);
1084 return Constant::getNullValue(Ty);
1089 return ConstantFoldFP(sin, V, Ty, Context);
1090 else if (Name == "sinh")
1091 return ConstantFoldFP(sinh, V, Ty, Context);
1092 else if (Name == "sqrt" && V >= 0)
1093 return ConstantFoldFP(sqrt, V, Ty, Context);
1094 else if (Name == "sqrtf" && V >= 0)
1095 return ConstantFoldFP(sqrt, V, Ty, Context);
1096 else if (Name == "sinf")
1097 return ConstantFoldFP(sin, V, Ty, Context);
1101 return ConstantFoldFP(tan, V, Ty, Context);
1102 else if (Name == "tanh")
1103 return ConstantFoldFP(tanh, V, Ty, Context);
1112 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1113 if (Name.startswith("llvm.bswap"))
1114 return ConstantInt::get(Context, Op->getValue().byteSwap());
1115 else if (Name.startswith("llvm.ctpop"))
1116 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1117 else if (Name.startswith("llvm.cttz"))
1118 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
1119 else if (Name.startswith("llvm.ctlz"))
1120 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
1127 if (NumOperands == 2) {
1128 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1129 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1131 double Op1V = Ty->isFloatTy() ?
1132 (double)Op1->getValueAPF().convertToFloat() :
1133 Op1->getValueAPF().convertToDouble();
1134 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1135 if (Op2->getType() != Op1->getType())
1138 double Op2V = Ty->isFloatTy() ?
1139 (double)Op2->getValueAPF().convertToFloat():
1140 Op2->getValueAPF().convertToDouble();
1143 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
1145 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
1146 if (Name == "atan2")
1147 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
1148 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1149 if (Name == "llvm.powi.f32")
1150 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
1151 (int)Op2C->getZExtValue())));
1152 if (Name == "llvm.powi.f64")
1153 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
1154 (int)Op2C->getZExtValue())));
1160 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1161 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1162 switch (F->getIntrinsicID()) {
1164 case Intrinsic::uadd_with_overflow: {
1165 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
1167 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
1169 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1171 case Intrinsic::usub_with_overflow: {
1172 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
1174 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
1176 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1178 case Intrinsic::sadd_with_overflow: {
1179 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
1180 Constant *Overflow = ConstantExpr::getSelect(
1181 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1182 ConstantInt::get(Op1->getType(), 0), Op1),
1183 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
1184 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
1186 Constant *Ops[] = { Res, Overflow };
1187 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1189 case Intrinsic::ssub_with_overflow: {
1190 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
1191 Constant *Overflow = ConstantExpr::getSelect(
1192 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1193 ConstantInt::get(Op2->getType(), 0), Op2),
1194 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
1195 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
1197 Constant *Ops[] = { Res, Overflow };
1198 return ConstantStruct::get(F->getContext(), Ops, 2, false);