1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements folding of constants for LLVM. This implements the
11 // (internal) ConstantFold.h interface, which is used by the
12 // ConstantExpr::get* methods to automatically fold constants when possible.
14 // The current constant folding implementation is implemented in two pieces: the
15 // template-based folder for simple primitive constants like ConstantInt, and
16 // the special case hackery that we use to symbolically evaluate expressions
17 // that use ConstantExprs.
19 //===----------------------------------------------------------------------===//
21 #include "ConstantFold.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MathExtras.h"
35 //===----------------------------------------------------------------------===//
36 // ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
39 /// CastConstantVector - Convert the specified ConstantVector node to the
40 /// specified vector type. At this point, we know that the elements of the
41 /// input vector constant are all simple integer or FP values.
42 static Constant *CastConstantVector(ConstantVector *CV,
43 const VectorType *DstTy) {
44 unsigned SrcNumElts = CV->getType()->getNumElements();
45 unsigned DstNumElts = DstTy->getNumElements();
46 const Type *SrcEltTy = CV->getType()->getElementType();
47 const Type *DstEltTy = DstTy->getElementType();
49 // If both vectors have the same number of elements (thus, the elements
50 // are the same size), perform the conversion now.
51 if (SrcNumElts == DstNumElts) {
52 std::vector<Constant*> Result;
54 // If the src and dest elements are both integers, or both floats, we can
55 // just BitCast each element because the elements are the same size.
56 if ((SrcEltTy->isInteger() && DstEltTy->isInteger()) ||
57 (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
58 for (unsigned i = 0; i != SrcNumElts; ++i)
60 ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
61 return ConstantVector::get(Result);
64 // If this is an int-to-fp cast ..
65 if (SrcEltTy->isInteger()) {
66 // Ensure that it is int-to-fp cast
67 assert(DstEltTy->isFloatingPoint());
68 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
69 for (unsigned i = 0; i != SrcNumElts; ++i) {
70 ConstantInt *CI = cast<ConstantInt>(CV->getOperand(i));
71 double V = CI->getValue().bitsToDouble();
72 Result.push_back(ConstantFP::get(Type::DoubleTy, APFloat(V)));
74 return ConstantVector::get(Result);
76 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
77 for (unsigned i = 0; i != SrcNumElts; ++i) {
78 ConstantInt *CI = cast<ConstantInt>(CV->getOperand(i));
79 float V = CI->getValue().bitsToFloat();
80 Result.push_back(ConstantFP::get(Type::FloatTy, APFloat(V)));
82 return ConstantVector::get(Result);
85 // Otherwise, this is an fp-to-int cast.
86 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isInteger());
88 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
89 for (unsigned i = 0; i != SrcNumElts; ++i) {
90 uint64_t V = cast<ConstantFP>(CV->getOperand(i))->
91 getValueAPF().convertToAPInt().getZExtValue();
92 Constant *C = ConstantInt::get(Type::Int64Ty, V);
93 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
95 return ConstantVector::get(Result);
98 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
99 for (unsigned i = 0; i != SrcNumElts; ++i) {
100 uint32_t V = (uint32_t)cast<ConstantFP>(CV->getOperand(i))->
101 getValueAPF().convertToAPInt().getZExtValue();
102 Constant *C = ConstantInt::get(Type::Int32Ty, V);
103 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
105 return ConstantVector::get(Result);
108 // Otherwise, this is a cast that changes element count and size. Handle
109 // casts which shrink the elements here.
111 // FIXME: We need to know endianness to do this!
116 /// This function determines which opcode to use to fold two constant cast
117 /// expressions together. It uses CastInst::isEliminableCastPair to determine
118 /// the opcode. Consequently its just a wrapper around that function.
119 /// @brief Determine if it is valid to fold a cast of a cast
121 foldConstantCastPair(
122 unsigned opc, ///< opcode of the second cast constant expression
123 const ConstantExpr*Op, ///< the first cast constant expression
124 const Type *DstTy ///< desintation type of the first cast
126 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
127 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
128 assert(CastInst::isCast(opc) && "Invalid cast opcode");
130 // The the types and opcodes for the two Cast constant expressions
131 const Type *SrcTy = Op->getOperand(0)->getType();
132 const Type *MidTy = Op->getType();
133 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
134 Instruction::CastOps secondOp = Instruction::CastOps(opc);
136 // Let CastInst::isEliminableCastPair do the heavy lifting.
137 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
141 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
142 const Type *SrcTy = V->getType();
144 return V; // no-op cast
146 // Check to see if we are casting a pointer to an aggregate to a pointer to
147 // the first element. If so, return the appropriate GEP instruction.
148 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
149 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
150 SmallVector<Value*, 8> IdxList;
151 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
152 const Type *ElTy = PTy->getElementType();
153 while (ElTy != DPTy->getElementType()) {
154 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
155 if (STy->getNumElements() == 0) break;
156 ElTy = STy->getElementType(0);
157 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
158 } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
159 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
160 ElTy = STy->getElementType();
161 IdxList.push_back(IdxList[0]);
167 if (ElTy == DPTy->getElementType())
168 return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
171 // Handle casts from one vector constant to another. We know that the src
172 // and dest type have the same size (otherwise its an illegal cast).
173 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
174 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
175 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
176 "Not cast between same sized vectors!");
177 // First, check for null. Undef is already handled.
178 if (isa<ConstantAggregateZero>(V))
179 return Constant::getNullValue(DestTy);
181 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
182 // This is a cast from a ConstantVector of one type to a
183 // ConstantVector of another type. Check to see if all elements of
184 // the input are simple.
185 bool AllSimpleConstants = true;
186 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
187 if (!isa<ConstantInt>(CV->getOperand(i)) &&
188 !isa<ConstantFP>(CV->getOperand(i))) {
189 AllSimpleConstants = false;
194 // If all of the elements are simple constants, we can fold this.
195 if (AllSimpleConstants)
196 return CastConstantVector(const_cast<ConstantVector*>(CV), DestPTy);
201 // Finally, implement bitcast folding now. The code below doesn't handle
203 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
204 return ConstantPointerNull::get(cast<PointerType>(DestTy));
206 // Handle integral constant input.
207 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
208 if (DestTy->isInteger())
209 // Integral -> Integral. This is a no-op because the bit widths must
210 // be the same. Consequently, we just fold to V.
213 if (DestTy->isFloatingPoint()) {
214 assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) &&
216 return ConstantFP::get(DestTy, APFloat(CI->getValue()));
218 // Otherwise, can't fold this (vector?)
222 // Handle ConstantFP input.
223 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
225 if (DestTy == Type::Int32Ty) {
226 return ConstantInt::get(FP->getValueAPF().convertToAPInt());
228 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
229 return ConstantInt::get(FP->getValueAPF().convertToAPInt());
236 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
237 const Type *DestTy) {
238 const Type *SrcTy = V->getType();
240 if (isa<UndefValue>(V)) {
241 // zext(undef) = 0, because the top bits will be zero.
242 // sext(undef) = 0, because the top bits will all be the same.
243 if (opc == Instruction::ZExt || opc == Instruction::SExt)
244 return Constant::getNullValue(DestTy);
245 return UndefValue::get(DestTy);
247 // No compile-time operations on this type yet.
248 if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
251 // If the cast operand is a constant expression, there's a few things we can
252 // do to try to simplify it.
253 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
255 // Try hard to fold cast of cast because they are often eliminable.
256 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
257 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
258 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
259 // If all of the indexes in the GEP are null values, there is no pointer
260 // adjustment going on. We might as well cast the source pointer.
261 bool isAllNull = true;
262 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
263 if (!CE->getOperand(i)->isNullValue()) {
268 // This is casting one pointer type to another, always BitCast
269 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
273 // We actually have to do a cast now. Perform the cast according to the
276 case Instruction::FPTrunc:
277 case Instruction::FPExt:
278 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
279 APFloat Val = FPC->getValueAPF();
280 Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
281 DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
282 DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
283 DestTy == Type::FP128Ty ? APFloat::IEEEquad :
285 APFloat::rmNearestTiesToEven);
286 return ConstantFP::get(DestTy, Val);
288 return 0; // Can't fold.
289 case Instruction::FPToUI:
290 case Instruction::FPToSI:
291 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
292 const APFloat &V = FPC->getValueAPF();
294 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
295 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
296 APFloat::rmTowardZero);
297 APInt Val(DestBitWidth, 2, x);
298 return ConstantInt::get(Val);
300 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
301 std::vector<Constant*> res;
302 const VectorType *DestVecTy = cast<VectorType>(DestTy);
303 const Type *DstEltTy = DestVecTy->getElementType();
304 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
305 res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
307 return ConstantVector::get(DestVecTy, res);
309 return 0; // Can't fold.
310 case Instruction::IntToPtr: //always treated as unsigned
311 if (V->isNullValue()) // Is it an integral null value?
312 return ConstantPointerNull::get(cast<PointerType>(DestTy));
313 return 0; // Other pointer types cannot be casted
314 case Instruction::PtrToInt: // always treated as unsigned
315 if (V->isNullValue()) // is it a null pointer value?
316 return ConstantInt::get(DestTy, 0);
317 return 0; // Other pointer types cannot be casted
318 case Instruction::UIToFP:
319 case Instruction::SIToFP:
320 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
321 APInt api = CI->getValue();
322 const uint64_t zero[] = {0, 0};
323 uint32_t BitWidth = cast<IntegerType>(SrcTy)->getBitWidth();
324 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
326 (void)apf.convertFromZeroExtendedInteger(api.getRawData(), BitWidth,
327 opc==Instruction::SIToFP,
328 APFloat::rmNearestTiesToEven);
329 return ConstantFP::get(DestTy, apf);
331 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
332 std::vector<Constant*> res;
333 const VectorType *DestVecTy = cast<VectorType>(DestTy);
334 const Type *DstEltTy = DestVecTy->getElementType();
335 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
336 res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
338 return ConstantVector::get(DestVecTy, res);
341 case Instruction::ZExt:
342 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
343 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
344 APInt Result(CI->getValue());
345 Result.zext(BitWidth);
346 return ConstantInt::get(Result);
349 case Instruction::SExt:
350 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
351 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
352 APInt Result(CI->getValue());
353 Result.sext(BitWidth);
354 return ConstantInt::get(Result);
357 case Instruction::Trunc:
358 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
359 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
360 APInt Result(CI->getValue());
361 Result.trunc(BitWidth);
362 return ConstantInt::get(Result);
365 case Instruction::BitCast:
366 return FoldBitCast(const_cast<Constant*>(V), DestTy);
368 assert(!"Invalid CE CastInst opcode");
372 assert(0 && "Failed to cast constant expression");
376 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
378 const Constant *V2) {
379 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
380 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
382 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
383 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
384 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
385 if (V1 == V2) return const_cast<Constant*>(V1);
389 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
390 const Constant *Idx) {
391 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
392 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
393 if (Val->isNullValue()) // ee(zero, x) -> zero
394 return Constant::getNullValue(
395 cast<VectorType>(Val->getType())->getElementType());
397 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
398 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
399 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
400 } else if (isa<UndefValue>(Idx)) {
401 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
402 return const_cast<Constant*>(CVal->getOperand(0));
408 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
410 const Constant *Idx) {
411 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
413 APInt idxVal = CIdx->getValue();
414 if (isa<UndefValue>(Val)) {
415 // Insertion of scalar constant into vector undef
416 // Optimize away insertion of undef
417 if (isa<UndefValue>(Elt))
418 return const_cast<Constant*>(Val);
419 // Otherwise break the aggregate undef into multiple undefs and do
422 cast<VectorType>(Val->getType())->getNumElements();
423 std::vector<Constant*> Ops;
425 for (unsigned i = 0; i < numOps; ++i) {
427 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
428 Ops.push_back(const_cast<Constant*>(Op));
430 return ConstantVector::get(Ops);
432 if (isa<ConstantAggregateZero>(Val)) {
433 // Insertion of scalar constant into vector aggregate zero
434 // Optimize away insertion of zero
435 if (Elt->isNullValue())
436 return const_cast<Constant*>(Val);
437 // Otherwise break the aggregate zero into multiple zeros and do
440 cast<VectorType>(Val->getType())->getNumElements();
441 std::vector<Constant*> Ops;
443 for (unsigned i = 0; i < numOps; ++i) {
445 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
446 Ops.push_back(const_cast<Constant*>(Op));
448 return ConstantVector::get(Ops);
450 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
451 // Insertion of scalar constant into vector constant
452 std::vector<Constant*> Ops;
453 Ops.reserve(CVal->getNumOperands());
454 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
456 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
457 Ops.push_back(const_cast<Constant*>(Op));
459 return ConstantVector::get(Ops);
464 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
466 const Constant *Mask) {
471 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
472 /// function pointer to each element pair, producing a new ConstantVector
473 /// constant. Either or both of V1 and V2 may be NULL, meaning a
474 /// ConstantAggregateZero operand.
475 static Constant *EvalVectorOp(const ConstantVector *V1,
476 const ConstantVector *V2,
477 const VectorType *VTy,
478 Constant *(*FP)(Constant*, Constant*)) {
479 std::vector<Constant*> Res;
480 const Type *EltTy = VTy->getElementType();
481 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
482 const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
483 const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
484 Res.push_back(FP(const_cast<Constant*>(C1),
485 const_cast<Constant*>(C2)));
487 return ConstantVector::get(Res);
490 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
492 const Constant *C2) {
493 // No compile-time operations on this type yet.
494 if (C1->getType() == Type::PPC_FP128Ty)
497 // Handle UndefValue up front
498 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
500 case Instruction::Add:
501 case Instruction::Sub:
502 case Instruction::Xor:
503 return UndefValue::get(C1->getType());
504 case Instruction::Mul:
505 case Instruction::And:
506 return Constant::getNullValue(C1->getType());
507 case Instruction::UDiv:
508 case Instruction::SDiv:
509 case Instruction::FDiv:
510 case Instruction::URem:
511 case Instruction::SRem:
512 case Instruction::FRem:
513 if (!isa<UndefValue>(C2)) // undef / X -> 0
514 return Constant::getNullValue(C1->getType());
515 return const_cast<Constant*>(C2); // X / undef -> undef
516 case Instruction::Or: // X | undef -> -1
517 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
518 return ConstantVector::getAllOnesValue(PTy);
519 return ConstantInt::getAllOnesValue(C1->getType());
520 case Instruction::LShr:
521 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
522 return const_cast<Constant*>(C1); // undef lshr undef -> undef
523 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
525 case Instruction::AShr:
526 if (!isa<UndefValue>(C2))
527 return const_cast<Constant*>(C1); // undef ashr X --> undef
528 else if (isa<UndefValue>(C1))
529 return const_cast<Constant*>(C1); // undef ashr undef -> undef
531 return const_cast<Constant*>(C1); // X ashr undef --> X
532 case Instruction::Shl:
533 // undef << X -> 0 or X << undef -> 0
534 return Constant::getNullValue(C1->getType());
538 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
539 if (isa<ConstantExpr>(C2)) {
540 // There are many possible foldings we could do here. We should probably
541 // at least fold add of a pointer with an integer into the appropriate
542 // getelementptr. This will improve alias analysis a bit.
544 // Just implement a couple of simple identities.
546 case Instruction::Add:
547 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
549 case Instruction::Sub:
550 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
552 case Instruction::Mul:
553 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
554 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
555 if (CI->equalsInt(1))
556 return const_cast<Constant*>(C1); // X * 1 == X
558 case Instruction::UDiv:
559 case Instruction::SDiv:
560 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
561 if (CI->equalsInt(1))
562 return const_cast<Constant*>(C1); // X / 1 == X
564 case Instruction::URem:
565 case Instruction::SRem:
566 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
567 if (CI->equalsInt(1))
568 return Constant::getNullValue(CI->getType()); // X % 1 == 0
570 case Instruction::And:
571 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2)) {
572 if (CI->isZero()) return const_cast<Constant*>(C2); // X & 0 == 0
573 if (CI->isAllOnesValue())
574 return const_cast<Constant*>(C1); // X & -1 == X
576 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
577 if (CE1->getOpcode() == Instruction::ZExt) {
578 APInt PossiblySetBits
579 = cast<IntegerType>(CE1->getOperand(0)->getType())->getMask();
580 PossiblySetBits.zext(C1->getType()->getPrimitiveSizeInBits());
581 if ((PossiblySetBits & CI->getValue()) == PossiblySetBits)
582 return const_cast<Constant*>(C1);
585 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
586 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
588 // Functions are at least 4-byte aligned. If and'ing the address of a
589 // function with a constant < 4, fold it to zero.
590 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
591 if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
593 return Constant::getNullValue(CI->getType());
596 case Instruction::Or:
597 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
598 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
599 if (CI->isAllOnesValue())
600 return const_cast<Constant*>(C2); // X | -1 == -1
602 case Instruction::Xor:
603 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
605 case Instruction::AShr:
606 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
607 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
608 return ConstantExpr::getLShr(const_cast<Constant*>(C1),
609 const_cast<Constant*>(C2));
613 } else if (isa<ConstantExpr>(C2)) {
614 // If C2 is a constant expr and C1 isn't, flop them around and fold the
615 // other way if possible.
617 case Instruction::Add:
618 case Instruction::Mul:
619 case Instruction::And:
620 case Instruction::Or:
621 case Instruction::Xor:
622 // No change of opcode required.
623 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
625 case Instruction::Shl:
626 case Instruction::LShr:
627 case Instruction::AShr:
628 case Instruction::Sub:
629 case Instruction::SDiv:
630 case Instruction::UDiv:
631 case Instruction::FDiv:
632 case Instruction::URem:
633 case Instruction::SRem:
634 case Instruction::FRem:
635 default: // These instructions cannot be flopped around.
640 // At this point we know neither constant is an UndefValue nor a ConstantExpr
641 // so look at directly computing the value.
642 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
643 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
644 using namespace APIntOps;
645 APInt C1V = CI1->getValue();
646 APInt C2V = CI2->getValue();
650 case Instruction::Add:
651 return ConstantInt::get(C1V + C2V);
652 case Instruction::Sub:
653 return ConstantInt::get(C1V - C2V);
654 case Instruction::Mul:
655 return ConstantInt::get(C1V * C2V);
656 case Instruction::UDiv:
657 if (CI2->isNullValue())
658 return 0; // X / 0 -> can't fold
659 return ConstantInt::get(C1V.udiv(C2V));
660 case Instruction::SDiv:
661 if (CI2->isNullValue())
662 return 0; // X / 0 -> can't fold
663 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
664 return 0; // MIN_INT / -1 -> overflow
665 return ConstantInt::get(C1V.sdiv(C2V));
666 case Instruction::URem:
667 if (C2->isNullValue())
668 return 0; // X / 0 -> can't fold
669 return ConstantInt::get(C1V.urem(C2V));
670 case Instruction::SRem:
671 if (CI2->isNullValue())
672 return 0; // X % 0 -> can't fold
673 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
674 return 0; // MIN_INT % -1 -> overflow
675 return ConstantInt::get(C1V.srem(C2V));
676 case Instruction::And:
677 return ConstantInt::get(C1V & C2V);
678 case Instruction::Or:
679 return ConstantInt::get(C1V | C2V);
680 case Instruction::Xor:
681 return ConstantInt::get(C1V ^ C2V);
682 case Instruction::Shl:
683 if (uint32_t shiftAmt = C2V.getZExtValue())
684 if (shiftAmt < C1V.getBitWidth())
685 return ConstantInt::get(C1V.shl(shiftAmt));
687 return UndefValue::get(C1->getType()); // too big shift is undef
688 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
689 case Instruction::LShr:
690 if (uint32_t shiftAmt = C2V.getZExtValue())
691 if (shiftAmt < C1V.getBitWidth())
692 return ConstantInt::get(C1V.lshr(shiftAmt));
694 return UndefValue::get(C1->getType()); // too big shift is undef
695 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
696 case Instruction::AShr:
697 if (uint32_t shiftAmt = C2V.getZExtValue())
698 if (shiftAmt < C1V.getBitWidth())
699 return ConstantInt::get(C1V.ashr(shiftAmt));
701 return UndefValue::get(C1->getType()); // too big shift is undef
702 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
705 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
706 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
707 APFloat C1V = CFP1->getValueAPF();
708 APFloat C2V = CFP2->getValueAPF();
709 APFloat C3V = C1V; // copy for modification
710 bool isDouble = CFP1->getType()==Type::DoubleTy;
714 case Instruction::Add:
715 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
716 return ConstantFP::get(CFP1->getType(), C3V);
717 case Instruction::Sub:
718 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
719 return ConstantFP::get(CFP1->getType(), C3V);
720 case Instruction::Mul:
721 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
722 return ConstantFP::get(CFP1->getType(), C3V);
723 case Instruction::FDiv:
724 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
725 return ConstantFP::get(CFP1->getType(), C3V);
726 case Instruction::FRem:
728 // IEEE 754, Section 7.1, #5
729 return ConstantFP::get(CFP1->getType(), isDouble ?
730 APFloat(std::numeric_limits<double>::quiet_NaN()) :
731 APFloat(std::numeric_limits<float>::quiet_NaN()));
732 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
733 return ConstantFP::get(CFP1->getType(), C3V);
736 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
737 const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
738 const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
739 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
740 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
744 case Instruction::Add:
745 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
746 case Instruction::Sub:
747 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
748 case Instruction::Mul:
749 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
750 case Instruction::UDiv:
751 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
752 case Instruction::SDiv:
753 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
754 case Instruction::FDiv:
755 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
756 case Instruction::URem:
757 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
758 case Instruction::SRem:
759 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
760 case Instruction::FRem:
761 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
762 case Instruction::And:
763 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
764 case Instruction::Or:
765 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
766 case Instruction::Xor:
767 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
772 // We don't know how to fold this
776 /// isZeroSizedType - This type is zero sized if its an array or structure of
777 /// zero sized types. The only leaf zero sized type is an empty structure.
778 static bool isMaybeZeroSizedType(const Type *Ty) {
779 if (isa<OpaqueType>(Ty)) return true; // Can't say.
780 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
782 // If all of elements have zero size, this does too.
783 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
784 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
787 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
788 return isMaybeZeroSizedType(ATy->getElementType());
793 /// IdxCompare - Compare the two constants as though they were getelementptr
794 /// indices. This allows coersion of the types to be the same thing.
796 /// If the two constants are the "same" (after coersion), return 0. If the
797 /// first is less than the second, return -1, if the second is less than the
798 /// first, return 1. If the constants are not integral, return -2.
800 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
801 if (C1 == C2) return 0;
803 // Ok, we found a different index. If they are not ConstantInt, we can't do
804 // anything with them.
805 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
806 return -2; // don't know!
808 // Ok, we have two differing integer indices. Sign extend them to be the same
809 // type. Long is always big enough, so we use it.
810 if (C1->getType() != Type::Int64Ty)
811 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
813 if (C2->getType() != Type::Int64Ty)
814 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
816 if (C1 == C2) return 0; // They are equal
818 // If the type being indexed over is really just a zero sized type, there is
819 // no pointer difference being made here.
820 if (isMaybeZeroSizedType(ElTy))
823 // If they are really different, now that they are the same type, then we
824 // found a difference!
825 if (cast<ConstantInt>(C1)->getSExtValue() <
826 cast<ConstantInt>(C2)->getSExtValue())
832 /// evaluateFCmpRelation - This function determines if there is anything we can
833 /// decide about the two constants provided. This doesn't need to handle simple
834 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
835 /// If we can determine that the two constants have a particular relation to
836 /// each other, we should return the corresponding FCmpInst predicate,
837 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
838 /// ConstantFoldCompareInstruction.
840 /// To simplify this code we canonicalize the relation so that the first
841 /// operand is always the most "complex" of the two. We consider ConstantFP
842 /// to be the simplest, and ConstantExprs to be the most complex.
843 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
844 const Constant *V2) {
845 assert(V1->getType() == V2->getType() &&
846 "Cannot compare values of different types!");
848 // No compile-time operations on this type yet.
849 if (V1->getType() == Type::PPC_FP128Ty)
850 return FCmpInst::BAD_FCMP_PREDICATE;
852 // Handle degenerate case quickly
853 if (V1 == V2) return FCmpInst::FCMP_OEQ;
855 if (!isa<ConstantExpr>(V1)) {
856 if (!isa<ConstantExpr>(V2)) {
857 // We distilled thisUse the standard constant folder for a few cases
859 Constant *C1 = const_cast<Constant*>(V1);
860 Constant *C2 = const_cast<Constant*>(V2);
861 R = dyn_cast<ConstantInt>(
862 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
863 if (R && !R->isZero())
864 return FCmpInst::FCMP_OEQ;
865 R = dyn_cast<ConstantInt>(
866 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
867 if (R && !R->isZero())
868 return FCmpInst::FCMP_OLT;
869 R = dyn_cast<ConstantInt>(
870 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
871 if (R && !R->isZero())
872 return FCmpInst::FCMP_OGT;
874 // Nothing more we can do
875 return FCmpInst::BAD_FCMP_PREDICATE;
878 // If the first operand is simple and second is ConstantExpr, swap operands.
879 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
880 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
881 return FCmpInst::getSwappedPredicate(SwappedRelation);
883 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
884 // constantexpr or a simple constant.
885 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
886 switch (CE1->getOpcode()) {
887 case Instruction::FPTrunc:
888 case Instruction::FPExt:
889 case Instruction::UIToFP:
890 case Instruction::SIToFP:
891 // We might be able to do something with these but we don't right now.
897 // There are MANY other foldings that we could perform here. They will
898 // probably be added on demand, as they seem needed.
899 return FCmpInst::BAD_FCMP_PREDICATE;
902 /// evaluateICmpRelation - This function determines if there is anything we can
903 /// decide about the two constants provided. This doesn't need to handle simple
904 /// things like integer comparisons, but should instead handle ConstantExprs
905 /// and GlobalValues. If we can determine that the two constants have a
906 /// particular relation to each other, we should return the corresponding ICmp
907 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
909 /// To simplify this code we canonicalize the relation so that the first
910 /// operand is always the most "complex" of the two. We consider simple
911 /// constants (like ConstantInt) to be the simplest, followed by
912 /// GlobalValues, followed by ConstantExpr's (the most complex).
914 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
917 assert(V1->getType() == V2->getType() &&
918 "Cannot compare different types of values!");
919 if (V1 == V2) return ICmpInst::ICMP_EQ;
921 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
922 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
923 // We distilled this down to a simple case, use the standard constant
926 Constant *C1 = const_cast<Constant*>(V1);
927 Constant *C2 = const_cast<Constant*>(V2);
928 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
929 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
930 if (R && !R->isZero())
932 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
933 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
934 if (R && !R->isZero())
936 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
937 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
938 if (R && !R->isZero())
941 // If we couldn't figure it out, bail.
942 return ICmpInst::BAD_ICMP_PREDICATE;
945 // If the first operand is simple, swap operands.
946 ICmpInst::Predicate SwappedRelation =
947 evaluateICmpRelation(V2, V1, isSigned);
948 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
949 return ICmpInst::getSwappedPredicate(SwappedRelation);
951 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
952 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
953 ICmpInst::Predicate SwappedRelation =
954 evaluateICmpRelation(V2, V1, isSigned);
955 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
956 return ICmpInst::getSwappedPredicate(SwappedRelation);
958 return ICmpInst::BAD_ICMP_PREDICATE;
961 // Now we know that the RHS is a GlobalValue or simple constant,
962 // which (since the types must match) means that it's a ConstantPointerNull.
963 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
964 // Don't try to decide equality of aliases.
965 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
966 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
967 return ICmpInst::ICMP_NE;
969 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
970 // GlobalVals can never be null. Don't try to evaluate aliases.
971 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
972 return ICmpInst::ICMP_NE;
975 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
976 // constantexpr, a CPR, or a simple constant.
977 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
978 const Constant *CE1Op0 = CE1->getOperand(0);
980 switch (CE1->getOpcode()) {
981 case Instruction::Trunc:
982 case Instruction::FPTrunc:
983 case Instruction::FPExt:
984 case Instruction::FPToUI:
985 case Instruction::FPToSI:
986 break; // We can't evaluate floating point casts or truncations.
988 case Instruction::UIToFP:
989 case Instruction::SIToFP:
990 case Instruction::BitCast:
991 case Instruction::ZExt:
992 case Instruction::SExt:
993 // If the cast is not actually changing bits, and the second operand is a
994 // null pointer, do the comparison with the pre-casted value.
995 if (V2->isNullValue() &&
996 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
997 bool sgnd = isSigned;
998 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
999 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1000 return evaluateICmpRelation(CE1Op0,
1001 Constant::getNullValue(CE1Op0->getType()),
1005 // If the dest type is a pointer type, and the RHS is a constantexpr cast
1006 // from the same type as the src of the LHS, evaluate the inputs. This is
1007 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
1008 // which happens a lot in compilers with tagged integers.
1009 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1010 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
1011 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1012 CE1->getOperand(0)->getType()->isInteger()) {
1013 bool sgnd = isSigned;
1014 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1015 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1016 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1021 case Instruction::GetElementPtr:
1022 // Ok, since this is a getelementptr, we know that the constant has a
1023 // pointer type. Check the various cases.
1024 if (isa<ConstantPointerNull>(V2)) {
1025 // If we are comparing a GEP to a null pointer, check to see if the base
1026 // of the GEP equals the null pointer.
1027 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1028 if (GV->hasExternalWeakLinkage())
1029 // Weak linkage GVals could be zero or not. We're comparing that
1030 // to null pointer so its greater-or-equal
1031 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1033 // If its not weak linkage, the GVal must have a non-zero address
1034 // so the result is greater-than
1035 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1036 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1037 // If we are indexing from a null pointer, check to see if we have any
1038 // non-zero indices.
1039 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1040 if (!CE1->getOperand(i)->isNullValue())
1041 // Offsetting from null, must not be equal.
1042 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1043 // Only zero indexes from null, must still be zero.
1044 return ICmpInst::ICMP_EQ;
1046 // Otherwise, we can't really say if the first operand is null or not.
1047 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1048 if (isa<ConstantPointerNull>(CE1Op0)) {
1049 if (CPR2->hasExternalWeakLinkage())
1050 // Weak linkage GVals could be zero or not. We're comparing it to
1051 // a null pointer, so its less-or-equal
1052 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1054 // If its not weak linkage, the GVal must have a non-zero address
1055 // so the result is less-than
1056 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1057 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1059 // If this is a getelementptr of the same global, then it must be
1060 // different. Because the types must match, the getelementptr could
1061 // only have at most one index, and because we fold getelementptr's
1062 // with a single zero index, it must be nonzero.
1063 assert(CE1->getNumOperands() == 2 &&
1064 !CE1->getOperand(1)->isNullValue() &&
1065 "Suprising getelementptr!");
1066 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1068 // If they are different globals, we don't know what the value is,
1069 // but they can't be equal.
1070 return ICmpInst::ICMP_NE;
1074 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1075 const Constant *CE2Op0 = CE2->getOperand(0);
1077 // There are MANY other foldings that we could perform here. They will
1078 // probably be added on demand, as they seem needed.
1079 switch (CE2->getOpcode()) {
1081 case Instruction::GetElementPtr:
1082 // By far the most common case to handle is when the base pointers are
1083 // obviously to the same or different globals.
1084 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1085 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1086 return ICmpInst::ICMP_NE;
1087 // Ok, we know that both getelementptr instructions are based on the
1088 // same global. From this, we can precisely determine the relative
1089 // ordering of the resultant pointers.
1092 // Compare all of the operands the GEP's have in common.
1093 gep_type_iterator GTI = gep_type_begin(CE1);
1094 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1096 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1097 GTI.getIndexedType())) {
1098 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1099 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1100 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1103 // Ok, we ran out of things they have in common. If any leftovers
1104 // are non-zero then we have a difference, otherwise we are equal.
1105 for (; i < CE1->getNumOperands(); ++i)
1106 if (!CE1->getOperand(i)->isNullValue())
1107 if (isa<ConstantInt>(CE1->getOperand(i)))
1108 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1110 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1112 for (; i < CE2->getNumOperands(); ++i)
1113 if (!CE2->getOperand(i)->isNullValue())
1114 if (isa<ConstantInt>(CE2->getOperand(i)))
1115 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1117 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1118 return ICmpInst::ICMP_EQ;
1127 return ICmpInst::BAD_ICMP_PREDICATE;
1130 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1132 const Constant *C2) {
1134 // Handle some degenerate cases first
1135 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1136 return UndefValue::get(Type::Int1Ty);
1138 // No compile-time operations on this type yet.
1139 if (C1->getType() == Type::PPC_FP128Ty)
1142 // icmp eq/ne(null,GV) -> false/true
1143 if (C1->isNullValue()) {
1144 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1145 // Don't try to evaluate aliases. External weak GV can be null.
1146 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage())
1147 if (pred == ICmpInst::ICMP_EQ)
1148 return ConstantInt::getFalse();
1149 else if (pred == ICmpInst::ICMP_NE)
1150 return ConstantInt::getTrue();
1151 // icmp eq/ne(GV,null) -> false/true
1152 } else if (C2->isNullValue()) {
1153 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1154 // Don't try to evaluate aliases. External weak GV can be null.
1155 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage())
1156 if (pred == ICmpInst::ICMP_EQ)
1157 return ConstantInt::getFalse();
1158 else if (pred == ICmpInst::ICMP_NE)
1159 return ConstantInt::getTrue();
1162 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1163 APInt V1 = cast<ConstantInt>(C1)->getValue();
1164 APInt V2 = cast<ConstantInt>(C2)->getValue();
1166 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1167 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1168 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1169 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1170 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1171 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1172 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1173 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1174 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1175 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1176 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1178 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1179 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1180 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1181 APFloat::cmpResult R = C1V.compare(C2V);
1183 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1184 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1185 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1186 case FCmpInst::FCMP_UNO:
1187 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1188 case FCmpInst::FCMP_ORD:
1189 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1190 case FCmpInst::FCMP_UEQ:
1191 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1192 R==APFloat::cmpEqual);
1193 case FCmpInst::FCMP_OEQ:
1194 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1195 case FCmpInst::FCMP_UNE:
1196 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1197 case FCmpInst::FCMP_ONE:
1198 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1199 R==APFloat::cmpGreaterThan);
1200 case FCmpInst::FCMP_ULT:
1201 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1202 R==APFloat::cmpLessThan);
1203 case FCmpInst::FCMP_OLT:
1204 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1205 case FCmpInst::FCMP_UGT:
1206 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1207 R==APFloat::cmpGreaterThan);
1208 case FCmpInst::FCMP_OGT:
1209 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1210 case FCmpInst::FCMP_ULE:
1211 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1212 case FCmpInst::FCMP_OLE:
1213 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1214 R==APFloat::cmpEqual);
1215 case FCmpInst::FCMP_UGE:
1216 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1217 case FCmpInst::FCMP_OGE:
1218 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1219 R==APFloat::cmpEqual);
1221 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1222 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1223 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1224 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1225 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1226 const_cast<Constant*>(CP1->getOperand(i)),
1227 const_cast<Constant*>(CP2->getOperand(i)));
1228 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1231 // Otherwise, could not decide from any element pairs.
1233 } else if (pred == ICmpInst::ICMP_EQ) {
1234 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1235 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1236 const_cast<Constant*>(CP1->getOperand(i)),
1237 const_cast<Constant*>(CP2->getOperand(i)));
1238 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1241 // Otherwise, could not decide from any element pairs.
1247 if (C1->getType()->isFloatingPoint()) {
1248 switch (evaluateFCmpRelation(C1, C2)) {
1249 default: assert(0 && "Unknown relation!");
1250 case FCmpInst::FCMP_UNO:
1251 case FCmpInst::FCMP_ORD:
1252 case FCmpInst::FCMP_UEQ:
1253 case FCmpInst::FCMP_UNE:
1254 case FCmpInst::FCMP_ULT:
1255 case FCmpInst::FCMP_UGT:
1256 case FCmpInst::FCMP_ULE:
1257 case FCmpInst::FCMP_UGE:
1258 case FCmpInst::FCMP_TRUE:
1259 case FCmpInst::FCMP_FALSE:
1260 case FCmpInst::BAD_FCMP_PREDICATE:
1261 break; // Couldn't determine anything about these constants.
1262 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1263 return ConstantInt::get(Type::Int1Ty,
1264 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1265 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1266 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1267 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1268 return ConstantInt::get(Type::Int1Ty,
1269 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1270 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1271 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1272 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1273 return ConstantInt::get(Type::Int1Ty,
1274 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1275 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1276 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1277 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1278 // We can only partially decide this relation.
1279 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1280 return ConstantInt::getFalse();
1281 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1282 return ConstantInt::getTrue();
1284 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1285 // We can only partially decide this relation.
1286 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1287 return ConstantInt::getFalse();
1288 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1289 return ConstantInt::getTrue();
1291 case ICmpInst::ICMP_NE: // We know that C1 != C2
1292 // We can only partially decide this relation.
1293 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1294 return ConstantInt::getFalse();
1295 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1296 return ConstantInt::getTrue();
1300 // Evaluate the relation between the two constants, per the predicate.
1301 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1302 default: assert(0 && "Unknown relational!");
1303 case ICmpInst::BAD_ICMP_PREDICATE:
1304 break; // Couldn't determine anything about these constants.
1305 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1306 // If we know the constants are equal, we can decide the result of this
1307 // computation precisely.
1308 return ConstantInt::get(Type::Int1Ty,
1309 pred == ICmpInst::ICMP_EQ ||
1310 pred == ICmpInst::ICMP_ULE ||
1311 pred == ICmpInst::ICMP_SLE ||
1312 pred == ICmpInst::ICMP_UGE ||
1313 pred == ICmpInst::ICMP_SGE);
1314 case ICmpInst::ICMP_ULT:
1315 // If we know that C1 < C2, we can decide the result of this computation
1317 return ConstantInt::get(Type::Int1Ty,
1318 pred == ICmpInst::ICMP_ULT ||
1319 pred == ICmpInst::ICMP_NE ||
1320 pred == ICmpInst::ICMP_ULE);
1321 case ICmpInst::ICMP_SLT:
1322 // If we know that C1 < C2, we can decide the result of this computation
1324 return ConstantInt::get(Type::Int1Ty,
1325 pred == ICmpInst::ICMP_SLT ||
1326 pred == ICmpInst::ICMP_NE ||
1327 pred == ICmpInst::ICMP_SLE);
1328 case ICmpInst::ICMP_UGT:
1329 // If we know that C1 > C2, we can decide the result of this computation
1331 return ConstantInt::get(Type::Int1Ty,
1332 pred == ICmpInst::ICMP_UGT ||
1333 pred == ICmpInst::ICMP_NE ||
1334 pred == ICmpInst::ICMP_UGE);
1335 case ICmpInst::ICMP_SGT:
1336 // If we know that C1 > C2, we can decide the result of this computation
1338 return ConstantInt::get(Type::Int1Ty,
1339 pred == ICmpInst::ICMP_SGT ||
1340 pred == ICmpInst::ICMP_NE ||
1341 pred == ICmpInst::ICMP_SGE);
1342 case ICmpInst::ICMP_ULE:
1343 // If we know that C1 <= C2, we can only partially decide this relation.
1344 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1345 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1347 case ICmpInst::ICMP_SLE:
1348 // If we know that C1 <= C2, we can only partially decide this relation.
1349 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1350 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1353 case ICmpInst::ICMP_UGE:
1354 // If we know that C1 >= C2, we can only partially decide this relation.
1355 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1356 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1358 case ICmpInst::ICMP_SGE:
1359 // If we know that C1 >= C2, we can only partially decide this relation.
1360 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1361 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1364 case ICmpInst::ICMP_NE:
1365 // If we know that C1 != C2, we can only partially decide this relation.
1366 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1367 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1371 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1372 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1373 // other way if possible.
1375 case ICmpInst::ICMP_EQ:
1376 case ICmpInst::ICMP_NE:
1377 // No change of predicate required.
1378 return ConstantFoldCompareInstruction(pred, C2, C1);
1380 case ICmpInst::ICMP_ULT:
1381 case ICmpInst::ICMP_SLT:
1382 case ICmpInst::ICMP_UGT:
1383 case ICmpInst::ICMP_SGT:
1384 case ICmpInst::ICMP_ULE:
1385 case ICmpInst::ICMP_SLE:
1386 case ICmpInst::ICMP_UGE:
1387 case ICmpInst::ICMP_SGE:
1388 // Change the predicate as necessary to swap the operands.
1389 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1390 return ConstantFoldCompareInstruction(pred, C2, C1);
1392 default: // These predicates cannot be flopped around.
1400 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1401 Constant* const *Idxs,
1404 (NumIdx == 1 && Idxs[0]->isNullValue()))
1405 return const_cast<Constant*>(C);
1407 if (isa<UndefValue>(C)) {
1408 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1410 (Value **)Idxs+NumIdx,
1412 assert(Ty != 0 && "Invalid indices for GEP!");
1413 return UndefValue::get(PointerType::get(Ty));
1416 Constant *Idx0 = Idxs[0];
1417 if (C->isNullValue()) {
1419 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1420 if (!Idxs[i]->isNullValue()) {
1425 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1427 (Value**)Idxs+NumIdx,
1429 assert(Ty != 0 && "Invalid indices for GEP!");
1430 return ConstantPointerNull::get(PointerType::get(Ty));
1434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1435 // Combine Indices - If the source pointer to this getelementptr instruction
1436 // is a getelementptr instruction, combine the indices of the two
1437 // getelementptr instructions into a single instruction.
1439 if (CE->getOpcode() == Instruction::GetElementPtr) {
1440 const Type *LastTy = 0;
1441 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1445 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1446 SmallVector<Value*, 16> NewIndices;
1447 NewIndices.reserve(NumIdx + CE->getNumOperands());
1448 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1449 NewIndices.push_back(CE->getOperand(i));
1451 // Add the last index of the source with the first index of the new GEP.
1452 // Make sure to handle the case when they are actually different types.
1453 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1454 // Otherwise it must be an array.
1455 if (!Idx0->isNullValue()) {
1456 const Type *IdxTy = Combined->getType();
1457 if (IdxTy != Idx0->getType()) {
1458 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1459 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1461 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1464 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1468 NewIndices.push_back(Combined);
1469 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1470 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1475 // Implement folding of:
1476 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1478 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1480 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1481 if (const PointerType *SPT =
1482 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1483 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1484 if (const ArrayType *CAT =
1485 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1486 if (CAT->getElementType() == SAT->getElementType())
1487 return ConstantExpr::getGetElementPtr(
1488 (Constant*)CE->getOperand(0), Idxs, NumIdx);
1491 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1492 // Into: inttoptr (i64 0 to i8*)
1493 // This happens with pointers to member functions in C++.
1494 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1495 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1496 cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1497 Constant *Base = CE->getOperand(0);
1498 Constant *Offset = Idxs[0];
1500 // Convert the smaller integer to the larger type.
1501 if (Offset->getType()->getPrimitiveSizeInBits() <
1502 Base->getType()->getPrimitiveSizeInBits())
1503 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1504 else if (Base->getType()->getPrimitiveSizeInBits() <
1505 Offset->getType()->getPrimitiveSizeInBits())
1506 Base = ConstantExpr::getZExt(Base, Base->getType());
1508 Base = ConstantExpr::getAdd(Base, Offset);
1509 return ConstantExpr::getIntToPtr(Base, CE->getType());