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/ADT/SmallVector.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
34 //===----------------------------------------------------------------------===//
35 // ConstantFold*Instruction Implementations
36 //===----------------------------------------------------------------------===//
38 /// CastConstantVector - Convert the specified ConstantVector node to the
39 /// specified vector type. At this point, we know that the elements of the
40 /// input packed constant are all simple integer or FP values.
41 static Constant *CastConstantVector(ConstantVector *CV,
42 const VectorType *DstTy) {
43 unsigned SrcNumElts = CV->getType()->getNumElements();
44 unsigned DstNumElts = DstTy->getNumElements();
45 const Type *SrcEltTy = CV->getType()->getElementType();
46 const Type *DstEltTy = DstTy->getElementType();
48 // If both vectors have the same number of elements (thus, the elements
49 // are the same size), perform the conversion now.
50 if (SrcNumElts == DstNumElts) {
51 std::vector<Constant*> Result;
53 // If the src and dest elements are both integers, or both floats, we can
54 // just BitCast each element because the elements are the same size.
55 if ((SrcEltTy->isInteger() && DstEltTy->isInteger()) ||
56 (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
57 for (unsigned i = 0; i != SrcNumElts; ++i)
59 ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
60 return ConstantVector::get(Result);
63 // If this is an int-to-fp cast ..
64 if (SrcEltTy->isInteger()) {
65 // Ensure that it is int-to-fp cast
66 assert(DstEltTy->isFloatingPoint());
67 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
68 for (unsigned i = 0; i != SrcNumElts; ++i) {
69 ConstantInt *CI = cast<ConstantInt>(CV->getOperand(i));
70 double V = CI->getValue().bitsToDouble();
71 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
73 return ConstantVector::get(Result);
75 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
76 for (unsigned i = 0; i != SrcNumElts; ++i) {
77 ConstantInt *CI = cast<ConstantInt>(CV->getOperand(i));
78 float V = CI->getValue().bitsToFloat();
79 Result.push_back(ConstantFP::get(Type::FloatTy, V));
81 return ConstantVector::get(Result);
84 // Otherwise, this is an fp-to-int cast.
85 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isInteger());
87 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
88 for (unsigned i = 0; i != SrcNumElts; ++i) {
90 DoubleToBits(cast<ConstantFP>(CV->getOperand(i))->getValue());
91 Constant *C = ConstantInt::get(Type::Int64Ty, V);
92 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
94 return ConstantVector::get(Result);
97 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
98 for (unsigned i = 0; i != SrcNumElts; ++i) {
99 uint32_t V = FloatToBits(cast<ConstantFP>(CV->getOperand(i))->getValue());
100 Constant *C = ConstantInt::get(Type::Int32Ty, V);
101 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
103 return ConstantVector::get(Result);
106 // Otherwise, this is a cast that changes element count and size. Handle
107 // casts which shrink the elements here.
109 // FIXME: We need to know endianness to do this!
114 /// This function determines which opcode to use to fold two constant cast
115 /// expressions together. It uses CastInst::isEliminableCastPair to determine
116 /// the opcode. Consequently its just a wrapper around that function.
117 /// @Determine if it is valid to fold a cast of a cast
119 foldConstantCastPair(
120 unsigned opc, ///< opcode of the second cast constant expression
121 const ConstantExpr*Op, ///< the first cast constant expression
122 const Type *DstTy ///< desintation type of the first cast
124 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
125 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
126 assert(CastInst::isCast(opc) && "Invalid cast opcode");
128 // The the types and opcodes for the two Cast constant expressions
129 const Type *SrcTy = Op->getOperand(0)->getType();
130 const Type *MidTy = Op->getType();
131 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
132 Instruction::CastOps secondOp = Instruction::CastOps(opc);
134 // Let CastInst::isEliminableCastPair do the heavy lifting.
135 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
139 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
140 const Type *DestTy) {
141 const Type *SrcTy = V->getType();
143 if (isa<UndefValue>(V))
144 return UndefValue::get(DestTy);
146 // If the cast operand is a constant expression, there's a few things we can
147 // do to try to simplify it.
148 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
150 // Try hard to fold cast of cast because they are often eliminable.
151 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
152 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
153 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
154 // If all of the indexes in the GEP are null values, there is no pointer
155 // adjustment going on. We might as well cast the source pointer.
156 bool isAllNull = true;
157 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
158 if (!CE->getOperand(i)->isNullValue()) {
163 // This is casting one pointer type to another, always BitCast
164 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
168 // We actually have to do a cast now. Perform the cast according to the
171 case Instruction::FPTrunc:
172 case Instruction::FPExt:
173 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
174 return ConstantFP::get(DestTy, FPC->getValue());
175 return 0; // Can't fold.
176 case Instruction::FPToUI:
177 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
178 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
179 APInt Val(APIntOps::RoundDoubleToAPInt(FPC->getValue(), DestBitWidth));
180 return ConstantInt::get(Val);
182 return 0; // Can't fold.
183 case Instruction::FPToSI:
184 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
185 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
186 APInt Val(APIntOps::RoundDoubleToAPInt(FPC->getValue(), DestBitWidth));
187 return ConstantInt::get(Val);
189 return 0; // Can't fold.
190 case Instruction::IntToPtr: //always treated as unsigned
191 if (V->isNullValue()) // Is it an integral null value?
192 return ConstantPointerNull::get(cast<PointerType>(DestTy));
193 return 0; // Other pointer types cannot be casted
194 case Instruction::PtrToInt: // always treated as unsigned
195 if (V->isNullValue()) // is it a null pointer value?
196 return ConstantInt::get(DestTy, 0);
197 return 0; // Other pointer types cannot be casted
198 case Instruction::UIToFP:
199 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
200 return ConstantFP::get(DestTy, CI->getValue().roundToDouble());
202 case Instruction::SIToFP:
203 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
204 return ConstantFP::get(DestTy, CI->getValue().signedRoundToDouble());
206 case Instruction::ZExt:
207 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
208 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
209 APInt Result(CI->getValue());
210 Result.zext(BitWidth);
211 return ConstantInt::get(Result);
214 case Instruction::SExt:
215 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
216 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
217 APInt Result(CI->getValue());
218 Result.sext(BitWidth);
219 return ConstantInt::get(Result);
222 case Instruction::Trunc:
223 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
224 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
225 APInt Result(CI->getValue());
226 Result.trunc(BitWidth);
227 return ConstantInt::get(Result);
230 case Instruction::BitCast:
232 return (Constant*)V; // no-op cast
234 // Check to see if we are casting a pointer to an aggregate to a pointer to
235 // the first element. If so, return the appropriate GEP instruction.
236 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
237 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
238 SmallVector<Value*, 8> IdxList;
239 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
240 const Type *ElTy = PTy->getElementType();
241 while (ElTy != DPTy->getElementType()) {
242 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
243 if (STy->getNumElements() == 0) break;
244 ElTy = STy->getElementType(0);
245 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
246 } else if (const SequentialType *STy =
247 dyn_cast<SequentialType>(ElTy)) {
248 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
249 ElTy = STy->getElementType();
250 IdxList.push_back(IdxList[0]);
256 if (ElTy == DPTy->getElementType())
257 return ConstantExpr::getGetElementPtr(
258 const_cast<Constant*>(V), &IdxList[0], IdxList.size());
261 // Handle casts from one packed constant to another. We know that the src
262 // and dest type have the same size (otherwise its an illegal cast).
263 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
264 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
265 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
266 "Not cast between same sized vectors!");
267 // First, check for null and undef
268 if (isa<ConstantAggregateZero>(V))
269 return Constant::getNullValue(DestTy);
270 if (isa<UndefValue>(V))
271 return UndefValue::get(DestTy);
273 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
274 // This is a cast from a ConstantVector of one type to a
275 // ConstantVector of another type. Check to see if all elements of
276 // the input are simple.
277 bool AllSimpleConstants = true;
278 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
279 if (!isa<ConstantInt>(CV->getOperand(i)) &&
280 !isa<ConstantFP>(CV->getOperand(i))) {
281 AllSimpleConstants = false;
286 // If all of the elements are simple constants, we can fold this.
287 if (AllSimpleConstants)
288 return CastConstantVector(const_cast<ConstantVector*>(CV), DestPTy);
293 // Finally, implement bitcast folding now. The code below doesn't handle
295 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
296 return ConstantPointerNull::get(cast<PointerType>(DestTy));
298 // Handle integral constant input.
299 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
300 if (DestTy->isInteger())
301 // Integral -> Integral. This is a no-op because the bit widths must
302 // be the same. Consequently, we just fold to V.
303 return const_cast<Constant*>(V);
305 if (DestTy->isFloatingPoint()) {
306 if (DestTy == Type::FloatTy)
307 return ConstantFP::get(DestTy, CI->getValue().bitsToFloat());
308 assert(DestTy == Type::DoubleTy && "Unknown FP type!");
309 return ConstantFP::get(DestTy, CI->getValue().bitsToDouble());
311 // Otherwise, can't fold this (packed?)
315 // Handle ConstantFP input.
316 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
318 if (DestTy == Type::Int32Ty) {
320 return ConstantInt::get(Val.floatToBits(FP->getValue()));
322 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
324 return ConstantInt::get(Val.doubleToBits(FP->getValue()));
329 assert(!"Invalid CE CastInst opcode");
333 assert(0 && "Failed to cast constant expression");
337 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
339 const Constant *V2) {
340 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
341 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
343 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
344 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
345 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
346 if (V1 == V2) return const_cast<Constant*>(V1);
350 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
351 const Constant *Idx) {
352 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
353 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
354 if (Val->isNullValue()) // ee(zero, x) -> zero
355 return Constant::getNullValue(
356 cast<VectorType>(Val->getType())->getElementType());
358 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
359 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
360 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
361 } else if (isa<UndefValue>(Idx)) {
362 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
363 return const_cast<Constant*>(CVal->getOperand(0));
369 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
371 const Constant *Idx) {
372 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
374 APInt idxVal = CIdx->getValue();
375 if (isa<UndefValue>(Val)) {
376 // Insertion of scalar constant into packed undef
377 // Optimize away insertion of undef
378 if (isa<UndefValue>(Elt))
379 return const_cast<Constant*>(Val);
380 // Otherwise break the aggregate undef into multiple undefs and do
383 cast<VectorType>(Val->getType())->getNumElements();
384 std::vector<Constant*> Ops;
386 for (unsigned i = 0; i < numOps; ++i) {
388 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
389 Ops.push_back(const_cast<Constant*>(Op));
391 return ConstantVector::get(Ops);
393 if (isa<ConstantAggregateZero>(Val)) {
394 // Insertion of scalar constant into packed aggregate zero
395 // Optimize away insertion of zero
396 if (Elt->isNullValue())
397 return const_cast<Constant*>(Val);
398 // Otherwise break the aggregate zero into multiple zeros and do
401 cast<VectorType>(Val->getType())->getNumElements();
402 std::vector<Constant*> Ops;
404 for (unsigned i = 0; i < numOps; ++i) {
406 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
407 Ops.push_back(const_cast<Constant*>(Op));
409 return ConstantVector::get(Ops);
411 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
412 // Insertion of scalar constant into packed constant
413 std::vector<Constant*> Ops;
414 Ops.reserve(CVal->getNumOperands());
415 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
417 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
418 Ops.push_back(const_cast<Constant*>(Op));
420 return ConstantVector::get(Ops);
425 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
427 const Constant *Mask) {
432 /// EvalVectorOp - Given two packed constants and a function pointer, apply the
433 /// function pointer to each element pair, producing a new ConstantVector
435 static Constant *EvalVectorOp(const ConstantVector *V1,
436 const ConstantVector *V2,
437 Constant *(*FP)(Constant*, Constant*)) {
438 std::vector<Constant*> Res;
439 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
440 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
441 const_cast<Constant*>(V2->getOperand(i))));
442 return ConstantVector::get(Res);
445 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
447 const Constant *C2) {
448 // Handle UndefValue up front
449 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
451 case Instruction::Add:
452 case Instruction::Sub:
453 case Instruction::Xor:
454 return UndefValue::get(C1->getType());
455 case Instruction::Mul:
456 case Instruction::And:
457 return Constant::getNullValue(C1->getType());
458 case Instruction::UDiv:
459 case Instruction::SDiv:
460 case Instruction::FDiv:
461 case Instruction::URem:
462 case Instruction::SRem:
463 case Instruction::FRem:
464 if (!isa<UndefValue>(C2)) // undef / X -> 0
465 return Constant::getNullValue(C1->getType());
466 return const_cast<Constant*>(C2); // X / undef -> undef
467 case Instruction::Or: // X | undef -> -1
468 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
469 return ConstantVector::getAllOnesValue(PTy);
470 return ConstantInt::getAllOnesValue(C1->getType());
471 case Instruction::LShr:
472 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
473 return const_cast<Constant*>(C1); // undef lshr undef -> undef
474 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
476 case Instruction::AShr:
477 if (!isa<UndefValue>(C2))
478 return const_cast<Constant*>(C1); // undef ashr X --> undef
479 else if (isa<UndefValue>(C1))
480 return const_cast<Constant*>(C1); // undef ashr undef -> undef
482 return const_cast<Constant*>(C1); // X ashr undef --> X
483 case Instruction::Shl:
484 // undef << X -> 0 or X << undef -> 0
485 return Constant::getNullValue(C1->getType());
489 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
490 if (isa<ConstantExpr>(C2)) {
491 // There are many possible foldings we could do here. We should probably
492 // at least fold add of a pointer with an integer into the appropriate
493 // getelementptr. This will improve alias analysis a bit.
495 // Just implement a couple of simple identities.
497 case Instruction::Add:
498 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
500 case Instruction::Sub:
501 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
503 case Instruction::Mul:
504 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
506 if (CI->equalsInt(1))
507 return const_cast<Constant*>(C1); // X * 1 == X
509 case Instruction::UDiv:
510 case Instruction::SDiv:
511 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
512 if (CI->equalsInt(1))
513 return const_cast<Constant*>(C1); // X / 1 == X
515 case Instruction::URem:
516 case Instruction::SRem:
517 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
518 if (CI->equalsInt(1))
519 return Constant::getNullValue(CI->getType()); // X % 1 == 0
521 case Instruction::And:
522 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
523 if (CI->isAllOnesValue())
524 return const_cast<Constant*>(C1); // X & -1 == X
525 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X & 0 == 0
526 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
527 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
529 // Functions are at least 4-byte aligned. If and'ing the address of a
530 // function with a constant < 4, fold it to zero.
531 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
532 if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
534 return Constant::getNullValue(CI->getType());
537 case Instruction::Or:
538 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
539 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
540 if (CI->isAllOnesValue())
541 return const_cast<Constant*>(C2); // X | -1 == -1
543 case Instruction::Xor:
544 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
548 } else if (isa<ConstantExpr>(C2)) {
549 // If C2 is a constant expr and C1 isn't, flop them around and fold the
550 // other way if possible.
552 case Instruction::Add:
553 case Instruction::Mul:
554 case Instruction::And:
555 case Instruction::Or:
556 case Instruction::Xor:
557 // No change of opcode required.
558 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
560 case Instruction::Shl:
561 case Instruction::LShr:
562 case Instruction::AShr:
563 case Instruction::Sub:
564 case Instruction::SDiv:
565 case Instruction::UDiv:
566 case Instruction::FDiv:
567 case Instruction::URem:
568 case Instruction::SRem:
569 case Instruction::FRem:
570 default: // These instructions cannot be flopped around.
575 // At this point we know neither constant is an UndefValue nor a ConstantExpr
576 // so look at directly computing the value.
577 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
578 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
579 using namespace APIntOps;
580 APInt C1V = CI1->getValue();
581 APInt C2V = CI2->getValue();
585 case Instruction::Add:
586 return ConstantInt::get(C1V + C2V);
587 case Instruction::Sub:
588 return ConstantInt::get(C1V - C2V);
589 case Instruction::Mul:
590 return ConstantInt::get(C1V * C2V);
591 case Instruction::UDiv:
592 if (CI2->isNullValue())
593 return 0; // X / 0 -> can't fold
594 return ConstantInt::get(C1V.udiv(C2V));
595 case Instruction::SDiv:
596 if (CI2->isNullValue())
597 return 0; // X / 0 -> can't fold
598 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
599 return 0; // MIN_INT / -1 -> overflow
600 return ConstantInt::get(C1V.sdiv(C2V));
601 case Instruction::URem:
602 if (C2->isNullValue())
603 return 0; // X / 0 -> can't fold
604 return ConstantInt::get(C1V.urem(C2V));
605 case Instruction::SRem:
606 if (CI2->isNullValue())
607 return 0; // X % 0 -> can't fold
608 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
609 return 0; // MIN_INT % -1 -> overflow
610 return ConstantInt::get(C1V.srem(C2V));
611 case Instruction::And:
612 return ConstantInt::get(C1V & C2V);
613 case Instruction::Or:
614 return ConstantInt::get(C1V | C2V);
615 case Instruction::Xor:
616 return ConstantInt::get(C1V ^ C2V);
617 case Instruction::Shl:
618 if (uint32_t shiftAmt = C2V.getZExtValue())
619 if (shiftAmt < C1V.getBitWidth())
620 return ConstantInt::get(C1V.shl(shiftAmt));
622 return UndefValue::get(C1->getType()); // too big shift is undef
623 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
624 case Instruction::LShr:
625 if (uint32_t shiftAmt = C2V.getZExtValue())
626 if (shiftAmt < C1V.getBitWidth())
627 return ConstantInt::get(C1V.lshr(shiftAmt));
629 return UndefValue::get(C1->getType()); // too big shift is undef
630 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
631 case Instruction::AShr:
632 if (uint32_t shiftAmt = C2V.getZExtValue())
633 if (shiftAmt < C1V.getBitWidth())
634 return ConstantInt::get(C1V.ashr(shiftAmt));
636 return UndefValue::get(C1->getType()); // too big shift is undef
637 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
640 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
641 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
642 double C1Val = CFP1->getValue();
643 double C2Val = CFP2->getValue();
647 case Instruction::Add:
648 return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
649 case Instruction::Sub:
650 return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
651 case Instruction::Mul:
652 return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
653 case Instruction::FDiv:
654 if (CFP2->isExactlyValue(0.0))
655 return ConstantFP::get(CFP1->getType(),
656 std::numeric_limits<double>::infinity());
657 if (CFP2->isExactlyValue(-0.0))
658 return ConstantFP::get(CFP1->getType(),
659 -std::numeric_limits<double>::infinity());
660 return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
661 case Instruction::FRem:
662 if (CFP2->isNullValue())
664 return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
667 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
668 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
672 case Instruction::Add:
673 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
674 case Instruction::Sub:
675 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
676 case Instruction::Mul:
677 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
678 case Instruction::UDiv:
679 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
680 case Instruction::SDiv:
681 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
682 case Instruction::FDiv:
683 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
684 case Instruction::URem:
685 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
686 case Instruction::SRem:
687 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
688 case Instruction::FRem:
689 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
690 case Instruction::And:
691 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
692 case Instruction::Or:
693 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
694 case Instruction::Xor:
695 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
700 // We don't know how to fold this
704 /// isZeroSizedType - This type is zero sized if its an array or structure of
705 /// zero sized types. The only leaf zero sized type is an empty structure.
706 static bool isMaybeZeroSizedType(const Type *Ty) {
707 if (isa<OpaqueType>(Ty)) return true; // Can't say.
708 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
710 // If all of elements have zero size, this does too.
711 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
712 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
715 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
716 return isMaybeZeroSizedType(ATy->getElementType());
721 /// IdxCompare - Compare the two constants as though they were getelementptr
722 /// indices. This allows coersion of the types to be the same thing.
724 /// If the two constants are the "same" (after coersion), return 0. If the
725 /// first is less than the second, return -1, if the second is less than the
726 /// first, return 1. If the constants are not integral, return -2.
728 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
729 if (C1 == C2) return 0;
731 // Ok, we found a different index. If they are not ConstantInt, we can't do
732 // anything with them.
733 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
734 return -2; // don't know!
736 // Ok, we have two differing integer indices. Sign extend them to be the same
737 // type. Long is always big enough, so we use it.
738 if (C1->getType() != Type::Int64Ty)
739 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
741 if (C2->getType() != Type::Int64Ty)
742 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
744 if (C1 == C2) return 0; // They are equal
746 // If the type being indexed over is really just a zero sized type, there is
747 // no pointer difference being made here.
748 if (isMaybeZeroSizedType(ElTy))
751 // If they are really different, now that they are the same type, then we
752 // found a difference!
753 if (cast<ConstantInt>(C1)->getSExtValue() <
754 cast<ConstantInt>(C2)->getSExtValue())
760 /// evaluateFCmpRelation - This function determines if there is anything we can
761 /// decide about the two constants provided. This doesn't need to handle simple
762 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
763 /// If we can determine that the two constants have a particular relation to
764 /// each other, we should return the corresponding FCmpInst predicate,
765 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
766 /// ConstantFoldCompareInstruction.
768 /// To simplify this code we canonicalize the relation so that the first
769 /// operand is always the most "complex" of the two. We consider ConstantFP
770 /// to be the simplest, and ConstantExprs to be the most complex.
771 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
772 const Constant *V2) {
773 assert(V1->getType() == V2->getType() &&
774 "Cannot compare values of different types!");
775 // Handle degenerate case quickly
776 if (V1 == V2) return FCmpInst::FCMP_OEQ;
778 if (!isa<ConstantExpr>(V1)) {
779 if (!isa<ConstantExpr>(V2)) {
780 // We distilled thisUse the standard constant folder for a few cases
782 Constant *C1 = const_cast<Constant*>(V1);
783 Constant *C2 = const_cast<Constant*>(V2);
784 R = dyn_cast<ConstantInt>(
785 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
786 if (R && !R->isZero())
787 return FCmpInst::FCMP_OEQ;
788 R = dyn_cast<ConstantInt>(
789 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
790 if (R && !R->isZero())
791 return FCmpInst::FCMP_OLT;
792 R = dyn_cast<ConstantInt>(
793 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
794 if (R && !R->isZero())
795 return FCmpInst::FCMP_OGT;
797 // Nothing more we can do
798 return FCmpInst::BAD_FCMP_PREDICATE;
801 // If the first operand is simple and second is ConstantExpr, swap operands.
802 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
803 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
804 return FCmpInst::getSwappedPredicate(SwappedRelation);
806 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
807 // constantexpr or a simple constant.
808 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
809 switch (CE1->getOpcode()) {
810 case Instruction::FPTrunc:
811 case Instruction::FPExt:
812 case Instruction::UIToFP:
813 case Instruction::SIToFP:
814 // We might be able to do something with these but we don't right now.
820 // There are MANY other foldings that we could perform here. They will
821 // probably be added on demand, as they seem needed.
822 return FCmpInst::BAD_FCMP_PREDICATE;
825 /// evaluateICmpRelation - This function determines if there is anything we can
826 /// decide about the two constants provided. This doesn't need to handle simple
827 /// things like integer comparisons, but should instead handle ConstantExprs
828 /// and GlobalValues. If we can determine that the two constants have a
829 /// particular relation to each other, we should return the corresponding ICmp
830 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
832 /// To simplify this code we canonicalize the relation so that the first
833 /// operand is always the most "complex" of the two. We consider simple
834 /// constants (like ConstantInt) to be the simplest, followed by
835 /// GlobalValues, followed by ConstantExpr's (the most complex).
837 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
840 assert(V1->getType() == V2->getType() &&
841 "Cannot compare different types of values!");
842 if (V1 == V2) return ICmpInst::ICMP_EQ;
844 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
845 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
846 // We distilled this down to a simple case, use the standard constant
849 Constant *C1 = const_cast<Constant*>(V1);
850 Constant *C2 = const_cast<Constant*>(V2);
851 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
852 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
853 if (R && !R->isZero())
855 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
856 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
857 if (R && !R->isZero())
859 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
860 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
861 if (R && !R->isZero())
864 // If we couldn't figure it out, bail.
865 return ICmpInst::BAD_ICMP_PREDICATE;
868 // If the first operand is simple, swap operands.
869 ICmpInst::Predicate SwappedRelation =
870 evaluateICmpRelation(V2, V1, isSigned);
871 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
872 return ICmpInst::getSwappedPredicate(SwappedRelation);
874 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
875 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
876 ICmpInst::Predicate SwappedRelation =
877 evaluateICmpRelation(V2, V1, isSigned);
878 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
879 return ICmpInst::getSwappedPredicate(SwappedRelation);
881 return ICmpInst::BAD_ICMP_PREDICATE;
884 // Now we know that the RHS is a GlobalValue or simple constant,
885 // which (since the types must match) means that it's a ConstantPointerNull.
886 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
887 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
888 return ICmpInst::ICMP_NE;
890 // GlobalVals can never be null.
891 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
892 if (!CPR1->hasExternalWeakLinkage())
893 return ICmpInst::ICMP_NE;
896 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
897 // constantexpr, a CPR, or a simple constant.
898 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
899 const Constant *CE1Op0 = CE1->getOperand(0);
901 switch (CE1->getOpcode()) {
902 case Instruction::Trunc:
903 case Instruction::FPTrunc:
904 case Instruction::FPExt:
905 case Instruction::FPToUI:
906 case Instruction::FPToSI:
907 break; // We can't evaluate floating point casts or truncations.
909 case Instruction::UIToFP:
910 case Instruction::SIToFP:
911 case Instruction::IntToPtr:
912 case Instruction::BitCast:
913 case Instruction::ZExt:
914 case Instruction::SExt:
915 case Instruction::PtrToInt:
916 // If the cast is not actually changing bits, and the second operand is a
917 // null pointer, do the comparison with the pre-casted value.
918 if (V2->isNullValue() &&
919 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
920 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
921 (CE1->getOpcode() == Instruction::SExt ? true :
922 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
923 return evaluateICmpRelation(
924 CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
927 // If the dest type is a pointer type, and the RHS is a constantexpr cast
928 // from the same type as the src of the LHS, evaluate the inputs. This is
929 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
930 // which happens a lot in compilers with tagged integers.
931 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
932 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
933 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
934 CE1->getOperand(0)->getType()->isInteger()) {
935 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
936 (CE1->getOpcode() == Instruction::SExt ? true :
937 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
938 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
943 case Instruction::GetElementPtr:
944 // Ok, since this is a getelementptr, we know that the constant has a
945 // pointer type. Check the various cases.
946 if (isa<ConstantPointerNull>(V2)) {
947 // If we are comparing a GEP to a null pointer, check to see if the base
948 // of the GEP equals the null pointer.
949 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
950 if (GV->hasExternalWeakLinkage())
951 // Weak linkage GVals could be zero or not. We're comparing that
952 // to null pointer so its greater-or-equal
953 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
955 // If its not weak linkage, the GVal must have a non-zero address
956 // so the result is greater-than
957 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
958 } else if (isa<ConstantPointerNull>(CE1Op0)) {
959 // If we are indexing from a null pointer, check to see if we have any
961 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
962 if (!CE1->getOperand(i)->isNullValue())
963 // Offsetting from null, must not be equal.
964 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
965 // Only zero indexes from null, must still be zero.
966 return ICmpInst::ICMP_EQ;
968 // Otherwise, we can't really say if the first operand is null or not.
969 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
970 if (isa<ConstantPointerNull>(CE1Op0)) {
971 if (CPR2->hasExternalWeakLinkage())
972 // Weak linkage GVals could be zero or not. We're comparing it to
973 // a null pointer, so its less-or-equal
974 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
976 // If its not weak linkage, the GVal must have a non-zero address
977 // so the result is less-than
978 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
979 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
981 // If this is a getelementptr of the same global, then it must be
982 // different. Because the types must match, the getelementptr could
983 // only have at most one index, and because we fold getelementptr's
984 // with a single zero index, it must be nonzero.
985 assert(CE1->getNumOperands() == 2 &&
986 !CE1->getOperand(1)->isNullValue() &&
987 "Suprising getelementptr!");
988 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
990 // If they are different globals, we don't know what the value is,
991 // but they can't be equal.
992 return ICmpInst::ICMP_NE;
996 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
997 const Constant *CE2Op0 = CE2->getOperand(0);
999 // There are MANY other foldings that we could perform here. They will
1000 // probably be added on demand, as they seem needed.
1001 switch (CE2->getOpcode()) {
1003 case Instruction::GetElementPtr:
1004 // By far the most common case to handle is when the base pointers are
1005 // obviously to the same or different globals.
1006 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1007 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1008 return ICmpInst::ICMP_NE;
1009 // Ok, we know that both getelementptr instructions are based on the
1010 // same global. From this, we can precisely determine the relative
1011 // ordering of the resultant pointers.
1014 // Compare all of the operands the GEP's have in common.
1015 gep_type_iterator GTI = gep_type_begin(CE1);
1016 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1018 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1019 GTI.getIndexedType())) {
1020 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1021 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1022 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1025 // Ok, we ran out of things they have in common. If any leftovers
1026 // are non-zero then we have a difference, otherwise we are equal.
1027 for (; i < CE1->getNumOperands(); ++i)
1028 if (!CE1->getOperand(i)->isNullValue())
1029 if (isa<ConstantInt>(CE1->getOperand(i)))
1030 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1032 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1034 for (; i < CE2->getNumOperands(); ++i)
1035 if (!CE2->getOperand(i)->isNullValue())
1036 if (isa<ConstantInt>(CE2->getOperand(i)))
1037 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1039 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1040 return ICmpInst::ICMP_EQ;
1049 return ICmpInst::BAD_ICMP_PREDICATE;
1052 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1054 const Constant *C2) {
1056 // Handle some degenerate cases first
1057 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1058 return UndefValue::get(Type::Int1Ty);
1060 // icmp eq/ne(null,GV) -> false/true
1061 if (C1->isNullValue()) {
1062 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1063 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1064 if (pred == ICmpInst::ICMP_EQ)
1065 return ConstantInt::getFalse();
1066 else if (pred == ICmpInst::ICMP_NE)
1067 return ConstantInt::getTrue();
1068 // icmp eq/ne(GV,null) -> false/true
1069 } else if (C2->isNullValue()) {
1070 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1071 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1072 if (pred == ICmpInst::ICMP_EQ)
1073 return ConstantInt::getFalse();
1074 else if (pred == ICmpInst::ICMP_NE)
1075 return ConstantInt::getTrue();
1078 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1079 APInt V1 = cast<ConstantInt>(C1)->getValue();
1080 APInt V2 = cast<ConstantInt>(C2)->getValue();
1082 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1083 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1084 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1085 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1086 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1087 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1088 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1089 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1090 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1091 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1092 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1094 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1095 double C1Val = cast<ConstantFP>(C1)->getValue();
1096 double C2Val = cast<ConstantFP>(C2)->getValue();
1098 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1099 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1100 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1101 case FCmpInst::FCMP_UNO:
1102 return ConstantInt::get(Type::Int1Ty, C1Val != C1Val || C2Val != C2Val);
1103 case FCmpInst::FCMP_ORD:
1104 return ConstantInt::get(Type::Int1Ty, C1Val == C1Val && C2Val == C2Val);
1105 case FCmpInst::FCMP_UEQ:
1106 if (C1Val != C1Val || C2Val != C2Val)
1107 return ConstantInt::getTrue();
1109 case FCmpInst::FCMP_OEQ:
1110 return ConstantInt::get(Type::Int1Ty, C1Val == C2Val);
1111 case FCmpInst::FCMP_UNE:
1112 if (C1Val != C1Val || C2Val != C2Val)
1113 return ConstantInt::getTrue();
1115 case FCmpInst::FCMP_ONE:
1116 return ConstantInt::get(Type::Int1Ty, C1Val != C2Val);
1117 case FCmpInst::FCMP_ULT:
1118 if (C1Val != C1Val || C2Val != C2Val)
1119 return ConstantInt::getTrue();
1121 case FCmpInst::FCMP_OLT:
1122 return ConstantInt::get(Type::Int1Ty, C1Val < C2Val);
1123 case FCmpInst::FCMP_UGT:
1124 if (C1Val != C1Val || C2Val != C2Val)
1125 return ConstantInt::getTrue();
1127 case FCmpInst::FCMP_OGT:
1128 return ConstantInt::get(Type::Int1Ty, C1Val > C2Val);
1129 case FCmpInst::FCMP_ULE:
1130 if (C1Val != C1Val || C2Val != C2Val)
1131 return ConstantInt::getTrue();
1133 case FCmpInst::FCMP_OLE:
1134 return ConstantInt::get(Type::Int1Ty, C1Val <= C2Val);
1135 case FCmpInst::FCMP_UGE:
1136 if (C1Val != C1Val || C2Val != C2Val)
1137 return ConstantInt::getTrue();
1139 case FCmpInst::FCMP_OGE:
1140 return ConstantInt::get(Type::Int1Ty, C1Val >= C2Val);
1142 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1143 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1144 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1145 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1146 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1147 const_cast<Constant*>(CP1->getOperand(i)),
1148 const_cast<Constant*>(CP2->getOperand(i)));
1149 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1152 // Otherwise, could not decide from any element pairs.
1154 } else if (pred == ICmpInst::ICMP_EQ) {
1155 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1156 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1157 const_cast<Constant*>(CP1->getOperand(i)),
1158 const_cast<Constant*>(CP2->getOperand(i)));
1159 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1162 // Otherwise, could not decide from any element pairs.
1168 if (C1->getType()->isFloatingPoint()) {
1169 switch (evaluateFCmpRelation(C1, C2)) {
1170 default: assert(0 && "Unknown relation!");
1171 case FCmpInst::FCMP_UNO:
1172 case FCmpInst::FCMP_ORD:
1173 case FCmpInst::FCMP_UEQ:
1174 case FCmpInst::FCMP_UNE:
1175 case FCmpInst::FCMP_ULT:
1176 case FCmpInst::FCMP_UGT:
1177 case FCmpInst::FCMP_ULE:
1178 case FCmpInst::FCMP_UGE:
1179 case FCmpInst::FCMP_TRUE:
1180 case FCmpInst::FCMP_FALSE:
1181 case FCmpInst::BAD_FCMP_PREDICATE:
1182 break; // Couldn't determine anything about these constants.
1183 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1184 return ConstantInt::get(Type::Int1Ty,
1185 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1186 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1187 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1188 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1189 return ConstantInt::get(Type::Int1Ty,
1190 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1191 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1192 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1193 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1194 return ConstantInt::get(Type::Int1Ty,
1195 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1196 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1197 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1198 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1199 // We can only partially decide this relation.
1200 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1201 return ConstantInt::getFalse();
1202 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1203 return ConstantInt::getTrue();
1205 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1206 // We can only partially decide this relation.
1207 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1208 return ConstantInt::getFalse();
1209 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1210 return ConstantInt::getTrue();
1212 case ICmpInst::ICMP_NE: // We know that C1 != C2
1213 // We can only partially decide this relation.
1214 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1215 return ConstantInt::getFalse();
1216 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1217 return ConstantInt::getTrue();
1221 // Evaluate the relation between the two constants, per the predicate.
1222 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1223 default: assert(0 && "Unknown relational!");
1224 case ICmpInst::BAD_ICMP_PREDICATE:
1225 break; // Couldn't determine anything about these constants.
1226 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1227 // If we know the constants are equal, we can decide the result of this
1228 // computation precisely.
1229 return ConstantInt::get(Type::Int1Ty,
1230 pred == ICmpInst::ICMP_EQ ||
1231 pred == ICmpInst::ICMP_ULE ||
1232 pred == ICmpInst::ICMP_SLE ||
1233 pred == ICmpInst::ICMP_UGE ||
1234 pred == ICmpInst::ICMP_SGE);
1235 case ICmpInst::ICMP_ULT:
1236 // If we know that C1 < C2, we can decide the result of this computation
1238 return ConstantInt::get(Type::Int1Ty,
1239 pred == ICmpInst::ICMP_ULT ||
1240 pred == ICmpInst::ICMP_NE ||
1241 pred == ICmpInst::ICMP_ULE);
1242 case ICmpInst::ICMP_SLT:
1243 // If we know that C1 < C2, we can decide the result of this computation
1245 return ConstantInt::get(Type::Int1Ty,
1246 pred == ICmpInst::ICMP_SLT ||
1247 pred == ICmpInst::ICMP_NE ||
1248 pred == ICmpInst::ICMP_SLE);
1249 case ICmpInst::ICMP_UGT:
1250 // If we know that C1 > C2, we can decide the result of this computation
1252 return ConstantInt::get(Type::Int1Ty,
1253 pred == ICmpInst::ICMP_UGT ||
1254 pred == ICmpInst::ICMP_NE ||
1255 pred == ICmpInst::ICMP_UGE);
1256 case ICmpInst::ICMP_SGT:
1257 // If we know that C1 > C2, we can decide the result of this computation
1259 return ConstantInt::get(Type::Int1Ty,
1260 pred == ICmpInst::ICMP_SGT ||
1261 pred == ICmpInst::ICMP_NE ||
1262 pred == ICmpInst::ICMP_SGE);
1263 case ICmpInst::ICMP_ULE:
1264 // If we know that C1 <= C2, we can only partially decide this relation.
1265 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1266 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1268 case ICmpInst::ICMP_SLE:
1269 // If we know that C1 <= C2, we can only partially decide this relation.
1270 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1271 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1274 case ICmpInst::ICMP_UGE:
1275 // If we know that C1 >= C2, we can only partially decide this relation.
1276 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1277 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1279 case ICmpInst::ICMP_SGE:
1280 // If we know that C1 >= C2, we can only partially decide this relation.
1281 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1282 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1285 case ICmpInst::ICMP_NE:
1286 // If we know that C1 != C2, we can only partially decide this relation.
1287 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1288 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1292 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1293 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1294 // other way if possible.
1296 case ICmpInst::ICMP_EQ:
1297 case ICmpInst::ICMP_NE:
1298 // No change of predicate required.
1299 return ConstantFoldCompareInstruction(pred, C2, C1);
1301 case ICmpInst::ICMP_ULT:
1302 case ICmpInst::ICMP_SLT:
1303 case ICmpInst::ICMP_UGT:
1304 case ICmpInst::ICMP_SGT:
1305 case ICmpInst::ICMP_ULE:
1306 case ICmpInst::ICMP_SLE:
1307 case ICmpInst::ICMP_UGE:
1308 case ICmpInst::ICMP_SGE:
1309 // Change the predicate as necessary to swap the operands.
1310 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1311 return ConstantFoldCompareInstruction(pred, C2, C1);
1313 default: // These predicates cannot be flopped around.
1321 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1322 Constant* const *Idxs,
1325 (NumIdx == 1 && Idxs[0]->isNullValue()))
1326 return const_cast<Constant*>(C);
1328 if (isa<UndefValue>(C)) {
1329 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1330 (Value**)Idxs, NumIdx,
1332 assert(Ty != 0 && "Invalid indices for GEP!");
1333 return UndefValue::get(PointerType::get(Ty));
1336 Constant *Idx0 = Idxs[0];
1337 if (C->isNullValue()) {
1339 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1340 if (!Idxs[i]->isNullValue()) {
1345 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
1346 (Value**)Idxs, NumIdx,
1348 assert(Ty != 0 && "Invalid indices for GEP!");
1349 return ConstantPointerNull::get(PointerType::get(Ty));
1353 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1354 // Combine Indices - If the source pointer to this getelementptr instruction
1355 // is a getelementptr instruction, combine the indices of the two
1356 // getelementptr instructions into a single instruction.
1358 if (CE->getOpcode() == Instruction::GetElementPtr) {
1359 const Type *LastTy = 0;
1360 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1364 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1365 SmallVector<Value*, 16> NewIndices;
1366 NewIndices.reserve(NumIdx + CE->getNumOperands());
1367 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1368 NewIndices.push_back(CE->getOperand(i));
1370 // Add the last index of the source with the first index of the new GEP.
1371 // Make sure to handle the case when they are actually different types.
1372 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1373 // Otherwise it must be an array.
1374 if (!Idx0->isNullValue()) {
1375 const Type *IdxTy = Combined->getType();
1376 if (IdxTy != Idx0->getType()) {
1377 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1378 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1380 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1383 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1387 NewIndices.push_back(Combined);
1388 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1389 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1394 // Implement folding of:
1395 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1397 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1399 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue())
1400 if (const PointerType *SPT =
1401 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1402 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1403 if (const ArrayType *CAT =
1404 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1405 if (CAT->getElementType() == SAT->getElementType())
1406 return ConstantExpr::getGetElementPtr(
1407 (Constant*)CE->getOperand(0), Idxs, NumIdx);