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 // template-based folder for simple primitive constants like ConstantInt, and
16 // the special case hackery that we use to symbolically evaluate expressions
17 // that use ConstantExprs.
19 //===----------------------------------------------------------------------===//
21 #include "ConstantFold.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MathExtras.h"
35 //===----------------------------------------------------------------------===//
36 // ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
39 /// BitCastConstantVector - Convert the specified ConstantVector node to the
40 /// specified vector type. At this point, we know that the elements of the
41 /// input vector constant are all simple integer or FP values.
42 static Constant *BitCastConstantVector(ConstantVector *CV,
43 const VectorType *DstTy) {
44 // If this cast changes element count then we can't handle it here:
45 // doing so requires endianness information. This should be handled by
46 // Analysis/ConstantFolding.cpp
47 unsigned NumElts = DstTy->getNumElements();
48 if (NumElts != CV->getNumOperands())
51 // Check to verify that all elements of the input are simple.
52 for (unsigned i = 0; i != NumElts; ++i) {
53 if (!isa<ConstantInt>(CV->getOperand(i)) &&
54 !isa<ConstantFP>(CV->getOperand(i)))
58 // Bitcast each element now.
59 std::vector<Constant*> Result;
60 const Type *DstEltTy = DstTy->getElementType();
61 for (unsigned i = 0; i != NumElts; ++i)
62 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63 return ConstantVector::get(Result);
66 /// This function determines which opcode to use to fold two constant cast
67 /// expressions together. It uses CastInst::isEliminableCastPair to determine
68 /// the opcode. Consequently its just a wrapper around that function.
69 /// @brief Determine if it is valid to fold a cast of a cast
72 unsigned opc, ///< opcode of the second cast constant expression
73 const ConstantExpr*Op, ///< the first cast constant expression
74 const Type *DstTy ///< desintation type of the first cast
76 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78 assert(CastInst::isCast(opc) && "Invalid cast opcode");
80 // The the types and opcodes for the two Cast constant expressions
81 const Type *SrcTy = Op->getOperand(0)->getType();
82 const Type *MidTy = Op->getType();
83 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84 Instruction::CastOps secondOp = Instruction::CastOps(opc);
86 // Let CastInst::isEliminableCastPair do the heavy lifting.
87 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
91 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92 const Type *SrcTy = V->getType();
94 return V; // no-op cast
96 // Check to see if we are casting a pointer to an aggregate to a pointer to
97 // the first element. If so, return the appropriate GEP instruction.
98 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
100 SmallVector<Value*, 8> IdxList;
101 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
102 const Type *ElTy = PTy->getElementType();
103 while (ElTy != DPTy->getElementType()) {
104 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
105 if (STy->getNumElements() == 0) break;
106 ElTy = STy->getElementType(0);
107 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
108 } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
109 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
110 ElTy = STy->getElementType();
111 IdxList.push_back(IdxList[0]);
117 if (ElTy == DPTy->getElementType())
118 return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
121 // Handle casts from one vector constant to another. We know that the src
122 // and dest type have the same size (otherwise its an illegal cast).
123 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
124 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
125 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
126 "Not cast between same sized vectors!");
127 // First, check for null. Undef is already handled.
128 if (isa<ConstantAggregateZero>(V))
129 return Constant::getNullValue(DestTy);
131 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
132 return BitCastConstantVector(CV, DestPTy);
136 // Finally, implement bitcast folding now. The code below doesn't handle
138 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
139 return ConstantPointerNull::get(cast<PointerType>(DestTy));
141 // Handle integral constant input.
142 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
143 if (DestTy->isInteger())
144 // Integral -> Integral. This is a no-op because the bit widths must
145 // be the same. Consequently, we just fold to V.
148 if (DestTy->isFloatingPoint()) {
149 assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) &&
151 return ConstantFP::get(DestTy, APFloat(CI->getValue()));
153 // Otherwise, can't fold this (vector?)
157 // Handle ConstantFP input.
158 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
160 if (DestTy == Type::Int32Ty) {
161 return ConstantInt::get(FP->getValueAPF().convertToAPInt());
163 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
164 return ConstantInt::get(FP->getValueAPF().convertToAPInt());
171 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
172 const Type *DestTy) {
173 if (isa<UndefValue>(V)) {
174 // zext(undef) = 0, because the top bits will be zero.
175 // sext(undef) = 0, because the top bits will all be the same.
176 // [us]itofp(undef) = 0, because the result value is bounded.
177 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
178 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
179 return Constant::getNullValue(DestTy);
180 return UndefValue::get(DestTy);
182 // No compile-time operations on this type yet.
183 if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
186 // If the cast operand is a constant expression, there's a few things we can
187 // do to try to simplify it.
188 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
190 // Try hard to fold cast of cast because they are often eliminable.
191 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
192 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
193 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
194 // If all of the indexes in the GEP are null values, there is no pointer
195 // adjustment going on. We might as well cast the source pointer.
196 bool isAllNull = true;
197 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
198 if (!CE->getOperand(i)->isNullValue()) {
203 // This is casting one pointer type to another, always BitCast
204 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
208 // We actually have to do a cast now. Perform the cast according to the
211 case Instruction::FPTrunc:
212 case Instruction::FPExt:
213 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
214 APFloat Val = FPC->getValueAPF();
215 Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
216 DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
217 DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
218 DestTy == Type::FP128Ty ? APFloat::IEEEquad :
220 APFloat::rmNearestTiesToEven);
221 return ConstantFP::get(DestTy, Val);
223 return 0; // Can't fold.
224 case Instruction::FPToUI:
225 case Instruction::FPToSI:
226 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
227 const APFloat &V = FPC->getValueAPF();
229 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
230 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
231 APFloat::rmTowardZero);
232 APInt Val(DestBitWidth, 2, x);
233 return ConstantInt::get(Val);
235 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
236 std::vector<Constant*> res;
237 const VectorType *DestVecTy = cast<VectorType>(DestTy);
238 const Type *DstEltTy = DestVecTy->getElementType();
239 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
240 res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
242 return ConstantVector::get(DestVecTy, res);
244 return 0; // Can't fold.
245 case Instruction::IntToPtr: //always treated as unsigned
246 if (V->isNullValue()) // Is it an integral null value?
247 return ConstantPointerNull::get(cast<PointerType>(DestTy));
248 return 0; // Other pointer types cannot be casted
249 case Instruction::PtrToInt: // always treated as unsigned
250 if (V->isNullValue()) // is it a null pointer value?
251 return ConstantInt::get(DestTy, 0);
252 return 0; // Other pointer types cannot be casted
253 case Instruction::UIToFP:
254 case Instruction::SIToFP:
255 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
256 APInt api = CI->getValue();
257 const uint64_t zero[] = {0, 0};
258 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
260 (void)apf.convertFromAPInt(api,
261 opc==Instruction::SIToFP,
262 APFloat::rmNearestTiesToEven);
263 return ConstantFP::get(DestTy, apf);
265 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
266 std::vector<Constant*> res;
267 const VectorType *DestVecTy = cast<VectorType>(DestTy);
268 const Type *DstEltTy = DestVecTy->getElementType();
269 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
270 res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
272 return ConstantVector::get(DestVecTy, res);
275 case Instruction::ZExt:
276 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
277 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
278 APInt Result(CI->getValue());
279 Result.zext(BitWidth);
280 return ConstantInt::get(Result);
283 case Instruction::SExt:
284 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
285 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
286 APInt Result(CI->getValue());
287 Result.sext(BitWidth);
288 return ConstantInt::get(Result);
291 case Instruction::Trunc:
292 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
293 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
294 APInt Result(CI->getValue());
295 Result.trunc(BitWidth);
296 return ConstantInt::get(Result);
299 case Instruction::BitCast:
300 return FoldBitCast(const_cast<Constant*>(V), DestTy);
302 assert(!"Invalid CE CastInst opcode");
306 assert(0 && "Failed to cast constant expression");
310 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
312 const Constant *V2) {
313 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
314 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
316 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
317 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
318 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
319 if (V1 == V2) return const_cast<Constant*>(V1);
323 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
324 const Constant *Idx) {
325 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
326 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
327 if (Val->isNullValue()) // ee(zero, x) -> zero
328 return Constant::getNullValue(
329 cast<VectorType>(Val->getType())->getElementType());
331 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
332 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
333 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
334 } else if (isa<UndefValue>(Idx)) {
335 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
336 return const_cast<Constant*>(CVal->getOperand(0));
342 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
344 const Constant *Idx) {
345 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
347 APInt idxVal = CIdx->getValue();
348 if (isa<UndefValue>(Val)) {
349 // Insertion of scalar constant into vector undef
350 // Optimize away insertion of undef
351 if (isa<UndefValue>(Elt))
352 return const_cast<Constant*>(Val);
353 // Otherwise break the aggregate undef into multiple undefs and do
356 cast<VectorType>(Val->getType())->getNumElements();
357 std::vector<Constant*> Ops;
359 for (unsigned i = 0; i < numOps; ++i) {
361 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
362 Ops.push_back(const_cast<Constant*>(Op));
364 return ConstantVector::get(Ops);
366 if (isa<ConstantAggregateZero>(Val)) {
367 // Insertion of scalar constant into vector aggregate zero
368 // Optimize away insertion of zero
369 if (Elt->isNullValue())
370 return const_cast<Constant*>(Val);
371 // Otherwise break the aggregate zero into multiple zeros and do
374 cast<VectorType>(Val->getType())->getNumElements();
375 std::vector<Constant*> Ops;
377 for (unsigned i = 0; i < numOps; ++i) {
379 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
380 Ops.push_back(const_cast<Constant*>(Op));
382 return ConstantVector::get(Ops);
384 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
385 // Insertion of scalar constant into vector constant
386 std::vector<Constant*> Ops;
387 Ops.reserve(CVal->getNumOperands());
388 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
390 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
391 Ops.push_back(const_cast<Constant*>(Op));
393 return ConstantVector::get(Ops);
398 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
399 /// return the specified element value. Otherwise return null.
400 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
401 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
402 return const_cast<Constant*>(CV->getOperand(EltNo));
404 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
405 if (isa<ConstantAggregateZero>(C))
406 return Constant::getNullValue(EltTy);
407 if (isa<UndefValue>(C))
408 return UndefValue::get(EltTy);
412 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
414 const Constant *Mask) {
415 // Undefined shuffle mask -> undefined value.
416 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
418 unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
419 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
421 // Loop over the shuffle mask, evaluating each element.
422 SmallVector<Constant*, 32> Result;
423 for (unsigned i = 0; i != NumElts; ++i) {
424 Constant *InElt = GetVectorElement(Mask, i);
425 if (InElt == 0) return 0;
427 if (isa<UndefValue>(InElt))
428 InElt = UndefValue::get(EltTy);
429 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
430 unsigned Elt = CI->getZExtValue();
431 if (Elt >= NumElts*2)
432 InElt = UndefValue::get(EltTy);
433 else if (Elt >= NumElts)
434 InElt = GetVectorElement(V2, Elt-NumElts);
436 InElt = GetVectorElement(V1, Elt);
437 if (InElt == 0) return 0;
442 Result.push_back(InElt);
445 return ConstantVector::get(&Result[0], Result.size());
448 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
449 /// function pointer to each element pair, producing a new ConstantVector
450 /// constant. Either or both of V1 and V2 may be NULL, meaning a
451 /// ConstantAggregateZero operand.
452 static Constant *EvalVectorOp(const ConstantVector *V1,
453 const ConstantVector *V2,
454 const VectorType *VTy,
455 Constant *(*FP)(Constant*, Constant*)) {
456 std::vector<Constant*> Res;
457 const Type *EltTy = VTy->getElementType();
458 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
459 const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
460 const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
461 Res.push_back(FP(const_cast<Constant*>(C1),
462 const_cast<Constant*>(C2)));
464 return ConstantVector::get(Res);
467 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
469 const Constant *C2) {
470 // No compile-time operations on this type yet.
471 if (C1->getType() == Type::PPC_FP128Ty)
474 // Handle UndefValue up front
475 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
477 case Instruction::Add:
478 case Instruction::Sub:
479 case Instruction::Xor:
480 return UndefValue::get(C1->getType());
481 case Instruction::Mul:
482 case Instruction::And:
483 return Constant::getNullValue(C1->getType());
484 case Instruction::UDiv:
485 case Instruction::SDiv:
486 case Instruction::FDiv:
487 case Instruction::URem:
488 case Instruction::SRem:
489 case Instruction::FRem:
490 if (!isa<UndefValue>(C2)) // undef / X -> 0
491 return Constant::getNullValue(C1->getType());
492 return const_cast<Constant*>(C2); // X / undef -> undef
493 case Instruction::Or: // X | undef -> -1
494 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
495 return ConstantVector::getAllOnesValue(PTy);
496 return ConstantInt::getAllOnesValue(C1->getType());
497 case Instruction::LShr:
498 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
499 return const_cast<Constant*>(C1); // undef lshr undef -> undef
500 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
502 case Instruction::AShr:
503 if (!isa<UndefValue>(C2))
504 return const_cast<Constant*>(C1); // undef ashr X --> undef
505 else if (isa<UndefValue>(C1))
506 return const_cast<Constant*>(C1); // undef ashr undef -> undef
508 return const_cast<Constant*>(C1); // X ashr undef --> X
509 case Instruction::Shl:
510 // undef << X -> 0 or X << undef -> 0
511 return Constant::getNullValue(C1->getType());
515 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
516 if (isa<ConstantExpr>(C2)) {
517 // There are many possible foldings we could do here. We should probably
518 // at least fold add of a pointer with an integer into the appropriate
519 // getelementptr. This will improve alias analysis a bit.
521 // Just implement a couple of simple identities.
523 case Instruction::Add:
524 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
526 case Instruction::Sub:
527 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
529 case Instruction::Mul:
530 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
531 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
532 if (CI->equalsInt(1))
533 return const_cast<Constant*>(C1); // X * 1 == X
535 case Instruction::UDiv:
536 case Instruction::SDiv:
537 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
538 if (CI->equalsInt(1))
539 return const_cast<Constant*>(C1); // X / 1 == X
541 case Instruction::URem:
542 case Instruction::SRem:
543 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
544 if (CI->equalsInt(1))
545 return Constant::getNullValue(CI->getType()); // X % 1 == 0
547 case Instruction::And:
548 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2)) {
549 if (CI->isZero()) return const_cast<Constant*>(C2); // X & 0 == 0
550 if (CI->isAllOnesValue())
551 return const_cast<Constant*>(C1); // X & -1 == X
553 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
554 if (CE1->getOpcode() == Instruction::ZExt) {
555 APInt PossiblySetBits
556 = cast<IntegerType>(CE1->getOperand(0)->getType())->getMask();
557 PossiblySetBits.zext(C1->getType()->getPrimitiveSizeInBits());
558 if ((PossiblySetBits & CI->getValue()) == PossiblySetBits)
559 return const_cast<Constant*>(C1);
562 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
563 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
565 // Functions are at least 4-byte aligned. If and'ing the address of a
566 // function with a constant < 4, fold it to zero.
567 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
568 if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
570 return Constant::getNullValue(CI->getType());
573 case Instruction::Or:
574 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
575 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
576 if (CI->isAllOnesValue())
577 return const_cast<Constant*>(C2); // X | -1 == -1
579 case Instruction::Xor:
580 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
582 case Instruction::AShr:
583 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
584 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
585 return ConstantExpr::getLShr(const_cast<Constant*>(C1),
586 const_cast<Constant*>(C2));
590 } else if (isa<ConstantExpr>(C2)) {
591 // If C2 is a constant expr and C1 isn't, flop them around and fold the
592 // other way if possible.
594 case Instruction::Add:
595 case Instruction::Mul:
596 case Instruction::And:
597 case Instruction::Or:
598 case Instruction::Xor:
599 // No change of opcode required.
600 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
602 case Instruction::Shl:
603 case Instruction::LShr:
604 case Instruction::AShr:
605 case Instruction::Sub:
606 case Instruction::SDiv:
607 case Instruction::UDiv:
608 case Instruction::FDiv:
609 case Instruction::URem:
610 case Instruction::SRem:
611 case Instruction::FRem:
612 default: // These instructions cannot be flopped around.
617 // At this point we know neither constant is an UndefValue nor a ConstantExpr
618 // so look at directly computing the value.
619 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
620 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
621 using namespace APIntOps;
622 APInt C1V = CI1->getValue();
623 APInt C2V = CI2->getValue();
627 case Instruction::Add:
628 return ConstantInt::get(C1V + C2V);
629 case Instruction::Sub:
630 return ConstantInt::get(C1V - C2V);
631 case Instruction::Mul:
632 return ConstantInt::get(C1V * C2V);
633 case Instruction::UDiv:
634 if (CI2->isNullValue())
635 return 0; // X / 0 -> can't fold
636 return ConstantInt::get(C1V.udiv(C2V));
637 case Instruction::SDiv:
638 if (CI2->isNullValue())
639 return 0; // X / 0 -> can't fold
640 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
641 return 0; // MIN_INT / -1 -> overflow
642 return ConstantInt::get(C1V.sdiv(C2V));
643 case Instruction::URem:
644 if (C2->isNullValue())
645 return 0; // X / 0 -> can't fold
646 return ConstantInt::get(C1V.urem(C2V));
647 case Instruction::SRem:
648 if (CI2->isNullValue())
649 return 0; // X % 0 -> can't fold
650 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
651 return 0; // MIN_INT % -1 -> overflow
652 return ConstantInt::get(C1V.srem(C2V));
653 case Instruction::And:
654 return ConstantInt::get(C1V & C2V);
655 case Instruction::Or:
656 return ConstantInt::get(C1V | C2V);
657 case Instruction::Xor:
658 return ConstantInt::get(C1V ^ C2V);
659 case Instruction::Shl:
660 if (uint32_t shiftAmt = C2V.getZExtValue()) {
661 if (shiftAmt < C1V.getBitWidth())
662 return ConstantInt::get(C1V.shl(shiftAmt));
664 return UndefValue::get(C1->getType()); // too big shift is undef
666 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
667 case Instruction::LShr:
668 if (uint32_t shiftAmt = C2V.getZExtValue()) {
669 if (shiftAmt < C1V.getBitWidth())
670 return ConstantInt::get(C1V.lshr(shiftAmt));
672 return UndefValue::get(C1->getType()); // too big shift is undef
674 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
675 case Instruction::AShr:
676 if (uint32_t shiftAmt = C2V.getZExtValue()) {
677 if (shiftAmt < C1V.getBitWidth())
678 return ConstantInt::get(C1V.ashr(shiftAmt));
680 return UndefValue::get(C1->getType()); // too big shift is undef
682 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
685 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
686 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
687 APFloat C1V = CFP1->getValueAPF();
688 APFloat C2V = CFP2->getValueAPF();
689 APFloat C3V = C1V; // copy for modification
690 bool isDouble = CFP1->getType()==Type::DoubleTy;
694 case Instruction::Add:
695 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
696 return ConstantFP::get(CFP1->getType(), C3V);
697 case Instruction::Sub:
698 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
699 return ConstantFP::get(CFP1->getType(), C3V);
700 case Instruction::Mul:
701 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
702 return ConstantFP::get(CFP1->getType(), C3V);
703 case Instruction::FDiv:
704 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
705 return ConstantFP::get(CFP1->getType(), C3V);
706 case Instruction::FRem:
708 // IEEE 754, Section 7.1, #5
709 return ConstantFP::get(CFP1->getType(), isDouble ?
710 APFloat(std::numeric_limits<double>::quiet_NaN()) :
711 APFloat(std::numeric_limits<float>::quiet_NaN()));
712 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
713 return ConstantFP::get(CFP1->getType(), C3V);
716 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
717 const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
718 const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
719 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
720 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
724 case Instruction::Add:
725 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
726 case Instruction::Sub:
727 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
728 case Instruction::Mul:
729 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
730 case Instruction::UDiv:
731 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
732 case Instruction::SDiv:
733 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
734 case Instruction::FDiv:
735 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
736 case Instruction::URem:
737 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
738 case Instruction::SRem:
739 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
740 case Instruction::FRem:
741 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
742 case Instruction::And:
743 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
744 case Instruction::Or:
745 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
746 case Instruction::Xor:
747 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
752 // We don't know how to fold this
756 /// isZeroSizedType - This type is zero sized if its an array or structure of
757 /// zero sized types. The only leaf zero sized type is an empty structure.
758 static bool isMaybeZeroSizedType(const Type *Ty) {
759 if (isa<OpaqueType>(Ty)) return true; // Can't say.
760 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
762 // If all of elements have zero size, this does too.
763 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
764 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
767 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
768 return isMaybeZeroSizedType(ATy->getElementType());
773 /// IdxCompare - Compare the two constants as though they were getelementptr
774 /// indices. This allows coersion of the types to be the same thing.
776 /// If the two constants are the "same" (after coersion), return 0. If the
777 /// first is less than the second, return -1, if the second is less than the
778 /// first, return 1. If the constants are not integral, return -2.
780 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
781 if (C1 == C2) return 0;
783 // Ok, we found a different index. If they are not ConstantInt, we can't do
784 // anything with them.
785 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
786 return -2; // don't know!
788 // Ok, we have two differing integer indices. Sign extend them to be the same
789 // type. Long is always big enough, so we use it.
790 if (C1->getType() != Type::Int64Ty)
791 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
793 if (C2->getType() != Type::Int64Ty)
794 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
796 if (C1 == C2) return 0; // They are equal
798 // If the type being indexed over is really just a zero sized type, there is
799 // no pointer difference being made here.
800 if (isMaybeZeroSizedType(ElTy))
803 // If they are really different, now that they are the same type, then we
804 // found a difference!
805 if (cast<ConstantInt>(C1)->getSExtValue() <
806 cast<ConstantInt>(C2)->getSExtValue())
812 /// evaluateFCmpRelation - This function determines if there is anything we can
813 /// decide about the two constants provided. This doesn't need to handle simple
814 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
815 /// If we can determine that the two constants have a particular relation to
816 /// each other, we should return the corresponding FCmpInst predicate,
817 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
818 /// ConstantFoldCompareInstruction.
820 /// To simplify this code we canonicalize the relation so that the first
821 /// operand is always the most "complex" of the two. We consider ConstantFP
822 /// to be the simplest, and ConstantExprs to be the most complex.
823 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
824 const Constant *V2) {
825 assert(V1->getType() == V2->getType() &&
826 "Cannot compare values of different types!");
828 // No compile-time operations on this type yet.
829 if (V1->getType() == Type::PPC_FP128Ty)
830 return FCmpInst::BAD_FCMP_PREDICATE;
832 // Handle degenerate case quickly
833 if (V1 == V2) return FCmpInst::FCMP_OEQ;
835 if (!isa<ConstantExpr>(V1)) {
836 if (!isa<ConstantExpr>(V2)) {
837 // We distilled thisUse the standard constant folder for a few cases
839 Constant *C1 = const_cast<Constant*>(V1);
840 Constant *C2 = const_cast<Constant*>(V2);
841 R = dyn_cast<ConstantInt>(
842 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
843 if (R && !R->isZero())
844 return FCmpInst::FCMP_OEQ;
845 R = dyn_cast<ConstantInt>(
846 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
847 if (R && !R->isZero())
848 return FCmpInst::FCMP_OLT;
849 R = dyn_cast<ConstantInt>(
850 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
851 if (R && !R->isZero())
852 return FCmpInst::FCMP_OGT;
854 // Nothing more we can do
855 return FCmpInst::BAD_FCMP_PREDICATE;
858 // If the first operand is simple and second is ConstantExpr, swap operands.
859 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
860 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
861 return FCmpInst::getSwappedPredicate(SwappedRelation);
863 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
864 // constantexpr or a simple constant.
865 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
866 switch (CE1->getOpcode()) {
867 case Instruction::FPTrunc:
868 case Instruction::FPExt:
869 case Instruction::UIToFP:
870 case Instruction::SIToFP:
871 // We might be able to do something with these but we don't right now.
877 // There are MANY other foldings that we could perform here. They will
878 // probably be added on demand, as they seem needed.
879 return FCmpInst::BAD_FCMP_PREDICATE;
882 /// evaluateICmpRelation - This function determines if there is anything we can
883 /// decide about the two constants provided. This doesn't need to handle simple
884 /// things like integer comparisons, but should instead handle ConstantExprs
885 /// and GlobalValues. If we can determine that the two constants have a
886 /// particular relation to each other, we should return the corresponding ICmp
887 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
889 /// To simplify this code we canonicalize the relation so that the first
890 /// operand is always the most "complex" of the two. We consider simple
891 /// constants (like ConstantInt) to be the simplest, followed by
892 /// GlobalValues, followed by ConstantExpr's (the most complex).
894 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
897 assert(V1->getType() == V2->getType() &&
898 "Cannot compare different types of values!");
899 if (V1 == V2) return ICmpInst::ICMP_EQ;
901 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
902 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
903 // We distilled this down to a simple case, use the standard constant
906 Constant *C1 = const_cast<Constant*>(V1);
907 Constant *C2 = const_cast<Constant*>(V2);
908 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
909 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
910 if (R && !R->isZero())
912 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
913 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
914 if (R && !R->isZero())
916 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
917 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
918 if (R && !R->isZero())
921 // If we couldn't figure it out, bail.
922 return ICmpInst::BAD_ICMP_PREDICATE;
925 // If the first operand is simple, swap operands.
926 ICmpInst::Predicate SwappedRelation =
927 evaluateICmpRelation(V2, V1, isSigned);
928 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
929 return ICmpInst::getSwappedPredicate(SwappedRelation);
931 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
932 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
933 ICmpInst::Predicate SwappedRelation =
934 evaluateICmpRelation(V2, V1, isSigned);
935 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
936 return ICmpInst::getSwappedPredicate(SwappedRelation);
938 return ICmpInst::BAD_ICMP_PREDICATE;
941 // Now we know that the RHS is a GlobalValue or simple constant,
942 // which (since the types must match) means that it's a ConstantPointerNull.
943 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
944 // Don't try to decide equality of aliases.
945 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
946 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
947 return ICmpInst::ICMP_NE;
949 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
950 // GlobalVals can never be null. Don't try to evaluate aliases.
951 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
952 return ICmpInst::ICMP_NE;
955 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
956 // constantexpr, a CPR, or a simple constant.
957 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
958 const Constant *CE1Op0 = CE1->getOperand(0);
960 switch (CE1->getOpcode()) {
961 case Instruction::Trunc:
962 case Instruction::FPTrunc:
963 case Instruction::FPExt:
964 case Instruction::FPToUI:
965 case Instruction::FPToSI:
966 break; // We can't evaluate floating point casts or truncations.
968 case Instruction::UIToFP:
969 case Instruction::SIToFP:
970 case Instruction::BitCast:
971 case Instruction::ZExt:
972 case Instruction::SExt:
973 // If the cast is not actually changing bits, and the second operand is a
974 // null pointer, do the comparison with the pre-casted value.
975 if (V2->isNullValue() &&
976 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
977 bool sgnd = isSigned;
978 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
979 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
980 return evaluateICmpRelation(CE1Op0,
981 Constant::getNullValue(CE1Op0->getType()),
985 // If the dest type is a pointer type, and the RHS is a constantexpr cast
986 // from the same type as the src of the LHS, evaluate the inputs. This is
987 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
988 // which happens a lot in compilers with tagged integers.
989 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
990 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
991 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
992 CE1->getOperand(0)->getType()->isInteger()) {
993 bool sgnd = isSigned;
994 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
995 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
996 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1001 case Instruction::GetElementPtr:
1002 // Ok, since this is a getelementptr, we know that the constant has a
1003 // pointer type. Check the various cases.
1004 if (isa<ConstantPointerNull>(V2)) {
1005 // If we are comparing a GEP to a null pointer, check to see if the base
1006 // of the GEP equals the null pointer.
1007 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1008 if (GV->hasExternalWeakLinkage())
1009 // Weak linkage GVals could be zero or not. We're comparing that
1010 // to null pointer so its greater-or-equal
1011 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1013 // If its not weak linkage, the GVal must have a non-zero address
1014 // so the result is greater-than
1015 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1016 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1017 // If we are indexing from a null pointer, check to see if we have any
1018 // non-zero indices.
1019 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1020 if (!CE1->getOperand(i)->isNullValue())
1021 // Offsetting from null, must not be equal.
1022 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1023 // Only zero indexes from null, must still be zero.
1024 return ICmpInst::ICMP_EQ;
1026 // Otherwise, we can't really say if the first operand is null or not.
1027 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1028 if (isa<ConstantPointerNull>(CE1Op0)) {
1029 if (CPR2->hasExternalWeakLinkage())
1030 // Weak linkage GVals could be zero or not. We're comparing it to
1031 // a null pointer, so its less-or-equal
1032 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1034 // If its not weak linkage, the GVal must have a non-zero address
1035 // so the result is less-than
1036 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1037 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1039 // If this is a getelementptr of the same global, then it must be
1040 // different. Because the types must match, the getelementptr could
1041 // only have at most one index, and because we fold getelementptr's
1042 // with a single zero index, it must be nonzero.
1043 assert(CE1->getNumOperands() == 2 &&
1044 !CE1->getOperand(1)->isNullValue() &&
1045 "Suprising getelementptr!");
1046 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1048 // If they are different globals, we don't know what the value is,
1049 // but they can't be equal.
1050 return ICmpInst::ICMP_NE;
1054 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1055 const Constant *CE2Op0 = CE2->getOperand(0);
1057 // There are MANY other foldings that we could perform here. They will
1058 // probably be added on demand, as they seem needed.
1059 switch (CE2->getOpcode()) {
1061 case Instruction::GetElementPtr:
1062 // By far the most common case to handle is when the base pointers are
1063 // obviously to the same or different globals.
1064 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1065 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1066 return ICmpInst::ICMP_NE;
1067 // Ok, we know that both getelementptr instructions are based on the
1068 // same global. From this, we can precisely determine the relative
1069 // ordering of the resultant pointers.
1072 // Compare all of the operands the GEP's have in common.
1073 gep_type_iterator GTI = gep_type_begin(CE1);
1074 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1076 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1077 GTI.getIndexedType())) {
1078 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1079 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1080 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1083 // Ok, we ran out of things they have in common. If any leftovers
1084 // are non-zero then we have a difference, otherwise we are equal.
1085 for (; i < CE1->getNumOperands(); ++i)
1086 if (!CE1->getOperand(i)->isNullValue()) {
1087 if (isa<ConstantInt>(CE1->getOperand(i)))
1088 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1090 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1093 for (; i < CE2->getNumOperands(); ++i)
1094 if (!CE2->getOperand(i)->isNullValue()) {
1095 if (isa<ConstantInt>(CE2->getOperand(i)))
1096 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1098 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1100 return ICmpInst::ICMP_EQ;
1109 return ICmpInst::BAD_ICMP_PREDICATE;
1112 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1114 const Constant *C2) {
1116 // Handle some degenerate cases first
1117 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1118 return UndefValue::get(Type::Int1Ty);
1120 // No compile-time operations on this type yet.
1121 if (C1->getType() == Type::PPC_FP128Ty)
1124 // icmp eq/ne(null,GV) -> false/true
1125 if (C1->isNullValue()) {
1126 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1127 // Don't try to evaluate aliases. External weak GV can be null.
1128 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1129 if (pred == ICmpInst::ICMP_EQ)
1130 return ConstantInt::getFalse();
1131 else if (pred == ICmpInst::ICMP_NE)
1132 return ConstantInt::getTrue();
1134 // icmp eq/ne(GV,null) -> false/true
1135 } else if (C2->isNullValue()) {
1136 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1137 // Don't try to evaluate aliases. External weak GV can be null.
1138 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1139 if (pred == ICmpInst::ICMP_EQ)
1140 return ConstantInt::getFalse();
1141 else if (pred == ICmpInst::ICMP_NE)
1142 return ConstantInt::getTrue();
1146 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1147 APInt V1 = cast<ConstantInt>(C1)->getValue();
1148 APInt V2 = cast<ConstantInt>(C2)->getValue();
1150 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1151 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1152 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1153 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1154 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1155 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1156 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1157 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1158 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1159 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1160 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1162 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1163 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1164 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1165 APFloat::cmpResult R = C1V.compare(C2V);
1167 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1168 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1169 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
1170 case FCmpInst::FCMP_UNO:
1171 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1172 case FCmpInst::FCMP_ORD:
1173 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1174 case FCmpInst::FCMP_UEQ:
1175 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1176 R==APFloat::cmpEqual);
1177 case FCmpInst::FCMP_OEQ:
1178 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1179 case FCmpInst::FCMP_UNE:
1180 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1181 case FCmpInst::FCMP_ONE:
1182 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1183 R==APFloat::cmpGreaterThan);
1184 case FCmpInst::FCMP_ULT:
1185 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1186 R==APFloat::cmpLessThan);
1187 case FCmpInst::FCMP_OLT:
1188 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1189 case FCmpInst::FCMP_UGT:
1190 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1191 R==APFloat::cmpGreaterThan);
1192 case FCmpInst::FCMP_OGT:
1193 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1194 case FCmpInst::FCMP_ULE:
1195 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1196 case FCmpInst::FCMP_OLE:
1197 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1198 R==APFloat::cmpEqual);
1199 case FCmpInst::FCMP_UGE:
1200 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1201 case FCmpInst::FCMP_OGE:
1202 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1203 R==APFloat::cmpEqual);
1205 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1206 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1207 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1208 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1209 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1210 const_cast<Constant*>(CP1->getOperand(i)),
1211 const_cast<Constant*>(CP2->getOperand(i)));
1212 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1215 // Otherwise, could not decide from any element pairs.
1217 } else if (pred == ICmpInst::ICMP_EQ) {
1218 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1219 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1220 const_cast<Constant*>(CP1->getOperand(i)),
1221 const_cast<Constant*>(CP2->getOperand(i)));
1222 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1225 // Otherwise, could not decide from any element pairs.
1231 if (C1->getType()->isFloatingPoint()) {
1232 switch (evaluateFCmpRelation(C1, C2)) {
1233 default: assert(0 && "Unknown relation!");
1234 case FCmpInst::FCMP_UNO:
1235 case FCmpInst::FCMP_ORD:
1236 case FCmpInst::FCMP_UEQ:
1237 case FCmpInst::FCMP_UNE:
1238 case FCmpInst::FCMP_ULT:
1239 case FCmpInst::FCMP_UGT:
1240 case FCmpInst::FCMP_ULE:
1241 case FCmpInst::FCMP_UGE:
1242 case FCmpInst::FCMP_TRUE:
1243 case FCmpInst::FCMP_FALSE:
1244 case FCmpInst::BAD_FCMP_PREDICATE:
1245 break; // Couldn't determine anything about these constants.
1246 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1247 return ConstantInt::get(Type::Int1Ty,
1248 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1249 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1250 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1251 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1252 return ConstantInt::get(Type::Int1Ty,
1253 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1254 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1255 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1256 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1257 return ConstantInt::get(Type::Int1Ty,
1258 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1259 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1260 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1261 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1262 // We can only partially decide this relation.
1263 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1264 return ConstantInt::getFalse();
1265 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1266 return ConstantInt::getTrue();
1268 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1269 // We can only partially decide this relation.
1270 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1271 return ConstantInt::getFalse();
1272 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1273 return ConstantInt::getTrue();
1275 case ICmpInst::ICMP_NE: // We know that C1 != C2
1276 // We can only partially decide this relation.
1277 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1278 return ConstantInt::getFalse();
1279 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1280 return ConstantInt::getTrue();
1284 // Evaluate the relation between the two constants, per the predicate.
1285 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1286 default: assert(0 && "Unknown relational!");
1287 case ICmpInst::BAD_ICMP_PREDICATE:
1288 break; // Couldn't determine anything about these constants.
1289 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1290 // If we know the constants are equal, we can decide the result of this
1291 // computation precisely.
1292 return ConstantInt::get(Type::Int1Ty,
1293 pred == ICmpInst::ICMP_EQ ||
1294 pred == ICmpInst::ICMP_ULE ||
1295 pred == ICmpInst::ICMP_SLE ||
1296 pred == ICmpInst::ICMP_UGE ||
1297 pred == ICmpInst::ICMP_SGE);
1298 case ICmpInst::ICMP_ULT:
1299 // If we know that C1 < C2, we can decide the result of this computation
1301 return ConstantInt::get(Type::Int1Ty,
1302 pred == ICmpInst::ICMP_ULT ||
1303 pred == ICmpInst::ICMP_NE ||
1304 pred == ICmpInst::ICMP_ULE);
1305 case ICmpInst::ICMP_SLT:
1306 // If we know that C1 < C2, we can decide the result of this computation
1308 return ConstantInt::get(Type::Int1Ty,
1309 pred == ICmpInst::ICMP_SLT ||
1310 pred == ICmpInst::ICMP_NE ||
1311 pred == ICmpInst::ICMP_SLE);
1312 case ICmpInst::ICMP_UGT:
1313 // If we know that C1 > C2, we can decide the result of this computation
1315 return ConstantInt::get(Type::Int1Ty,
1316 pred == ICmpInst::ICMP_UGT ||
1317 pred == ICmpInst::ICMP_NE ||
1318 pred == ICmpInst::ICMP_UGE);
1319 case ICmpInst::ICMP_SGT:
1320 // If we know that C1 > C2, we can decide the result of this computation
1322 return ConstantInt::get(Type::Int1Ty,
1323 pred == ICmpInst::ICMP_SGT ||
1324 pred == ICmpInst::ICMP_NE ||
1325 pred == ICmpInst::ICMP_SGE);
1326 case ICmpInst::ICMP_ULE:
1327 // If we know that C1 <= C2, we can only partially decide this relation.
1328 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1329 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1331 case ICmpInst::ICMP_SLE:
1332 // If we know that C1 <= C2, we can only partially decide this relation.
1333 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1334 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1337 case ICmpInst::ICMP_UGE:
1338 // If we know that C1 >= C2, we can only partially decide this relation.
1339 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1340 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1342 case ICmpInst::ICMP_SGE:
1343 // If we know that C1 >= C2, we can only partially decide this relation.
1344 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1345 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1348 case ICmpInst::ICMP_NE:
1349 // If we know that C1 != C2, we can only partially decide this relation.
1350 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1351 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1355 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1356 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1357 // other way if possible.
1359 case ICmpInst::ICMP_EQ:
1360 case ICmpInst::ICMP_NE:
1361 // No change of predicate required.
1362 return ConstantFoldCompareInstruction(pred, C2, C1);
1364 case ICmpInst::ICMP_ULT:
1365 case ICmpInst::ICMP_SLT:
1366 case ICmpInst::ICMP_UGT:
1367 case ICmpInst::ICMP_SGT:
1368 case ICmpInst::ICMP_ULE:
1369 case ICmpInst::ICMP_SLE:
1370 case ICmpInst::ICMP_UGE:
1371 case ICmpInst::ICMP_SGE:
1372 // Change the predicate as necessary to swap the operands.
1373 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1374 return ConstantFoldCompareInstruction(pred, C2, C1);
1376 default: // These predicates cannot be flopped around.
1384 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1385 Constant* const *Idxs,
1388 (NumIdx == 1 && Idxs[0]->isNullValue()))
1389 return const_cast<Constant*>(C);
1391 if (isa<UndefValue>(C)) {
1392 const PointerType *Ptr = cast<PointerType>(C->getType());
1393 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1395 (Value **)Idxs+NumIdx,
1397 assert(Ty != 0 && "Invalid indices for GEP!");
1398 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1401 Constant *Idx0 = Idxs[0];
1402 if (C->isNullValue()) {
1404 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1405 if (!Idxs[i]->isNullValue()) {
1410 const PointerType *Ptr = cast<PointerType>(C->getType());
1411 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1413 (Value**)Idxs+NumIdx,
1415 assert(Ty != 0 && "Invalid indices for GEP!");
1417 ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1422 // Combine Indices - If the source pointer to this getelementptr instruction
1423 // is a getelementptr instruction, combine the indices of the two
1424 // getelementptr instructions into a single instruction.
1426 if (CE->getOpcode() == Instruction::GetElementPtr) {
1427 const Type *LastTy = 0;
1428 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1432 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1433 SmallVector<Value*, 16> NewIndices;
1434 NewIndices.reserve(NumIdx + CE->getNumOperands());
1435 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1436 NewIndices.push_back(CE->getOperand(i));
1438 // Add the last index of the source with the first index of the new GEP.
1439 // Make sure to handle the case when they are actually different types.
1440 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1441 // Otherwise it must be an array.
1442 if (!Idx0->isNullValue()) {
1443 const Type *IdxTy = Combined->getType();
1444 if (IdxTy != Idx0->getType()) {
1445 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1446 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1448 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1451 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1455 NewIndices.push_back(Combined);
1456 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1457 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1462 // Implement folding of:
1463 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1465 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1467 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1468 if (const PointerType *SPT =
1469 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1470 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1471 if (const ArrayType *CAT =
1472 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1473 if (CAT->getElementType() == SAT->getElementType())
1474 return ConstantExpr::getGetElementPtr(
1475 (Constant*)CE->getOperand(0), Idxs, NumIdx);
1478 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1479 // Into: inttoptr (i64 0 to i8*)
1480 // This happens with pointers to member functions in C++.
1481 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1482 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1483 cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1484 Constant *Base = CE->getOperand(0);
1485 Constant *Offset = Idxs[0];
1487 // Convert the smaller integer to the larger type.
1488 if (Offset->getType()->getPrimitiveSizeInBits() <
1489 Base->getType()->getPrimitiveSizeInBits())
1490 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1491 else if (Base->getType()->getPrimitiveSizeInBits() <
1492 Offset->getType()->getPrimitiveSizeInBits())
1493 Base = ConstantExpr::getZExt(Base, Base->getType());
1495 Base = ConstantExpr::getAdd(Base, Offset);
1496 return ConstantExpr::getIntToPtr(Base, CE->getType());