1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file 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 // pieces that don't need TargetData, and the pieces that do. This is to avoid
16 // a dependence in VMCore on Target.
18 //===----------------------------------------------------------------------===//
20 #include "ConstantFold.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
37 //===----------------------------------------------------------------------===//
38 // ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
41 /// BitCastConstantVector - Convert the specified ConstantVector node to the
42 /// specified vector type. At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
45 const VectorType *DstTy) {
46 // If this cast changes element count then we can't handle it here:
47 // doing so requires endianness information. This should be handled by
48 // Analysis/ConstantFolding.cpp
49 unsigned NumElts = DstTy->getNumElements();
50 if (NumElts != CV->getNumOperands())
53 // Check to verify that all elements of the input are simple.
54 for (unsigned i = 0; i != NumElts; ++i) {
55 if (!isa<ConstantInt>(CV->getOperand(i)) &&
56 !isa<ConstantFP>(CV->getOperand(i)))
60 // Bitcast each element now.
61 std::vector<Constant*> Result;
62 const Type *DstEltTy = DstTy->getElementType();
63 for (unsigned i = 0; i != NumElts; ++i)
64 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
66 return ConstantVector::get(Result);
69 /// This function determines which opcode to use to fold two constant cast
70 /// expressions together. It uses CastInst::isEliminableCastPair to determine
71 /// the opcode. Consequently its just a wrapper around that function.
72 /// @brief Determine if it is valid to fold a cast of a cast
75 unsigned opc, ///< opcode of the second cast constant expression
76 ConstantExpr *Op, ///< the first cast constant expression
77 const Type *DstTy ///< desintation type of the first cast
79 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
80 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
81 assert(CastInst::isCast(opc) && "Invalid cast opcode");
83 // The the types and opcodes for the two Cast constant expressions
84 const Type *SrcTy = Op->getOperand(0)->getType();
85 const Type *MidTy = Op->getType();
86 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
87 Instruction::CastOps secondOp = Instruction::CastOps(opc);
89 // Let CastInst::isEliminableCastPair do the heavy lifting.
90 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
91 Type::getInt64Ty(DstTy->getContext()));
94 static Constant *FoldBitCast(LLVMContext &Context,
95 Constant *V, const Type *DestTy) {
96 const Type *SrcTy = V->getType();
98 return V; // no-op cast
100 // Check to see if we are casting a pointer to an aggregate to a pointer to
101 // the first element. If so, return the appropriate GEP instruction.
102 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
103 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
104 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
105 SmallVector<Value*, 8> IdxList;
106 Value *Zero = Constant::getNullValue(Type::getInt32Ty(Context));
107 IdxList.push_back(Zero);
108 const Type *ElTy = PTy->getElementType();
109 while (ElTy != DPTy->getElementType()) {
110 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
111 if (STy->getNumElements() == 0) break;
112 ElTy = STy->getElementType(0);
113 IdxList.push_back(Zero);
114 } else if (const SequentialType *STy =
115 dyn_cast<SequentialType>(ElTy)) {
116 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
117 ElTy = STy->getElementType();
118 IdxList.push_back(Zero);
124 if (ElTy == DPTy->getElementType())
125 // This GEP is inbounds because all indices are zero.
126 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
130 // Handle casts from one vector constant to another. We know that the src
131 // and dest type have the same size (otherwise its an illegal cast).
132 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
133 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
134 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
135 "Not cast between same sized vectors!");
137 // First, check for null. Undef is already handled.
138 if (isa<ConstantAggregateZero>(V))
139 return Constant::getNullValue(DestTy);
141 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
142 return BitCastConstantVector(Context, CV, DestPTy);
145 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
146 // This allows for other simplifications (although some of them
147 // can only be handled by Analysis/ConstantFolding.cpp).
148 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
149 return ConstantExpr::getBitCast(
150 ConstantVector::get(&V, 1), DestPTy);
153 // Finally, implement bitcast folding now. The code below doesn't handle
155 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
156 return ConstantPointerNull::get(cast<PointerType>(DestTy));
158 // Handle integral constant input.
159 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
160 if (DestTy->isInteger())
161 // Integral -> Integral. This is a no-op because the bit widths must
162 // be the same. Consequently, we just fold to V.
165 if (DestTy->isFloatingPoint())
166 return ConstantFP::get(Context, APFloat(CI->getValue(),
167 DestTy != Type::getPPC_FP128Ty(Context)));
169 // Otherwise, can't fold this (vector?)
173 // Handle ConstantFP input.
174 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
176 return ConstantInt::get(Context, FP->getValueAPF().bitcastToAPInt());
182 Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context,
183 unsigned opc, Constant *V,
184 const Type *DestTy) {
185 if (isa<UndefValue>(V)) {
186 // zext(undef) = 0, because the top bits will be zero.
187 // sext(undef) = 0, because the top bits will all be the same.
188 // [us]itofp(undef) = 0, because the result value is bounded.
189 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
190 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
191 return Constant::getNullValue(DestTy);
192 return UndefValue::get(DestTy);
194 // No compile-time operations on this type yet.
195 if (V->getType() == Type::getPPC_FP128Ty(Context) || DestTy == Type::getPPC_FP128Ty(Context))
198 // If the cast operand is a constant expression, there's a few things we can
199 // do to try to simplify it.
200 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
202 // Try hard to fold cast of cast because they are often eliminable.
203 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
204 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
205 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
206 // If all of the indexes in the GEP are null values, there is no pointer
207 // adjustment going on. We might as well cast the source pointer.
208 bool isAllNull = true;
209 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
210 if (!CE->getOperand(i)->isNullValue()) {
215 // This is casting one pointer type to another, always BitCast
216 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
220 // If the cast operand is a constant vector, perform the cast by
221 // operating on each element. In the cast of bitcasts, the element
222 // count may be mismatched; don't attempt to handle that here.
223 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
224 if (isa<VectorType>(DestTy) &&
225 cast<VectorType>(DestTy)->getNumElements() ==
226 CV->getType()->getNumElements()) {
227 std::vector<Constant*> res;
228 const VectorType *DestVecTy = cast<VectorType>(DestTy);
229 const Type *DstEltTy = DestVecTy->getElementType();
230 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
231 res.push_back(ConstantExpr::getCast(opc,
232 CV->getOperand(i), DstEltTy));
233 return ConstantVector::get(DestVecTy, res);
236 // We actually have to do a cast now. Perform the cast according to the
239 case Instruction::FPTrunc:
240 case Instruction::FPExt:
241 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
243 APFloat Val = FPC->getValueAPF();
244 Val.convert(DestTy == Type::getFloatTy(Context) ? APFloat::IEEEsingle :
245 DestTy == Type::getDoubleTy(Context) ? APFloat::IEEEdouble :
246 DestTy == Type::getX86_FP80Ty(Context) ? APFloat::x87DoubleExtended :
247 DestTy == Type::getFP128Ty(Context) ? APFloat::IEEEquad :
249 APFloat::rmNearestTiesToEven, &ignored);
250 return ConstantFP::get(Context, Val);
252 return 0; // Can't fold.
253 case Instruction::FPToUI:
254 case Instruction::FPToSI:
255 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
256 const APFloat &V = FPC->getValueAPF();
259 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
260 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
261 APFloat::rmTowardZero, &ignored);
262 APInt Val(DestBitWidth, 2, x);
263 return ConstantInt::get(Context, Val);
265 return 0; // Can't fold.
266 case Instruction::IntToPtr: //always treated as unsigned
267 if (V->isNullValue()) // Is it an integral null value?
268 return ConstantPointerNull::get(cast<PointerType>(DestTy));
269 return 0; // Other pointer types cannot be casted
270 case Instruction::PtrToInt: // always treated as unsigned
271 if (V->isNullValue()) // is it a null pointer value?
272 return ConstantInt::get(DestTy, 0);
273 return 0; // Other pointer types cannot be casted
274 case Instruction::UIToFP:
275 case Instruction::SIToFP:
276 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
277 APInt api = CI->getValue();
278 const uint64_t zero[] = {0, 0};
279 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
281 (void)apf.convertFromAPInt(api,
282 opc==Instruction::SIToFP,
283 APFloat::rmNearestTiesToEven);
284 return ConstantFP::get(Context, apf);
287 case Instruction::ZExt:
288 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
289 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
290 APInt Result(CI->getValue());
291 Result.zext(BitWidth);
292 return ConstantInt::get(Context, Result);
295 case Instruction::SExt:
296 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
297 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
298 APInt Result(CI->getValue());
299 Result.sext(BitWidth);
300 return ConstantInt::get(Context, Result);
303 case Instruction::Trunc:
304 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
305 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
306 APInt Result(CI->getValue());
307 Result.trunc(BitWidth);
308 return ConstantInt::get(Context, Result);
311 case Instruction::BitCast:
312 return FoldBitCast(Context, V, DestTy);
314 assert(!"Invalid CE CastInst opcode");
318 llvm_unreachable("Failed to cast constant expression");
322 Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
324 Constant *V1, Constant *V2) {
325 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
326 return CB->getZExtValue() ? V1 : V2;
328 if (isa<UndefValue>(V1)) return V2;
329 if (isa<UndefValue>(V2)) return V1;
330 if (isa<UndefValue>(Cond)) return V1;
331 if (V1 == V2) return V1;
335 Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
338 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
339 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
340 if (Val->isNullValue()) // ee(zero, x) -> zero
341 return Constant::getNullValue(
342 cast<VectorType>(Val->getType())->getElementType());
344 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
345 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
346 return CVal->getOperand(CIdx->getZExtValue());
347 } else if (isa<UndefValue>(Idx)) {
348 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
349 return CVal->getOperand(0);
355 Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
359 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
361 APInt idxVal = CIdx->getValue();
362 if (isa<UndefValue>(Val)) {
363 // Insertion of scalar constant into vector undef
364 // Optimize away insertion of undef
365 if (isa<UndefValue>(Elt))
367 // Otherwise break the aggregate undef into multiple undefs and do
370 cast<VectorType>(Val->getType())->getNumElements();
371 std::vector<Constant*> Ops;
373 for (unsigned i = 0; i < numOps; ++i) {
375 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
378 return ConstantVector::get(Ops);
380 if (isa<ConstantAggregateZero>(Val)) {
381 // Insertion of scalar constant into vector aggregate zero
382 // Optimize away insertion of zero
383 if (Elt->isNullValue())
385 // Otherwise break the aggregate zero into multiple zeros and do
388 cast<VectorType>(Val->getType())->getNumElements();
389 std::vector<Constant*> Ops;
391 for (unsigned i = 0; i < numOps; ++i) {
393 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
396 return ConstantVector::get(Ops);
398 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
399 // Insertion of scalar constant into vector constant
400 std::vector<Constant*> Ops;
401 Ops.reserve(CVal->getNumOperands());
402 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
404 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
407 return ConstantVector::get(Ops);
413 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
414 /// return the specified element value. Otherwise return null.
415 static Constant *GetVectorElement(LLVMContext &Context, Constant *C,
417 if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
418 return CV->getOperand(EltNo);
420 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
421 if (isa<ConstantAggregateZero>(C))
422 return Constant::getNullValue(EltTy);
423 if (isa<UndefValue>(C))
424 return UndefValue::get(EltTy);
428 Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
432 // Undefined shuffle mask -> undefined value.
433 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
435 unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
436 unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
437 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
439 // Loop over the shuffle mask, evaluating each element.
440 SmallVector<Constant*, 32> Result;
441 for (unsigned i = 0; i != MaskNumElts; ++i) {
442 Constant *InElt = GetVectorElement(Context, Mask, i);
443 if (InElt == 0) return 0;
445 if (isa<UndefValue>(InElt))
446 InElt = UndefValue::get(EltTy);
447 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
448 unsigned Elt = CI->getZExtValue();
449 if (Elt >= SrcNumElts*2)
450 InElt = UndefValue::get(EltTy);
451 else if (Elt >= SrcNumElts)
452 InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
454 InElt = GetVectorElement(Context, V1, Elt);
455 if (InElt == 0) return 0;
460 Result.push_back(InElt);
463 return ConstantVector::get(&Result[0], Result.size());
466 Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
468 const unsigned *Idxs,
470 // Base case: no indices, so return the entire value.
474 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
475 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
479 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
481 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
485 // Otherwise recurse.
486 return ConstantFoldExtractValueInstruction(Context, Agg->getOperand(*Idxs),
490 Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
493 const unsigned *Idxs,
495 // Base case: no indices, so replace the entire value.
499 if (isa<UndefValue>(Agg)) {
500 // Insertion of constant into aggregate undef
501 // Optimize away insertion of undef.
502 if (isa<UndefValue>(Val))
505 // Otherwise break the aggregate undef into multiple undefs and do
507 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
509 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
510 numOps = AR->getNumElements();
512 numOps = cast<StructType>(AggTy)->getNumElements();
514 std::vector<Constant*> Ops(numOps);
515 for (unsigned i = 0; i < numOps; ++i) {
516 const Type *MemberTy = AggTy->getTypeAtIndex(i);
519 ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
520 Val, Idxs+1, NumIdx-1) :
521 UndefValue::get(MemberTy);
525 if (const StructType* ST = dyn_cast<StructType>(AggTy))
526 return ConstantStruct::get(Context, Ops, ST->isPacked());
527 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
530 if (isa<ConstantAggregateZero>(Agg)) {
531 // Insertion of constant into aggregate zero
532 // Optimize away insertion of zero.
533 if (Val->isNullValue())
536 // Otherwise break the aggregate zero into multiple zeros and do
538 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
540 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
541 numOps = AR->getNumElements();
543 numOps = cast<StructType>(AggTy)->getNumElements();
545 std::vector<Constant*> Ops(numOps);
546 for (unsigned i = 0; i < numOps; ++i) {
547 const Type *MemberTy = AggTy->getTypeAtIndex(i);
550 ConstantFoldInsertValueInstruction(Context,
551 Constant::getNullValue(MemberTy),
552 Val, Idxs+1, NumIdx-1) :
553 Constant::getNullValue(MemberTy);
557 if (const StructType* ST = dyn_cast<StructType>(AggTy))
558 return ConstantStruct::get(Context, Ops, ST->isPacked());
559 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
562 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
563 // Insertion of constant into aggregate constant.
564 std::vector<Constant*> Ops(Agg->getNumOperands());
565 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
568 ConstantFoldInsertValueInstruction(Context, Agg->getOperand(i),
569 Val, Idxs+1, NumIdx-1) :
574 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
575 return ConstantStruct::get(Context, Ops, ST->isPacked());
576 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
583 Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
585 Constant *C1, Constant *C2) {
586 // No compile-time operations on this type yet.
587 if (C1->getType() == Type::getPPC_FP128Ty(Context))
590 // Handle UndefValue up front.
591 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
593 case Instruction::Xor:
594 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
595 // Handle undef ^ undef -> 0 special case. This is a common
597 return Constant::getNullValue(C1->getType());
599 case Instruction::Add:
600 case Instruction::Sub:
601 return UndefValue::get(C1->getType());
602 case Instruction::Mul:
603 case Instruction::And:
604 return Constant::getNullValue(C1->getType());
605 case Instruction::UDiv:
606 case Instruction::SDiv:
607 case Instruction::URem:
608 case Instruction::SRem:
609 if (!isa<UndefValue>(C2)) // undef / X -> 0
610 return Constant::getNullValue(C1->getType());
611 return C2; // X / undef -> undef
612 case Instruction::Or: // X | undef -> -1
613 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
614 return Constant::getAllOnesValue(PTy);
615 return Constant::getAllOnesValue(C1->getType());
616 case Instruction::LShr:
617 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
618 return C1; // undef lshr undef -> undef
619 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
621 case Instruction::AShr:
622 if (!isa<UndefValue>(C2))
623 return C1; // undef ashr X --> undef
624 else if (isa<UndefValue>(C1))
625 return C1; // undef ashr undef -> undef
627 return C1; // X ashr undef --> X
628 case Instruction::Shl:
629 // undef << X -> 0 or X << undef -> 0
630 return Constant::getNullValue(C1->getType());
634 // Handle simplifications when the RHS is a constant int.
635 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
637 case Instruction::Add:
638 if (CI2->equalsInt(0)) return C1; // X + 0 == X
640 case Instruction::Sub:
641 if (CI2->equalsInt(0)) return C1; // X - 0 == X
643 case Instruction::Mul:
644 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
645 if (CI2->equalsInt(1))
646 return C1; // X * 1 == X
648 case Instruction::UDiv:
649 case Instruction::SDiv:
650 if (CI2->equalsInt(1))
651 return C1; // X / 1 == X
652 if (CI2->equalsInt(0))
653 return UndefValue::get(CI2->getType()); // X / 0 == undef
655 case Instruction::URem:
656 case Instruction::SRem:
657 if (CI2->equalsInt(1))
658 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
659 if (CI2->equalsInt(0))
660 return UndefValue::get(CI2->getType()); // X % 0 == undef
662 case Instruction::And:
663 if (CI2->isZero()) return C2; // X & 0 == 0
664 if (CI2->isAllOnesValue())
665 return C1; // X & -1 == X
667 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
668 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
669 if (CE1->getOpcode() == Instruction::ZExt) {
670 unsigned DstWidth = CI2->getType()->getBitWidth();
672 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
673 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
674 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
678 // If and'ing the address of a global with a constant, fold it.
679 if (CE1->getOpcode() == Instruction::PtrToInt &&
680 isa<GlobalValue>(CE1->getOperand(0))) {
681 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
683 // Functions are at least 4-byte aligned.
684 unsigned GVAlign = GV->getAlignment();
685 if (isa<Function>(GV))
686 GVAlign = std::max(GVAlign, 4U);
689 unsigned DstWidth = CI2->getType()->getBitWidth();
690 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
691 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
693 // If checking bits we know are clear, return zero.
694 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
695 return Constant::getNullValue(CI2->getType());
700 case Instruction::Or:
701 if (CI2->equalsInt(0)) return C1; // X | 0 == X
702 if (CI2->isAllOnesValue())
703 return C2; // X | -1 == -1
705 case Instruction::Xor:
706 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
708 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
709 switch (CE1->getOpcode()) {
711 case Instruction::ICmp:
712 case Instruction::FCmp:
713 // cmp pred ^ true -> cmp !pred
714 assert(CI2->equalsInt(1));
715 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
716 pred = CmpInst::getInversePredicate(pred);
717 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
722 case Instruction::AShr:
723 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
724 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
725 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
726 return ConstantExpr::getLShr(C1, C2);
731 // At this point we know neither constant is an UndefValue.
732 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
733 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
734 using namespace APIntOps;
735 const APInt &C1V = CI1->getValue();
736 const APInt &C2V = CI2->getValue();
740 case Instruction::Add:
741 return ConstantInt::get(Context, C1V + C2V);
742 case Instruction::Sub:
743 return ConstantInt::get(Context, C1V - C2V);
744 case Instruction::Mul:
745 return ConstantInt::get(Context, C1V * C2V);
746 case Instruction::UDiv:
747 assert(!CI2->isNullValue() && "Div by zero handled above");
748 return ConstantInt::get(Context, C1V.udiv(C2V));
749 case Instruction::SDiv:
750 assert(!CI2->isNullValue() && "Div by zero handled above");
751 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
752 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
753 return ConstantInt::get(Context, C1V.sdiv(C2V));
754 case Instruction::URem:
755 assert(!CI2->isNullValue() && "Div by zero handled above");
756 return ConstantInt::get(Context, C1V.urem(C2V));
757 case Instruction::SRem:
758 assert(!CI2->isNullValue() && "Div by zero handled above");
759 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
760 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
761 return ConstantInt::get(Context, C1V.srem(C2V));
762 case Instruction::And:
763 return ConstantInt::get(Context, C1V & C2V);
764 case Instruction::Or:
765 return ConstantInt::get(Context, C1V | C2V);
766 case Instruction::Xor:
767 return ConstantInt::get(Context, C1V ^ C2V);
768 case Instruction::Shl: {
769 uint32_t shiftAmt = C2V.getZExtValue();
770 if (shiftAmt < C1V.getBitWidth())
771 return ConstantInt::get(Context, C1V.shl(shiftAmt));
773 return UndefValue::get(C1->getType()); // too big shift is undef
775 case Instruction::LShr: {
776 uint32_t shiftAmt = C2V.getZExtValue();
777 if (shiftAmt < C1V.getBitWidth())
778 return ConstantInt::get(Context, C1V.lshr(shiftAmt));
780 return UndefValue::get(C1->getType()); // too big shift is undef
782 case Instruction::AShr: {
783 uint32_t shiftAmt = C2V.getZExtValue();
784 if (shiftAmt < C1V.getBitWidth())
785 return ConstantInt::get(Context, C1V.ashr(shiftAmt));
787 return UndefValue::get(C1->getType()); // too big shift is undef
793 case Instruction::SDiv:
794 case Instruction::UDiv:
795 case Instruction::URem:
796 case Instruction::SRem:
797 case Instruction::LShr:
798 case Instruction::AShr:
799 case Instruction::Shl:
800 if (CI1->equalsInt(0)) return C1;
805 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
806 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
807 APFloat C1V = CFP1->getValueAPF();
808 APFloat C2V = CFP2->getValueAPF();
809 APFloat C3V = C1V; // copy for modification
813 case Instruction::FAdd:
814 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
815 return ConstantFP::get(Context, C3V);
816 case Instruction::FSub:
817 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
818 return ConstantFP::get(Context, C3V);
819 case Instruction::FMul:
820 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
821 return ConstantFP::get(Context, C3V);
822 case Instruction::FDiv:
823 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
824 return ConstantFP::get(Context, C3V);
825 case Instruction::FRem:
826 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
827 return ConstantFP::get(Context, C3V);
830 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
831 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
832 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
833 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
834 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
835 std::vector<Constant*> Res;
836 const Type* EltTy = VTy->getElementType();
842 case Instruction::Add:
843 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
844 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
845 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
846 Res.push_back(ConstantExpr::getAdd(C1, C2));
848 return ConstantVector::get(Res);
849 case Instruction::FAdd:
850 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
851 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
852 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
853 Res.push_back(ConstantExpr::getFAdd(C1, C2));
855 return ConstantVector::get(Res);
856 case Instruction::Sub:
857 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
858 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
859 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
860 Res.push_back(ConstantExpr::getSub(C1, C2));
862 return ConstantVector::get(Res);
863 case Instruction::FSub:
864 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
865 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
866 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
867 Res.push_back(ConstantExpr::getFSub(C1, C2));
869 return ConstantVector::get(Res);
870 case Instruction::Mul:
871 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
872 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
873 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
874 Res.push_back(ConstantExpr::getMul(C1, C2));
876 return ConstantVector::get(Res);
877 case Instruction::FMul:
878 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
879 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
880 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
881 Res.push_back(ConstantExpr::getFMul(C1, C2));
883 return ConstantVector::get(Res);
884 case Instruction::UDiv:
885 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
886 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
887 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
888 Res.push_back(ConstantExpr::getUDiv(C1, C2));
890 return ConstantVector::get(Res);
891 case Instruction::SDiv:
892 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
893 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
894 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
895 Res.push_back(ConstantExpr::getSDiv(C1, C2));
897 return ConstantVector::get(Res);
898 case Instruction::FDiv:
899 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
900 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
901 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
902 Res.push_back(ConstantExpr::getFDiv(C1, C2));
904 return ConstantVector::get(Res);
905 case Instruction::URem:
906 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
907 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
908 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
909 Res.push_back(ConstantExpr::getURem(C1, C2));
911 return ConstantVector::get(Res);
912 case Instruction::SRem:
913 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
914 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
915 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
916 Res.push_back(ConstantExpr::getSRem(C1, C2));
918 return ConstantVector::get(Res);
919 case Instruction::FRem:
920 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
921 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
922 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
923 Res.push_back(ConstantExpr::getFRem(C1, C2));
925 return ConstantVector::get(Res);
926 case Instruction::And:
927 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
928 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
929 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
930 Res.push_back(ConstantExpr::getAnd(C1, C2));
932 return ConstantVector::get(Res);
933 case Instruction::Or:
934 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
935 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
936 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
937 Res.push_back(ConstantExpr::getOr(C1, C2));
939 return ConstantVector::get(Res);
940 case Instruction::Xor:
941 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
942 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
943 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
944 Res.push_back(ConstantExpr::getXor(C1, C2));
946 return ConstantVector::get(Res);
947 case Instruction::LShr:
948 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
949 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
950 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
951 Res.push_back(ConstantExpr::getLShr(C1, C2));
953 return ConstantVector::get(Res);
954 case Instruction::AShr:
955 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
956 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
957 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
958 Res.push_back(ConstantExpr::getAShr(C1, C2));
960 return ConstantVector::get(Res);
961 case Instruction::Shl:
962 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
963 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
964 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
965 Res.push_back(ConstantExpr::getShl(C1, C2));
967 return ConstantVector::get(Res);
972 if (isa<ConstantExpr>(C1)) {
973 // There are many possible foldings we could do here. We should probably
974 // at least fold add of a pointer with an integer into the appropriate
975 // getelementptr. This will improve alias analysis a bit.
976 } else if (isa<ConstantExpr>(C2)) {
977 // If C2 is a constant expr and C1 isn't, flop them around and fold the
978 // other way if possible.
980 case Instruction::Add:
981 case Instruction::FAdd:
982 case Instruction::Mul:
983 case Instruction::FMul:
984 case Instruction::And:
985 case Instruction::Or:
986 case Instruction::Xor:
987 // No change of opcode required.
988 return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
990 case Instruction::Shl:
991 case Instruction::LShr:
992 case Instruction::AShr:
993 case Instruction::Sub:
994 case Instruction::FSub:
995 case Instruction::SDiv:
996 case Instruction::UDiv:
997 case Instruction::FDiv:
998 case Instruction::URem:
999 case Instruction::SRem:
1000 case Instruction::FRem:
1001 default: // These instructions cannot be flopped around.
1006 // i1 can be simplified in many cases.
1007 if (C1->getType() == Type::getInt1Ty(Context)) {
1009 case Instruction::Add:
1010 case Instruction::Sub:
1011 return ConstantExpr::getXor(C1, C2);
1012 case Instruction::Mul:
1013 return ConstantExpr::getAnd(C1, C2);
1014 case Instruction::Shl:
1015 case Instruction::LShr:
1016 case Instruction::AShr:
1017 // We can assume that C2 == 0. If it were one the result would be
1018 // undefined because the shift value is as large as the bitwidth.
1020 case Instruction::SDiv:
1021 case Instruction::UDiv:
1022 // We can assume that C2 == 1. If it were zero the result would be
1023 // undefined through division by zero.
1025 case Instruction::URem:
1026 case Instruction::SRem:
1027 // We can assume that C2 == 1. If it were zero the result would be
1028 // undefined through division by zero.
1029 return ConstantInt::getFalse(Context);
1035 // We don't know how to fold this.
1039 /// isZeroSizedType - This type is zero sized if its an array or structure of
1040 /// zero sized types. The only leaf zero sized type is an empty structure.
1041 static bool isMaybeZeroSizedType(const Type *Ty) {
1042 if (isa<OpaqueType>(Ty)) return true; // Can't say.
1043 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1045 // If all of elements have zero size, this does too.
1046 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1047 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1050 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1051 return isMaybeZeroSizedType(ATy->getElementType());
1056 /// IdxCompare - Compare the two constants as though they were getelementptr
1057 /// indices. This allows coersion of the types to be the same thing.
1059 /// If the two constants are the "same" (after coersion), return 0. If the
1060 /// first is less than the second, return -1, if the second is less than the
1061 /// first, return 1. If the constants are not integral, return -2.
1063 static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2,
1065 if (C1 == C2) return 0;
1067 // Ok, we found a different index. If they are not ConstantInt, we can't do
1068 // anything with them.
1069 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1070 return -2; // don't know!
1072 // Ok, we have two differing integer indices. Sign extend them to be the same
1073 // type. Long is always big enough, so we use it.
1074 if (C1->getType() != Type::getInt64Ty(Context))
1075 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
1077 if (C2->getType() != Type::getInt64Ty(Context))
1078 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
1080 if (C1 == C2) return 0; // They are equal
1082 // If the type being indexed over is really just a zero sized type, there is
1083 // no pointer difference being made here.
1084 if (isMaybeZeroSizedType(ElTy))
1085 return -2; // dunno.
1087 // If they are really different, now that they are the same type, then we
1088 // found a difference!
1089 if (cast<ConstantInt>(C1)->getSExtValue() <
1090 cast<ConstantInt>(C2)->getSExtValue())
1096 /// evaluateFCmpRelation - This function determines if there is anything we can
1097 /// decide about the two constants provided. This doesn't need to handle simple
1098 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1099 /// If we can determine that the two constants have a particular relation to
1100 /// each other, we should return the corresponding FCmpInst predicate,
1101 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1102 /// ConstantFoldCompareInstruction.
1104 /// To simplify this code we canonicalize the relation so that the first
1105 /// operand is always the most "complex" of the two. We consider ConstantFP
1106 /// to be the simplest, and ConstantExprs to be the most complex.
1107 static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
1108 Constant *V1, Constant *V2) {
1109 assert(V1->getType() == V2->getType() &&
1110 "Cannot compare values of different types!");
1112 // No compile-time operations on this type yet.
1113 if (V1->getType() == Type::getPPC_FP128Ty(Context))
1114 return FCmpInst::BAD_FCMP_PREDICATE;
1116 // Handle degenerate case quickly
1117 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1119 if (!isa<ConstantExpr>(V1)) {
1120 if (!isa<ConstantExpr>(V2)) {
1121 // We distilled thisUse the standard constant folder for a few cases
1123 R = dyn_cast<ConstantInt>(
1124 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1125 if (R && !R->isZero())
1126 return FCmpInst::FCMP_OEQ;
1127 R = dyn_cast<ConstantInt>(
1128 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1129 if (R && !R->isZero())
1130 return FCmpInst::FCMP_OLT;
1131 R = dyn_cast<ConstantInt>(
1132 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1133 if (R && !R->isZero())
1134 return FCmpInst::FCMP_OGT;
1136 // Nothing more we can do
1137 return FCmpInst::BAD_FCMP_PREDICATE;
1140 // If the first operand is simple and second is ConstantExpr, swap operands.
1141 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
1142 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1143 return FCmpInst::getSwappedPredicate(SwappedRelation);
1145 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1146 // constantexpr or a simple constant.
1147 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1148 switch (CE1->getOpcode()) {
1149 case Instruction::FPTrunc:
1150 case Instruction::FPExt:
1151 case Instruction::UIToFP:
1152 case Instruction::SIToFP:
1153 // We might be able to do something with these but we don't right now.
1159 // There are MANY other foldings that we could perform here. They will
1160 // probably be added on demand, as they seem needed.
1161 return FCmpInst::BAD_FCMP_PREDICATE;
1164 /// evaluateICmpRelation - This function determines if there is anything we can
1165 /// decide about the two constants provided. This doesn't need to handle simple
1166 /// things like integer comparisons, but should instead handle ConstantExprs
1167 /// and GlobalValues. If we can determine that the two constants have a
1168 /// particular relation to each other, we should return the corresponding ICmp
1169 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1171 /// To simplify this code we canonicalize the relation so that the first
1172 /// operand is always the most "complex" of the two. We consider simple
1173 /// constants (like ConstantInt) to be the simplest, followed by
1174 /// GlobalValues, followed by ConstantExpr's (the most complex).
1176 static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
1180 assert(V1->getType() == V2->getType() &&
1181 "Cannot compare different types of values!");
1182 if (V1 == V2) return ICmpInst::ICMP_EQ;
1184 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1185 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1186 // We distilled this down to a simple case, use the standard constant
1189 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1190 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1191 if (R && !R->isZero())
1193 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1194 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1195 if (R && !R->isZero())
1197 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1198 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1199 if (R && !R->isZero())
1202 // If we couldn't figure it out, bail.
1203 return ICmpInst::BAD_ICMP_PREDICATE;
1206 // If the first operand is simple, swap operands.
1207 ICmpInst::Predicate SwappedRelation =
1208 evaluateICmpRelation(Context, V2, V1, isSigned);
1209 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1210 return ICmpInst::getSwappedPredicate(SwappedRelation);
1212 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1213 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1214 ICmpInst::Predicate SwappedRelation =
1215 evaluateICmpRelation(Context, V2, V1, isSigned);
1216 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1217 return ICmpInst::getSwappedPredicate(SwappedRelation);
1219 return ICmpInst::BAD_ICMP_PREDICATE;
1222 // Now we know that the RHS is a GlobalValue or simple constant,
1223 // which (since the types must match) means that it's a ConstantPointerNull.
1224 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1225 // Don't try to decide equality of aliases.
1226 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1227 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1228 return ICmpInst::ICMP_NE;
1230 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1231 // GlobalVals can never be null. Don't try to evaluate aliases.
1232 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
1233 return ICmpInst::ICMP_NE;
1236 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1237 // constantexpr, a CPR, or a simple constant.
1238 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1239 Constant *CE1Op0 = CE1->getOperand(0);
1241 switch (CE1->getOpcode()) {
1242 case Instruction::Trunc:
1243 case Instruction::FPTrunc:
1244 case Instruction::FPExt:
1245 case Instruction::FPToUI:
1246 case Instruction::FPToSI:
1247 break; // We can't evaluate floating point casts or truncations.
1249 case Instruction::UIToFP:
1250 case Instruction::SIToFP:
1251 case Instruction::BitCast:
1252 case Instruction::ZExt:
1253 case Instruction::SExt:
1254 // If the cast is not actually changing bits, and the second operand is a
1255 // null pointer, do the comparison with the pre-casted value.
1256 if (V2->isNullValue() &&
1257 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1258 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1259 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1260 return evaluateICmpRelation(Context, CE1Op0,
1261 Constant::getNullValue(CE1Op0->getType()),
1266 case Instruction::GetElementPtr:
1267 // Ok, since this is a getelementptr, we know that the constant has a
1268 // pointer type. Check the various cases.
1269 if (isa<ConstantPointerNull>(V2)) {
1270 // If we are comparing a GEP to a null pointer, check to see if the base
1271 // of the GEP equals the null pointer.
1272 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1273 if (GV->hasExternalWeakLinkage())
1274 // Weak linkage GVals could be zero or not. We're comparing that
1275 // to null pointer so its greater-or-equal
1276 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1278 // If its not weak linkage, the GVal must have a non-zero address
1279 // so the result is greater-than
1280 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1281 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1282 // If we are indexing from a null pointer, check to see if we have any
1283 // non-zero indices.
1284 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1285 if (!CE1->getOperand(i)->isNullValue())
1286 // Offsetting from null, must not be equal.
1287 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1288 // Only zero indexes from null, must still be zero.
1289 return ICmpInst::ICMP_EQ;
1291 // Otherwise, we can't really say if the first operand is null or not.
1292 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1293 if (isa<ConstantPointerNull>(CE1Op0)) {
1294 if (CPR2->hasExternalWeakLinkage())
1295 // Weak linkage GVals could be zero or not. We're comparing it to
1296 // a null pointer, so its less-or-equal
1297 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1299 // If its not weak linkage, the GVal must have a non-zero address
1300 // so the result is less-than
1301 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1302 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1304 // If this is a getelementptr of the same global, then it must be
1305 // different. Because the types must match, the getelementptr could
1306 // only have at most one index, and because we fold getelementptr's
1307 // with a single zero index, it must be nonzero.
1308 assert(CE1->getNumOperands() == 2 &&
1309 !CE1->getOperand(1)->isNullValue() &&
1310 "Suprising getelementptr!");
1311 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1313 // If they are different globals, we don't know what the value is,
1314 // but they can't be equal.
1315 return ICmpInst::ICMP_NE;
1319 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1320 Constant *CE2Op0 = CE2->getOperand(0);
1322 // There are MANY other foldings that we could perform here. They will
1323 // probably be added on demand, as they seem needed.
1324 switch (CE2->getOpcode()) {
1326 case Instruction::GetElementPtr:
1327 // By far the most common case to handle is when the base pointers are
1328 // obviously to the same or different globals.
1329 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1330 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1331 return ICmpInst::ICMP_NE;
1332 // Ok, we know that both getelementptr instructions are based on the
1333 // same global. From this, we can precisely determine the relative
1334 // ordering of the resultant pointers.
1337 // The logic below assumes that the result of the comparison
1338 // can be determined by finding the first index that differs.
1339 // This doesn't work if there is over-indexing in any
1340 // subsequent indices, so check for that case first.
1341 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1342 !CE2->isGEPWithNoNotionalOverIndexing())
1343 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1345 // Compare all of the operands the GEP's have in common.
1346 gep_type_iterator GTI = gep_type_begin(CE1);
1347 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1349 switch (IdxCompare(Context, CE1->getOperand(i),
1350 CE2->getOperand(i), GTI.getIndexedType())) {
1351 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1352 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1353 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1356 // Ok, we ran out of things they have in common. If any leftovers
1357 // are non-zero then we have a difference, otherwise we are equal.
1358 for (; i < CE1->getNumOperands(); ++i)
1359 if (!CE1->getOperand(i)->isNullValue()) {
1360 if (isa<ConstantInt>(CE1->getOperand(i)))
1361 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1363 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1366 for (; i < CE2->getNumOperands(); ++i)
1367 if (!CE2->getOperand(i)->isNullValue()) {
1368 if (isa<ConstantInt>(CE2->getOperand(i)))
1369 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1371 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1373 return ICmpInst::ICMP_EQ;
1382 return ICmpInst::BAD_ICMP_PREDICATE;
1385 Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1386 unsigned short pred,
1387 Constant *C1, Constant *C2) {
1388 const Type *ResultTy;
1389 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1390 ResultTy = VectorType::get(Type::getInt1Ty(Context), VT->getNumElements());
1392 ResultTy = Type::getInt1Ty(Context);
1394 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1395 if (pred == FCmpInst::FCMP_FALSE)
1396 return Constant::getNullValue(ResultTy);
1398 if (pred == FCmpInst::FCMP_TRUE)
1399 return Constant::getAllOnesValue(ResultTy);
1401 // Handle some degenerate cases first
1402 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1403 return UndefValue::get(ResultTy);
1405 // No compile-time operations on this type yet.
1406 if (C1->getType() == Type::getPPC_FP128Ty(Context))
1409 // icmp eq/ne(null,GV) -> false/true
1410 if (C1->isNullValue()) {
1411 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1412 // Don't try to evaluate aliases. External weak GV can be null.
1413 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1414 if (pred == ICmpInst::ICMP_EQ)
1415 return ConstantInt::getFalse(Context);
1416 else if (pred == ICmpInst::ICMP_NE)
1417 return ConstantInt::getTrue(Context);
1419 // icmp eq/ne(GV,null) -> false/true
1420 } else if (C2->isNullValue()) {
1421 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1422 // Don't try to evaluate aliases. External weak GV can be null.
1423 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1424 if (pred == ICmpInst::ICMP_EQ)
1425 return ConstantInt::getFalse(Context);
1426 else if (pred == ICmpInst::ICMP_NE)
1427 return ConstantInt::getTrue(Context);
1431 // If the comparison is a comparison between two i1's, simplify it.
1432 if (C1->getType() == Type::getInt1Ty(Context)) {
1434 case ICmpInst::ICMP_EQ:
1435 if (isa<ConstantInt>(C2))
1436 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1437 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1438 case ICmpInst::ICMP_NE:
1439 return ConstantExpr::getXor(C1, C2);
1445 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1446 APInt V1 = cast<ConstantInt>(C1)->getValue();
1447 APInt V2 = cast<ConstantInt>(C2)->getValue();
1449 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1450 case ICmpInst::ICMP_EQ:
1451 return ConstantInt::get(Type::getInt1Ty(Context), V1 == V2);
1452 case ICmpInst::ICMP_NE:
1453 return ConstantInt::get(Type::getInt1Ty(Context), V1 != V2);
1454 case ICmpInst::ICMP_SLT:
1455 return ConstantInt::get(Type::getInt1Ty(Context), V1.slt(V2));
1456 case ICmpInst::ICMP_SGT:
1457 return ConstantInt::get(Type::getInt1Ty(Context), V1.sgt(V2));
1458 case ICmpInst::ICMP_SLE:
1459 return ConstantInt::get(Type::getInt1Ty(Context), V1.sle(V2));
1460 case ICmpInst::ICMP_SGE:
1461 return ConstantInt::get(Type::getInt1Ty(Context), V1.sge(V2));
1462 case ICmpInst::ICMP_ULT:
1463 return ConstantInt::get(Type::getInt1Ty(Context), V1.ult(V2));
1464 case ICmpInst::ICMP_UGT:
1465 return ConstantInt::get(Type::getInt1Ty(Context), V1.ugt(V2));
1466 case ICmpInst::ICMP_ULE:
1467 return ConstantInt::get(Type::getInt1Ty(Context), V1.ule(V2));
1468 case ICmpInst::ICMP_UGE:
1469 return ConstantInt::get(Type::getInt1Ty(Context), V1.uge(V2));
1471 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1472 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1473 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1474 APFloat::cmpResult R = C1V.compare(C2V);
1476 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1477 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse(Context);
1478 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue(Context);
1479 case FCmpInst::FCMP_UNO:
1480 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered);
1481 case FCmpInst::FCMP_ORD:
1482 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpUnordered);
1483 case FCmpInst::FCMP_UEQ:
1484 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1485 R==APFloat::cmpEqual);
1486 case FCmpInst::FCMP_OEQ:
1487 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpEqual);
1488 case FCmpInst::FCMP_UNE:
1489 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpEqual);
1490 case FCmpInst::FCMP_ONE:
1491 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1492 R==APFloat::cmpGreaterThan);
1493 case FCmpInst::FCMP_ULT:
1494 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1495 R==APFloat::cmpLessThan);
1496 case FCmpInst::FCMP_OLT:
1497 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan);
1498 case FCmpInst::FCMP_UGT:
1499 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
1500 R==APFloat::cmpGreaterThan);
1501 case FCmpInst::FCMP_OGT:
1502 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan);
1503 case FCmpInst::FCMP_ULE:
1504 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpGreaterThan);
1505 case FCmpInst::FCMP_OLE:
1506 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
1507 R==APFloat::cmpEqual);
1508 case FCmpInst::FCMP_UGE:
1509 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpLessThan);
1510 case FCmpInst::FCMP_OGE:
1511 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan ||
1512 R==APFloat::cmpEqual);
1514 } else if (isa<VectorType>(C1->getType())) {
1515 SmallVector<Constant*, 16> C1Elts, C2Elts;
1516 C1->getVectorElements(Context, C1Elts);
1517 C2->getVectorElements(Context, C2Elts);
1519 // If we can constant fold the comparison of each element, constant fold
1520 // the whole vector comparison.
1521 SmallVector<Constant*, 4> ResElts;
1522 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1523 // Compare the elements, producing an i1 result or constant expr.
1525 ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1527 return ConstantVector::get(&ResElts[0], ResElts.size());
1530 if (C1->getType()->isFloatingPoint()) {
1531 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1532 switch (evaluateFCmpRelation(Context, C1, C2)) {
1533 default: llvm_unreachable("Unknown relation!");
1534 case FCmpInst::FCMP_UNO:
1535 case FCmpInst::FCMP_ORD:
1536 case FCmpInst::FCMP_UEQ:
1537 case FCmpInst::FCMP_UNE:
1538 case FCmpInst::FCMP_ULT:
1539 case FCmpInst::FCMP_UGT:
1540 case FCmpInst::FCMP_ULE:
1541 case FCmpInst::FCMP_UGE:
1542 case FCmpInst::FCMP_TRUE:
1543 case FCmpInst::FCMP_FALSE:
1544 case FCmpInst::BAD_FCMP_PREDICATE:
1545 break; // Couldn't determine anything about these constants.
1546 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1547 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1548 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1549 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1551 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1552 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1553 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1554 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1556 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1557 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1558 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1559 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1561 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1562 // We can only partially decide this relation.
1563 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1565 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1568 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1569 // We can only partially decide this relation.
1570 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1572 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1575 case ICmpInst::ICMP_NE: // We know that C1 != C2
1576 // We can only partially decide this relation.
1577 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1579 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1584 // If we evaluated the result, return it now.
1586 return ConstantInt::get(Type::getInt1Ty(Context), Result);
1589 // Evaluate the relation between the two constants, per the predicate.
1590 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1591 switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
1592 default: llvm_unreachable("Unknown relational!");
1593 case ICmpInst::BAD_ICMP_PREDICATE:
1594 break; // Couldn't determine anything about these constants.
1595 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1596 // If we know the constants are equal, we can decide the result of this
1597 // computation precisely.
1598 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1600 case ICmpInst::ICMP_ULT:
1602 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1604 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1608 case ICmpInst::ICMP_SLT:
1610 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1612 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1616 case ICmpInst::ICMP_UGT:
1618 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1620 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1624 case ICmpInst::ICMP_SGT:
1626 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1628 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1632 case ICmpInst::ICMP_ULE:
1633 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1634 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1636 case ICmpInst::ICMP_SLE:
1637 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1638 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1640 case ICmpInst::ICMP_UGE:
1641 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1642 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1644 case ICmpInst::ICMP_SGE:
1645 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1646 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1648 case ICmpInst::ICMP_NE:
1649 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1650 if (pred == ICmpInst::ICMP_NE) Result = 1;
1654 // If we evaluated the result, return it now.
1656 return ConstantInt::get(Type::getInt1Ty(Context), Result);
1658 // If the right hand side is a bitcast, try using its inverse to simplify
1659 // it by moving it to the left hand side.
1660 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1661 if (CE2->getOpcode() == Instruction::BitCast) {
1662 Constant *CE2Op0 = CE2->getOperand(0);
1663 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1664 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1668 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1669 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1670 // other way if possible.
1672 case ICmpInst::ICMP_EQ:
1673 case ICmpInst::ICMP_NE:
1674 // No change of predicate required.
1675 return ConstantFoldCompareInstruction(Context, pred, C2, C1);
1677 case ICmpInst::ICMP_ULT:
1678 case ICmpInst::ICMP_SLT:
1679 case ICmpInst::ICMP_UGT:
1680 case ICmpInst::ICMP_SGT:
1681 case ICmpInst::ICMP_ULE:
1682 case ICmpInst::ICMP_SLE:
1683 case ICmpInst::ICMP_UGE:
1684 case ICmpInst::ICMP_SGE:
1685 // Change the predicate as necessary to swap the operands.
1686 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1687 return ConstantFoldCompareInstruction(Context, pred, C2, C1);
1689 default: // These predicates cannot be flopped around.
1697 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1699 static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
1700 // No indices means nothing that could be out of bounds.
1701 if (NumIdx == 0) return true;
1703 // If the first index is zero, it's in bounds.
1704 if (Idxs[0]->isNullValue()) return true;
1706 // If the first index is one and all the rest are zero, it's in bounds,
1707 // by the one-past-the-end rule.
1708 if (!cast<ConstantInt>(Idxs[0])->isOne())
1710 for (unsigned i = 1, e = NumIdx; i != e; ++i)
1711 if (!Idxs[i]->isNullValue())
1716 Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context,
1719 Constant* const *Idxs,
1722 (NumIdx == 1 && Idxs[0]->isNullValue()))
1725 if (isa<UndefValue>(C)) {
1726 const PointerType *Ptr = cast<PointerType>(C->getType());
1727 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1729 (Value **)Idxs+NumIdx);
1730 assert(Ty != 0 && "Invalid indices for GEP!");
1731 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1734 Constant *Idx0 = Idxs[0];
1735 if (C->isNullValue()) {
1737 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1738 if (!Idxs[i]->isNullValue()) {
1743 const PointerType *Ptr = cast<PointerType>(C->getType());
1744 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1746 (Value**)Idxs+NumIdx);
1747 assert(Ty != 0 && "Invalid indices for GEP!");
1748 return ConstantPointerNull::get(
1749 PointerType::get(Ty,Ptr->getAddressSpace()));
1753 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1754 // Combine Indices - If the source pointer to this getelementptr instruction
1755 // is a getelementptr instruction, combine the indices of the two
1756 // getelementptr instructions into a single instruction.
1758 if (CE->getOpcode() == Instruction::GetElementPtr) {
1759 const Type *LastTy = 0;
1760 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1764 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1765 SmallVector<Value*, 16> NewIndices;
1766 NewIndices.reserve(NumIdx + CE->getNumOperands());
1767 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1768 NewIndices.push_back(CE->getOperand(i));
1770 // Add the last index of the source with the first index of the new GEP.
1771 // Make sure to handle the case when they are actually different types.
1772 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1773 // Otherwise it must be an array.
1774 if (!Idx0->isNullValue()) {
1775 const Type *IdxTy = Combined->getType();
1776 if (IdxTy != Idx0->getType()) {
1778 ConstantExpr::getSExtOrBitCast(Idx0, Type::getInt64Ty(Context));
1779 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1780 Type::getInt64Ty(Context));
1781 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1784 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1788 NewIndices.push_back(Combined);
1789 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1790 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
1791 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
1793 NewIndices.size()) :
1794 ConstantExpr::getGetElementPtr(CE->getOperand(0),
1800 // Implement folding of:
1801 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1803 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1805 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1806 if (const PointerType *SPT =
1807 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1808 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1809 if (const ArrayType *CAT =
1810 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1811 if (CAT->getElementType() == SAT->getElementType())
1813 ConstantExpr::getInBoundsGetElementPtr(
1814 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
1815 ConstantExpr::getGetElementPtr(
1816 (Constant*)CE->getOperand(0), Idxs, NumIdx);
1819 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1820 // Into: inttoptr (i64 0 to i8*)
1821 // This happens with pointers to member functions in C++.
1822 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1823 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1824 cast<PointerType>(CE->getType())->getElementType() == Type::getInt8Ty(Context)) {
1825 Constant *Base = CE->getOperand(0);
1826 Constant *Offset = Idxs[0];
1828 // Convert the smaller integer to the larger type.
1829 if (Offset->getType()->getPrimitiveSizeInBits() <
1830 Base->getType()->getPrimitiveSizeInBits())
1831 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1832 else if (Base->getType()->getPrimitiveSizeInBits() <
1833 Offset->getType()->getPrimitiveSizeInBits())
1834 Base = ConstantExpr::getZExt(Base, Offset->getType());
1836 Base = ConstantExpr::getAdd(Base, Offset);
1837 return ConstantExpr::getIntToPtr(Base, CE->getType());
1841 // Check to see if any array indices are not within the corresponding
1842 // notional array bounds. If so, try to determine if they can be factored
1843 // out into preceding dimensions.
1844 bool Unknown = false;
1845 SmallVector<Constant *, 8> NewIdxs;
1846 const Type *Ty = C->getType();
1847 const Type *Prev = 0;
1848 for (unsigned i = 0; i != NumIdx;
1849 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
1850 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
1851 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1852 if (ATy->getNumElements() <= INT64_MAX &&
1853 ATy->getNumElements() != 0 &&
1854 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
1855 if (isa<SequentialType>(Prev)) {
1856 // It's out of range, but we can factor it into the prior
1858 NewIdxs.resize(NumIdx);
1859 ConstantInt *Factor = ConstantInt::get(CI->getType(),
1860 ATy->getNumElements());
1861 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
1863 Constant *PrevIdx = Idxs[i-1];
1864 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
1866 // Before adding, extend both operands to i64 to avoid
1867 // overflow trouble.
1868 if (PrevIdx->getType() != Type::getInt64Ty(Context))
1869 PrevIdx = ConstantExpr::getSExt(PrevIdx,
1870 Type::getInt64Ty(Context));
1871 if (Div->getType() != Type::getInt64Ty(Context))
1872 Div = ConstantExpr::getSExt(Div,
1873 Type::getInt64Ty(Context));
1875 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
1877 // It's out of range, but the prior dimension is a struct
1878 // so we can't do anything about it.
1883 // We don't know if it's in range or not.
1888 // If we did any factoring, start over with the adjusted indices.
1889 if (!NewIdxs.empty()) {
1890 for (unsigned i = 0; i != NumIdx; ++i)
1891 if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
1893 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
1895 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
1898 // If all indices are known integers and normalized, we can do a simple
1899 // check for the "inbounds" property.
1900 if (!Unknown && !inBounds &&
1901 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
1902 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);