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/Operator.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 vector Constant 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(Constant *CV, VectorType *DstTy) {
46 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47 if (CV->isNullValue()) return Constant::getNullValue(DstTy);
49 // If this cast changes element count then we can't handle it here:
50 // doing so requires endianness information. This should be handled by
51 // Analysis/ConstantFolding.cpp
52 unsigned NumElts = DstTy->getNumElements();
53 if (NumElts != CV->getType()->getVectorNumElements())
56 Type *DstEltTy = DstTy->getElementType();
58 // Check to verify that all elements of the input are simple.
59 SmallVector<Constant*, 16> Result;
60 for (unsigned i = 0; i != NumElts; ++i) {
61 Constant *C = CV->getAggregateElement(i);
63 C = ConstantExpr::getBitCast(C, DstEltTy);
64 if (isa<ConstantExpr>(C)) return 0;
68 return ConstantVector::get(Result);
71 /// This function determines which opcode to use to fold two constant cast
72 /// expressions together. It uses CastInst::isEliminableCastPair to determine
73 /// the opcode. Consequently its just a wrapper around that function.
74 /// @brief Determine if it is valid to fold a cast of a cast
77 unsigned opc, ///< opcode of the second cast constant expression
78 ConstantExpr *Op, ///< the first cast constant expression
79 Type *DstTy ///< desintation type of the first cast
81 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
82 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
83 assert(CastInst::isCast(opc) && "Invalid cast opcode");
85 // The the types and opcodes for the two Cast constant expressions
86 Type *SrcTy = Op->getOperand(0)->getType();
87 Type *MidTy = Op->getType();
88 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
89 Instruction::CastOps secondOp = Instruction::CastOps(opc);
91 // Let CastInst::isEliminableCastPair do the heavy lifting.
92 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
93 Type::getInt64Ty(DstTy->getContext()));
96 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
97 Type *SrcTy = V->getType();
99 return V; // no-op cast
101 // Check to see if we are casting a pointer to an aggregate to a pointer to
102 // the first element. If so, return the appropriate GEP instruction.
103 if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
104 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
105 if (PTy->getAddressSpace() == DPTy->getAddressSpace()
106 && DPTy->getElementType()->isSized()) {
107 SmallVector<Value*, 8> IdxList;
109 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
110 IdxList.push_back(Zero);
111 Type *ElTy = PTy->getElementType();
112 while (ElTy != DPTy->getElementType()) {
113 if (StructType *STy = dyn_cast<StructType>(ElTy)) {
114 if (STy->getNumElements() == 0) break;
115 ElTy = STy->getElementType(0);
116 IdxList.push_back(Zero);
117 } else if (SequentialType *STy =
118 dyn_cast<SequentialType>(ElTy)) {
119 if (ElTy->isPointerTy()) break; // Can't index into pointers!
120 ElTy = STy->getElementType();
121 IdxList.push_back(Zero);
127 if (ElTy == DPTy->getElementType())
128 // This GEP is inbounds because all indices are zero.
129 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
132 // Handle casts from one vector constant to another. We know that the src
133 // and dest type have the same size (otherwise its an illegal cast).
134 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
135 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
136 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
137 "Not cast between same sized vectors!");
139 // First, check for null. Undef is already handled.
140 if (isa<ConstantAggregateZero>(V))
141 return Constant::getNullValue(DestTy);
143 // Handle ConstantVector and ConstantAggregateVector.
144 return BitCastConstantVector(V, DestPTy);
147 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
148 // This allows for other simplifications (although some of them
149 // can only be handled by Analysis/ConstantFolding.cpp).
150 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
151 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
154 // Finally, implement bitcast folding now. The code below doesn't handle
156 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
157 return ConstantPointerNull::get(cast<PointerType>(DestTy));
159 // Handle integral constant input.
160 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
161 if (DestTy->isIntegerTy())
162 // Integral -> Integral. This is a no-op because the bit widths must
163 // be the same. Consequently, we just fold to V.
166 if (DestTy->isFloatingPointTy())
167 return ConstantFP::get(DestTy->getContext(),
168 APFloat(CI->getValue(),
169 !DestTy->isPPC_FP128Ty()));
171 // Otherwise, can't fold this (vector?)
175 // Handle ConstantFP input: FP -> Integral.
176 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
177 return ConstantInt::get(FP->getContext(),
178 FP->getValueAPF().bitcastToAPInt());
184 /// ExtractConstantBytes - V is an integer constant which only has a subset of
185 /// its bytes used. The bytes used are indicated by ByteStart (which is the
186 /// first byte used, counting from the least significant byte) and ByteSize,
187 /// which is the number of bytes used.
189 /// This function analyzes the specified constant to see if the specified byte
190 /// range can be returned as a simplified constant. If so, the constant is
191 /// returned, otherwise null is returned.
193 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
195 assert(C->getType()->isIntegerTy() &&
196 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
197 "Non-byte sized integer input");
198 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
199 assert(ByteSize && "Must be accessing some piece");
200 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
201 assert(ByteSize != CSize && "Should not extract everything");
203 // Constant Integers are simple.
204 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
205 APInt V = CI->getValue();
207 V = V.lshr(ByteStart*8);
208 V = V.trunc(ByteSize*8);
209 return ConstantInt::get(CI->getContext(), V);
212 // In the input is a constant expr, we might be able to recursively simplify.
213 // If not, we definitely can't do anything.
214 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
215 if (CE == 0) return 0;
217 switch (CE->getOpcode()) {
219 case Instruction::Or: {
220 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
225 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
226 if (RHSC->isAllOnesValue())
229 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
232 return ConstantExpr::getOr(LHS, RHS);
234 case Instruction::And: {
235 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
240 if (RHS->isNullValue())
243 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
246 return ConstantExpr::getAnd(LHS, RHS);
248 case Instruction::LShr: {
249 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
252 unsigned ShAmt = Amt->getZExtValue();
253 // Cannot analyze non-byte shifts.
254 if ((ShAmt & 7) != 0)
258 // If the extract is known to be all zeros, return zero.
259 if (ByteStart >= CSize-ShAmt)
260 return Constant::getNullValue(IntegerType::get(CE->getContext(),
262 // If the extract is known to be fully in the input, extract it.
263 if (ByteStart+ByteSize+ShAmt <= CSize)
264 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
266 // TODO: Handle the 'partially zero' case.
270 case Instruction::Shl: {
271 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
274 unsigned ShAmt = Amt->getZExtValue();
275 // Cannot analyze non-byte shifts.
276 if ((ShAmt & 7) != 0)
280 // If the extract is known to be all zeros, return zero.
281 if (ByteStart+ByteSize <= ShAmt)
282 return Constant::getNullValue(IntegerType::get(CE->getContext(),
284 // If the extract is known to be fully in the input, extract it.
285 if (ByteStart >= ShAmt)
286 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
288 // TODO: Handle the 'partially zero' case.
292 case Instruction::ZExt: {
293 unsigned SrcBitSize =
294 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
296 // If extracting something that is completely zero, return 0.
297 if (ByteStart*8 >= SrcBitSize)
298 return Constant::getNullValue(IntegerType::get(CE->getContext(),
301 // If exactly extracting the input, return it.
302 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
303 return CE->getOperand(0);
305 // If extracting something completely in the input, if if the input is a
306 // multiple of 8 bits, recurse.
307 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
308 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
310 // Otherwise, if extracting a subset of the input, which is not multiple of
311 // 8 bits, do a shift and trunc to get the bits.
312 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
313 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
314 Constant *Res = CE->getOperand(0);
316 Res = ConstantExpr::getLShr(Res,
317 ConstantInt::get(Res->getType(), ByteStart*8));
318 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
322 // TODO: Handle the 'partially zero' case.
328 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
329 /// on Ty, with any known factors factored out. If Folded is false,
330 /// return null if no factoring was possible, to avoid endlessly
331 /// bouncing an unfoldable expression back into the top-level folder.
333 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
335 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
336 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
337 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
338 return ConstantExpr::getNUWMul(E, N);
341 if (StructType *STy = dyn_cast<StructType>(Ty))
342 if (!STy->isPacked()) {
343 unsigned NumElems = STy->getNumElements();
344 // An empty struct has size zero.
346 return ConstantExpr::getNullValue(DestTy);
347 // Check for a struct with all members having the same size.
348 Constant *MemberSize =
349 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
351 for (unsigned i = 1; i != NumElems; ++i)
353 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
358 Constant *N = ConstantInt::get(DestTy, NumElems);
359 return ConstantExpr::getNUWMul(MemberSize, N);
363 // Pointer size doesn't depend on the pointee type, so canonicalize them
364 // to an arbitrary pointee.
365 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
366 if (!PTy->getElementType()->isIntegerTy(1))
368 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
369 PTy->getAddressSpace()),
372 // If there's no interesting folding happening, bail so that we don't create
373 // a constant that looks like it needs folding but really doesn't.
377 // Base case: Get a regular sizeof expression.
378 Constant *C = ConstantExpr::getSizeOf(Ty);
379 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
385 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
386 /// on Ty, with any known factors factored out. If Folded is false,
387 /// return null if no factoring was possible, to avoid endlessly
388 /// bouncing an unfoldable expression back into the top-level folder.
390 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
392 // The alignment of an array is equal to the alignment of the
393 // array element. Note that this is not always true for vectors.
394 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
395 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
396 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
403 if (StructType *STy = dyn_cast<StructType>(Ty)) {
404 // Packed structs always have an alignment of 1.
406 return ConstantInt::get(DestTy, 1);
408 // Otherwise, struct alignment is the maximum alignment of any member.
409 // Without target data, we can't compare much, but we can check to see
410 // if all the members have the same alignment.
411 unsigned NumElems = STy->getNumElements();
412 // An empty struct has minimal alignment.
414 return ConstantInt::get(DestTy, 1);
415 // Check for a struct with all members having the same alignment.
416 Constant *MemberAlign =
417 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
419 for (unsigned i = 1; i != NumElems; ++i)
420 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
428 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
429 // to an arbitrary pointee.
430 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
431 if (!PTy->getElementType()->isIntegerTy(1))
433 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
435 PTy->getAddressSpace()),
438 // If there's no interesting folding happening, bail so that we don't create
439 // a constant that looks like it needs folding but really doesn't.
443 // Base case: Get a regular alignof expression.
444 Constant *C = ConstantExpr::getAlignOf(Ty);
445 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
451 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
452 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
453 /// return null if no factoring was possible, to avoid endlessly
454 /// bouncing an unfoldable expression back into the top-level folder.
456 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
459 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
460 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
463 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
464 return ConstantExpr::getNUWMul(E, N);
467 if (StructType *STy = dyn_cast<StructType>(Ty))
468 if (!STy->isPacked()) {
469 unsigned NumElems = STy->getNumElements();
470 // An empty struct has no members.
473 // Check for a struct with all members having the same size.
474 Constant *MemberSize =
475 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
477 for (unsigned i = 1; i != NumElems; ++i)
479 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
484 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
489 return ConstantExpr::getNUWMul(MemberSize, N);
493 // If there's no interesting folding happening, bail so that we don't create
494 // a constant that looks like it needs folding but really doesn't.
498 // Base case: Get a regular offsetof expression.
499 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
500 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
506 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
508 if (isa<UndefValue>(V)) {
509 // zext(undef) = 0, because the top bits will be zero.
510 // sext(undef) = 0, because the top bits will all be the same.
511 // [us]itofp(undef) = 0, because the result value is bounded.
512 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
513 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
514 return Constant::getNullValue(DestTy);
515 return UndefValue::get(DestTy);
518 // No compile-time operations on this type yet.
519 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
522 if (V->isNullValue() && !DestTy->isX86_MMXTy())
523 return Constant::getNullValue(DestTy);
525 // If the cast operand is a constant expression, there's a few things we can
526 // do to try to simplify it.
527 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
529 // Try hard to fold cast of cast because they are often eliminable.
530 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
531 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
532 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
533 // If all of the indexes in the GEP are null values, there is no pointer
534 // adjustment going on. We might as well cast the source pointer.
535 bool isAllNull = true;
536 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
537 if (!CE->getOperand(i)->isNullValue()) {
542 // This is casting one pointer type to another, always BitCast
543 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
547 // If the cast operand is a constant vector, perform the cast by
548 // operating on each element. In the cast of bitcasts, the element
549 // count may be mismatched; don't attempt to handle that here.
550 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
551 if (DestTy->isVectorTy() &&
552 cast<VectorType>(DestTy)->getNumElements() ==
553 CV->getType()->getNumElements()) {
554 std::vector<Constant*> res;
555 VectorType *DestVecTy = cast<VectorType>(DestTy);
556 Type *DstEltTy = DestVecTy->getElementType();
557 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
558 res.push_back(ConstantExpr::getCast(opc,
559 CV->getOperand(i), DstEltTy));
560 return ConstantVector::get(res);
563 // We actually have to do a cast now. Perform the cast according to the
567 llvm_unreachable("Failed to cast constant expression");
568 case Instruction::FPTrunc:
569 case Instruction::FPExt:
570 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
572 APFloat Val = FPC->getValueAPF();
573 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
574 DestTy->isFloatTy() ? APFloat::IEEEsingle :
575 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
576 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
577 DestTy->isFP128Ty() ? APFloat::IEEEquad :
579 APFloat::rmNearestTiesToEven, &ignored);
580 return ConstantFP::get(V->getContext(), Val);
582 return 0; // Can't fold.
583 case Instruction::FPToUI:
584 case Instruction::FPToSI:
585 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
586 const APFloat &V = FPC->getValueAPF();
589 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
590 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
591 APFloat::rmTowardZero, &ignored);
592 APInt Val(DestBitWidth, x);
593 return ConstantInt::get(FPC->getContext(), Val);
595 return 0; // Can't fold.
596 case Instruction::IntToPtr: //always treated as unsigned
597 if (V->isNullValue()) // Is it an integral null value?
598 return ConstantPointerNull::get(cast<PointerType>(DestTy));
599 return 0; // Other pointer types cannot be casted
600 case Instruction::PtrToInt: // always treated as unsigned
601 // Is it a null pointer value?
602 if (V->isNullValue())
603 return ConstantInt::get(DestTy, 0);
604 // If this is a sizeof-like expression, pull out multiplications by
605 // known factors to expose them to subsequent folding. If it's an
606 // alignof-like expression, factor out known factors.
607 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
608 if (CE->getOpcode() == Instruction::GetElementPtr &&
609 CE->getOperand(0)->isNullValue()) {
611 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
612 if (CE->getNumOperands() == 2) {
613 // Handle a sizeof-like expression.
614 Constant *Idx = CE->getOperand(1);
615 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
616 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
617 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
620 return ConstantExpr::getMul(C, Idx);
622 } else if (CE->getNumOperands() == 3 &&
623 CE->getOperand(1)->isNullValue()) {
624 // Handle an alignof-like expression.
625 if (StructType *STy = dyn_cast<StructType>(Ty))
626 if (!STy->isPacked()) {
627 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
629 STy->getNumElements() == 2 &&
630 STy->getElementType(0)->isIntegerTy(1)) {
631 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
634 // Handle an offsetof-like expression.
635 if (Ty->isStructTy() || Ty->isArrayTy()) {
636 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
642 // Other pointer types cannot be casted
644 case Instruction::UIToFP:
645 case Instruction::SIToFP:
646 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
647 APInt api = CI->getValue();
648 APFloat apf(APInt::getNullValue(DestTy->getPrimitiveSizeInBits()), true);
649 (void)apf.convertFromAPInt(api,
650 opc==Instruction::SIToFP,
651 APFloat::rmNearestTiesToEven);
652 return ConstantFP::get(V->getContext(), apf);
655 case Instruction::ZExt:
656 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
657 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
658 return ConstantInt::get(V->getContext(),
659 CI->getValue().zext(BitWidth));
662 case Instruction::SExt:
663 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
664 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
665 return ConstantInt::get(V->getContext(),
666 CI->getValue().sext(BitWidth));
669 case Instruction::Trunc: {
670 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
671 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
672 return ConstantInt::get(V->getContext(),
673 CI->getValue().trunc(DestBitWidth));
676 // The input must be a constantexpr. See if we can simplify this based on
677 // the bytes we are demanding. Only do this if the source and dest are an
678 // even multiple of a byte.
679 if ((DestBitWidth & 7) == 0 &&
680 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
681 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
686 case Instruction::BitCast:
687 return FoldBitCast(V, DestTy);
691 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
692 Constant *V1, Constant *V2) {
693 // Check for i1 and vector true/false conditions.
694 if (Cond->isNullValue()) return V2;
695 if (Cond->isAllOnesValue()) return V1;
697 // FIXME: CDV Condition.
698 // If the condition is a vector constant, fold the result elementwise.
699 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
700 SmallVector<Constant*, 16> Result;
701 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
702 ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
703 if (Cond == 0) break;
705 Constant *Res = (Cond->getZExtValue() ? V2 : V1)->getAggregateElement(i);
707 Result.push_back(Res);
710 // If we were able to build the vector, return it.
711 if (Result.size() == V1->getType()->getVectorNumElements())
712 return ConstantVector::get(Result);
716 if (isa<UndefValue>(Cond)) {
717 if (isa<UndefValue>(V1)) return V1;
720 if (isa<UndefValue>(V1)) return V2;
721 if (isa<UndefValue>(V2)) return V1;
722 if (V1 == V2) return V1;
724 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
725 if (TrueVal->getOpcode() == Instruction::Select)
726 if (TrueVal->getOperand(0) == Cond)
727 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
729 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
730 if (FalseVal->getOpcode() == Instruction::Select)
731 if (FalseVal->getOperand(0) == Cond)
732 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
738 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
740 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
741 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
742 if (Val->isNullValue()) // ee(zero, x) -> zero
743 return Constant::getNullValue(
744 cast<VectorType>(Val->getType())->getElementType());
746 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
747 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
748 uint64_t Index = CIdx->getZExtValue();
749 if (Index >= CVal->getNumOperands())
750 // ee({w,x,y,z}, wrong_value) -> undef
751 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
752 return CVal->getOperand(CIdx->getZExtValue());
753 } else if (isa<UndefValue>(Idx)) {
754 // ee({w,x,y,z}, undef) -> undef
755 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
761 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
764 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
766 const APInt &IdxVal = CIdx->getValue();
768 SmallVector<Constant*, 16> Result;
769 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
771 Result.push_back(Elt);
775 if (Constant *C = Val->getAggregateElement(i))
781 return ConstantVector::get(Result);
784 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
787 // Undefined shuffle mask -> undefined value.
788 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
790 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
791 unsigned SrcNumElts = V1->getType()->getVectorNumElements();
792 Type *EltTy = V1->getType()->getVectorElementType();
794 // Loop over the shuffle mask, evaluating each element.
795 SmallVector<Constant*, 32> Result;
796 for (unsigned i = 0; i != MaskNumElts; ++i) {
797 int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
799 Result.push_back(UndefValue::get(EltTy));
803 if (unsigned(Elt) >= SrcNumElts*2)
804 InElt = UndefValue::get(EltTy);
805 else if (unsigned(Elt) >= SrcNumElts)
806 InElt = V2->getAggregateElement(Elt - SrcNumElts);
808 InElt = V1->getAggregateElement(Elt);
809 if (InElt == 0) return 0;
810 Result.push_back(InElt);
813 return ConstantVector::get(Result);
816 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
817 ArrayRef<unsigned> Idxs) {
818 // Base case: no indices, so return the entire value.
822 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
823 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
828 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
830 ArrayRef<unsigned> Idxs) {
831 // Base case: no indices, so replace the entire value.
836 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
837 NumElts = ST->getNumElements();
838 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
839 NumElts = AT->getNumElements();
841 NumElts = AT->getVectorNumElements();
843 SmallVector<Constant*, 32> Result;
844 for (unsigned i = 0; i != NumElts; ++i) {
845 Constant *C = Agg->getAggregateElement(i);
846 if (C == 0) return 0;
849 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
854 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
855 return ConstantStruct::get(ST, Result);
856 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
857 return ConstantArray::get(AT, Result);
858 return ConstantVector::get(Result);
862 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
863 Constant *C1, Constant *C2) {
864 // No compile-time operations on this type yet.
865 if (C1->getType()->isPPC_FP128Ty())
868 // Handle UndefValue up front.
869 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
871 case Instruction::Xor:
872 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
873 // Handle undef ^ undef -> 0 special case. This is a common
875 return Constant::getNullValue(C1->getType());
877 case Instruction::Add:
878 case Instruction::Sub:
879 return UndefValue::get(C1->getType());
880 case Instruction::And:
881 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
883 return Constant::getNullValue(C1->getType()); // undef & X -> 0
884 case Instruction::Mul: {
886 // X * undef -> undef if X is odd or undef
887 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
888 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
889 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
890 return UndefValue::get(C1->getType());
892 // X * undef -> 0 otherwise
893 return Constant::getNullValue(C1->getType());
895 case Instruction::UDiv:
896 case Instruction::SDiv:
897 // undef / 1 -> undef
898 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
899 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
903 case Instruction::URem:
904 case Instruction::SRem:
905 if (!isa<UndefValue>(C2)) // undef / X -> 0
906 return Constant::getNullValue(C1->getType());
907 return C2; // X / undef -> undef
908 case Instruction::Or: // X | undef -> -1
909 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
911 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
912 case Instruction::LShr:
913 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
914 return C1; // undef lshr undef -> undef
915 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
917 case Instruction::AShr:
918 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
919 return Constant::getAllOnesValue(C1->getType());
920 else if (isa<UndefValue>(C1))
921 return C1; // undef ashr undef -> undef
923 return C1; // X ashr undef --> X
924 case Instruction::Shl:
925 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
926 return C1; // undef shl undef -> undef
927 // undef << X -> 0 or X << undef -> 0
928 return Constant::getNullValue(C1->getType());
932 // Handle simplifications when the RHS is a constant int.
933 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
935 case Instruction::Add:
936 if (CI2->equalsInt(0)) return C1; // X + 0 == X
938 case Instruction::Sub:
939 if (CI2->equalsInt(0)) return C1; // X - 0 == X
941 case Instruction::Mul:
942 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
943 if (CI2->equalsInt(1))
944 return C1; // X * 1 == X
946 case Instruction::UDiv:
947 case Instruction::SDiv:
948 if (CI2->equalsInt(1))
949 return C1; // X / 1 == X
950 if (CI2->equalsInt(0))
951 return UndefValue::get(CI2->getType()); // X / 0 == undef
953 case Instruction::URem:
954 case Instruction::SRem:
955 if (CI2->equalsInt(1))
956 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
957 if (CI2->equalsInt(0))
958 return UndefValue::get(CI2->getType()); // X % 0 == undef
960 case Instruction::And:
961 if (CI2->isZero()) return C2; // X & 0 == 0
962 if (CI2->isAllOnesValue())
963 return C1; // X & -1 == X
965 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
966 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
967 if (CE1->getOpcode() == Instruction::ZExt) {
968 unsigned DstWidth = CI2->getType()->getBitWidth();
970 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
971 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
972 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
976 // If and'ing the address of a global with a constant, fold it.
977 if (CE1->getOpcode() == Instruction::PtrToInt &&
978 isa<GlobalValue>(CE1->getOperand(0))) {
979 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
981 // Functions are at least 4-byte aligned.
982 unsigned GVAlign = GV->getAlignment();
983 if (isa<Function>(GV))
984 GVAlign = std::max(GVAlign, 4U);
987 unsigned DstWidth = CI2->getType()->getBitWidth();
988 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
989 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
991 // If checking bits we know are clear, return zero.
992 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
993 return Constant::getNullValue(CI2->getType());
998 case Instruction::Or:
999 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1000 if (CI2->isAllOnesValue())
1001 return C2; // X | -1 == -1
1003 case Instruction::Xor:
1004 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1006 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1007 switch (CE1->getOpcode()) {
1009 case Instruction::ICmp:
1010 case Instruction::FCmp:
1011 // cmp pred ^ true -> cmp !pred
1012 assert(CI2->equalsInt(1));
1013 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1014 pred = CmpInst::getInversePredicate(pred);
1015 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1016 CE1->getOperand(1));
1020 case Instruction::AShr:
1021 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1022 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1023 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1024 return ConstantExpr::getLShr(C1, C2);
1027 } else if (isa<ConstantInt>(C1)) {
1028 // If C1 is a ConstantInt and C2 is not, swap the operands.
1029 if (Instruction::isCommutative(Opcode))
1030 return ConstantExpr::get(Opcode, C2, C1);
1033 // At this point we know neither constant is an UndefValue.
1034 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1035 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1036 const APInt &C1V = CI1->getValue();
1037 const APInt &C2V = CI2->getValue();
1041 case Instruction::Add:
1042 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1043 case Instruction::Sub:
1044 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1045 case Instruction::Mul:
1046 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1047 case Instruction::UDiv:
1048 assert(!CI2->isNullValue() && "Div by zero handled above");
1049 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1050 case Instruction::SDiv:
1051 assert(!CI2->isNullValue() && "Div by zero handled above");
1052 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1053 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1054 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1055 case Instruction::URem:
1056 assert(!CI2->isNullValue() && "Div by zero handled above");
1057 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1058 case Instruction::SRem:
1059 assert(!CI2->isNullValue() && "Div by zero handled above");
1060 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1061 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1062 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1063 case Instruction::And:
1064 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1065 case Instruction::Or:
1066 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1067 case Instruction::Xor:
1068 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1069 case Instruction::Shl: {
1070 uint32_t shiftAmt = C2V.getZExtValue();
1071 if (shiftAmt < C1V.getBitWidth())
1072 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1074 return UndefValue::get(C1->getType()); // too big shift is undef
1076 case Instruction::LShr: {
1077 uint32_t shiftAmt = C2V.getZExtValue();
1078 if (shiftAmt < C1V.getBitWidth())
1079 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1081 return UndefValue::get(C1->getType()); // too big shift is undef
1083 case Instruction::AShr: {
1084 uint32_t shiftAmt = C2V.getZExtValue();
1085 if (shiftAmt < C1V.getBitWidth())
1086 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1088 return UndefValue::get(C1->getType()); // too big shift is undef
1094 case Instruction::SDiv:
1095 case Instruction::UDiv:
1096 case Instruction::URem:
1097 case Instruction::SRem:
1098 case Instruction::LShr:
1099 case Instruction::AShr:
1100 case Instruction::Shl:
1101 if (CI1->equalsInt(0)) return C1;
1106 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1107 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1108 APFloat C1V = CFP1->getValueAPF();
1109 APFloat C2V = CFP2->getValueAPF();
1110 APFloat C3V = C1V; // copy for modification
1114 case Instruction::FAdd:
1115 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1116 return ConstantFP::get(C1->getContext(), C3V);
1117 case Instruction::FSub:
1118 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1119 return ConstantFP::get(C1->getContext(), C3V);
1120 case Instruction::FMul:
1121 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1122 return ConstantFP::get(C1->getContext(), C3V);
1123 case Instruction::FDiv:
1124 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1125 return ConstantFP::get(C1->getContext(), C3V);
1126 case Instruction::FRem:
1127 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1128 return ConstantFP::get(C1->getContext(), C3V);
1131 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1132 // Perform elementwise folding.
1133 SmallVector<Constant*, 16> Result;
1134 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1135 Constant *LHS = C1->getAggregateElement(i);
1136 Constant *RHS = C2->getAggregateElement(i);
1137 if (LHS == 0 || RHS == 0) break;
1139 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1142 if (Result.size() == VTy->getNumElements())
1143 return ConstantVector::get(Result);
1146 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1147 // There are many possible foldings we could do here. We should probably
1148 // at least fold add of a pointer with an integer into the appropriate
1149 // getelementptr. This will improve alias analysis a bit.
1151 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1153 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1154 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1155 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1156 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1158 } else if (isa<ConstantExpr>(C2)) {
1159 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1160 // other way if possible.
1161 if (Instruction::isCommutative(Opcode))
1162 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1165 // i1 can be simplified in many cases.
1166 if (C1->getType()->isIntegerTy(1)) {
1168 case Instruction::Add:
1169 case Instruction::Sub:
1170 return ConstantExpr::getXor(C1, C2);
1171 case Instruction::Mul:
1172 return ConstantExpr::getAnd(C1, C2);
1173 case Instruction::Shl:
1174 case Instruction::LShr:
1175 case Instruction::AShr:
1176 // We can assume that C2 == 0. If it were one the result would be
1177 // undefined because the shift value is as large as the bitwidth.
1179 case Instruction::SDiv:
1180 case Instruction::UDiv:
1181 // We can assume that C2 == 1. If it were zero the result would be
1182 // undefined through division by zero.
1184 case Instruction::URem:
1185 case Instruction::SRem:
1186 // We can assume that C2 == 1. If it were zero the result would be
1187 // undefined through division by zero.
1188 return ConstantInt::getFalse(C1->getContext());
1194 // We don't know how to fold this.
1198 /// isZeroSizedType - This type is zero sized if its an array or structure of
1199 /// zero sized types. The only leaf zero sized type is an empty structure.
1200 static bool isMaybeZeroSizedType(Type *Ty) {
1201 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1202 if (STy->isOpaque()) return true; // Can't say.
1204 // If all of elements have zero size, this does too.
1205 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1206 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1209 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1210 return isMaybeZeroSizedType(ATy->getElementType());
1215 /// IdxCompare - Compare the two constants as though they were getelementptr
1216 /// indices. This allows coersion of the types to be the same thing.
1218 /// If the two constants are the "same" (after coersion), return 0. If the
1219 /// first is less than the second, return -1, if the second is less than the
1220 /// first, return 1. If the constants are not integral, return -2.
1222 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1223 if (C1 == C2) return 0;
1225 // Ok, we found a different index. If they are not ConstantInt, we can't do
1226 // anything with them.
1227 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1228 return -2; // don't know!
1230 // Ok, we have two differing integer indices. Sign extend them to be the same
1231 // type. Long is always big enough, so we use it.
1232 if (!C1->getType()->isIntegerTy(64))
1233 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1235 if (!C2->getType()->isIntegerTy(64))
1236 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1238 if (C1 == C2) return 0; // They are equal
1240 // If the type being indexed over is really just a zero sized type, there is
1241 // no pointer difference being made here.
1242 if (isMaybeZeroSizedType(ElTy))
1243 return -2; // dunno.
1245 // If they are really different, now that they are the same type, then we
1246 // found a difference!
1247 if (cast<ConstantInt>(C1)->getSExtValue() <
1248 cast<ConstantInt>(C2)->getSExtValue())
1254 /// evaluateFCmpRelation - This function determines if there is anything we can
1255 /// decide about the two constants provided. This doesn't need to handle simple
1256 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1257 /// If we can determine that the two constants have a particular relation to
1258 /// each other, we should return the corresponding FCmpInst predicate,
1259 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1260 /// ConstantFoldCompareInstruction.
1262 /// To simplify this code we canonicalize the relation so that the first
1263 /// operand is always the most "complex" of the two. We consider ConstantFP
1264 /// to be the simplest, and ConstantExprs to be the most complex.
1265 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1266 assert(V1->getType() == V2->getType() &&
1267 "Cannot compare values of different types!");
1269 // No compile-time operations on this type yet.
1270 if (V1->getType()->isPPC_FP128Ty())
1271 return FCmpInst::BAD_FCMP_PREDICATE;
1273 // Handle degenerate case quickly
1274 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1276 if (!isa<ConstantExpr>(V1)) {
1277 if (!isa<ConstantExpr>(V2)) {
1278 // We distilled thisUse the standard constant folder for a few cases
1280 R = dyn_cast<ConstantInt>(
1281 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1282 if (R && !R->isZero())
1283 return FCmpInst::FCMP_OEQ;
1284 R = dyn_cast<ConstantInt>(
1285 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1286 if (R && !R->isZero())
1287 return FCmpInst::FCMP_OLT;
1288 R = dyn_cast<ConstantInt>(
1289 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1290 if (R && !R->isZero())
1291 return FCmpInst::FCMP_OGT;
1293 // Nothing more we can do
1294 return FCmpInst::BAD_FCMP_PREDICATE;
1297 // If the first operand is simple and second is ConstantExpr, swap operands.
1298 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1299 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1300 return FCmpInst::getSwappedPredicate(SwappedRelation);
1302 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1303 // constantexpr or a simple constant.
1304 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1305 switch (CE1->getOpcode()) {
1306 case Instruction::FPTrunc:
1307 case Instruction::FPExt:
1308 case Instruction::UIToFP:
1309 case Instruction::SIToFP:
1310 // We might be able to do something with these but we don't right now.
1316 // There are MANY other foldings that we could perform here. They will
1317 // probably be added on demand, as they seem needed.
1318 return FCmpInst::BAD_FCMP_PREDICATE;
1321 /// evaluateICmpRelation - This function determines if there is anything we can
1322 /// decide about the two constants provided. This doesn't need to handle simple
1323 /// things like integer comparisons, but should instead handle ConstantExprs
1324 /// and GlobalValues. If we can determine that the two constants have a
1325 /// particular relation to each other, we should return the corresponding ICmp
1326 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1328 /// To simplify this code we canonicalize the relation so that the first
1329 /// operand is always the most "complex" of the two. We consider simple
1330 /// constants (like ConstantInt) to be the simplest, followed by
1331 /// GlobalValues, followed by ConstantExpr's (the most complex).
1333 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1335 assert(V1->getType() == V2->getType() &&
1336 "Cannot compare different types of values!");
1337 if (V1 == V2) return ICmpInst::ICMP_EQ;
1339 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1340 !isa<BlockAddress>(V1)) {
1341 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1342 !isa<BlockAddress>(V2)) {
1343 // We distilled this down to a simple case, use the standard constant
1346 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1347 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1348 if (R && !R->isZero())
1350 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1351 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1352 if (R && !R->isZero())
1354 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1355 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1356 if (R && !R->isZero())
1359 // If we couldn't figure it out, bail.
1360 return ICmpInst::BAD_ICMP_PREDICATE;
1363 // If the first operand is simple, swap operands.
1364 ICmpInst::Predicate SwappedRelation =
1365 evaluateICmpRelation(V2, V1, isSigned);
1366 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1367 return ICmpInst::getSwappedPredicate(SwappedRelation);
1369 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1370 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1371 ICmpInst::Predicate SwappedRelation =
1372 evaluateICmpRelation(V2, V1, isSigned);
1373 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1374 return ICmpInst::getSwappedPredicate(SwappedRelation);
1375 return ICmpInst::BAD_ICMP_PREDICATE;
1378 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1379 // constant (which, since the types must match, means that it's a
1380 // ConstantPointerNull).
1381 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1382 // Don't try to decide equality of aliases.
1383 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1384 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1385 return ICmpInst::ICMP_NE;
1386 } else if (isa<BlockAddress>(V2)) {
1387 return ICmpInst::ICMP_NE; // Globals never equal labels.
1389 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1390 // GlobalVals can never be null unless they have external weak linkage.
1391 // We don't try to evaluate aliases here.
1392 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1393 return ICmpInst::ICMP_NE;
1395 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1396 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1397 ICmpInst::Predicate SwappedRelation =
1398 evaluateICmpRelation(V2, V1, isSigned);
1399 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1400 return ICmpInst::getSwappedPredicate(SwappedRelation);
1401 return ICmpInst::BAD_ICMP_PREDICATE;
1404 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1405 // constant (which, since the types must match, means that it is a
1406 // ConstantPointerNull).
1407 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1408 // Block address in another function can't equal this one, but block
1409 // addresses in the current function might be the same if blocks are
1411 if (BA2->getFunction() != BA->getFunction())
1412 return ICmpInst::ICMP_NE;
1414 // Block addresses aren't null, don't equal the address of globals.
1415 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1416 "Canonicalization guarantee!");
1417 return ICmpInst::ICMP_NE;
1420 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1421 // constantexpr, a global, block address, or a simple constant.
1422 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1423 Constant *CE1Op0 = CE1->getOperand(0);
1425 switch (CE1->getOpcode()) {
1426 case Instruction::Trunc:
1427 case Instruction::FPTrunc:
1428 case Instruction::FPExt:
1429 case Instruction::FPToUI:
1430 case Instruction::FPToSI:
1431 break; // We can't evaluate floating point casts or truncations.
1433 case Instruction::UIToFP:
1434 case Instruction::SIToFP:
1435 case Instruction::BitCast:
1436 case Instruction::ZExt:
1437 case Instruction::SExt:
1438 // If the cast is not actually changing bits, and the second operand is a
1439 // null pointer, do the comparison with the pre-casted value.
1440 if (V2->isNullValue() &&
1441 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1442 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1443 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1444 return evaluateICmpRelation(CE1Op0,
1445 Constant::getNullValue(CE1Op0->getType()),
1450 case Instruction::GetElementPtr:
1451 // Ok, since this is a getelementptr, we know that the constant has a
1452 // pointer type. Check the various cases.
1453 if (isa<ConstantPointerNull>(V2)) {
1454 // If we are comparing a GEP to a null pointer, check to see if the base
1455 // of the GEP equals the null pointer.
1456 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1457 if (GV->hasExternalWeakLinkage())
1458 // Weak linkage GVals could be zero or not. We're comparing that
1459 // to null pointer so its greater-or-equal
1460 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1462 // If its not weak linkage, the GVal must have a non-zero address
1463 // so the result is greater-than
1464 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1465 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1466 // If we are indexing from a null pointer, check to see if we have any
1467 // non-zero indices.
1468 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1469 if (!CE1->getOperand(i)->isNullValue())
1470 // Offsetting from null, must not be equal.
1471 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1472 // Only zero indexes from null, must still be zero.
1473 return ICmpInst::ICMP_EQ;
1475 // Otherwise, we can't really say if the first operand is null or not.
1476 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1477 if (isa<ConstantPointerNull>(CE1Op0)) {
1478 if (GV2->hasExternalWeakLinkage())
1479 // Weak linkage GVals could be zero or not. We're comparing it to
1480 // a null pointer, so its less-or-equal
1481 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1483 // If its not weak linkage, the GVal must have a non-zero address
1484 // so the result is less-than
1485 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1486 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1488 // If this is a getelementptr of the same global, then it must be
1489 // different. Because the types must match, the getelementptr could
1490 // only have at most one index, and because we fold getelementptr's
1491 // with a single zero index, it must be nonzero.
1492 assert(CE1->getNumOperands() == 2 &&
1493 !CE1->getOperand(1)->isNullValue() &&
1494 "Surprising getelementptr!");
1495 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1497 // If they are different globals, we don't know what the value is,
1498 // but they can't be equal.
1499 return ICmpInst::ICMP_NE;
1503 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1504 Constant *CE2Op0 = CE2->getOperand(0);
1506 // There are MANY other foldings that we could perform here. They will
1507 // probably be added on demand, as they seem needed.
1508 switch (CE2->getOpcode()) {
1510 case Instruction::GetElementPtr:
1511 // By far the most common case to handle is when the base pointers are
1512 // obviously to the same or different globals.
1513 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1514 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1515 return ICmpInst::ICMP_NE;
1516 // Ok, we know that both getelementptr instructions are based on the
1517 // same global. From this, we can precisely determine the relative
1518 // ordering of the resultant pointers.
1521 // The logic below assumes that the result of the comparison
1522 // can be determined by finding the first index that differs.
1523 // This doesn't work if there is over-indexing in any
1524 // subsequent indices, so check for that case first.
1525 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1526 !CE2->isGEPWithNoNotionalOverIndexing())
1527 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1529 // Compare all of the operands the GEP's have in common.
1530 gep_type_iterator GTI = gep_type_begin(CE1);
1531 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1533 switch (IdxCompare(CE1->getOperand(i),
1534 CE2->getOperand(i), GTI.getIndexedType())) {
1535 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1536 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1537 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1540 // Ok, we ran out of things they have in common. If any leftovers
1541 // are non-zero then we have a difference, otherwise we are equal.
1542 for (; i < CE1->getNumOperands(); ++i)
1543 if (!CE1->getOperand(i)->isNullValue()) {
1544 if (isa<ConstantInt>(CE1->getOperand(i)))
1545 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1547 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1550 for (; i < CE2->getNumOperands(); ++i)
1551 if (!CE2->getOperand(i)->isNullValue()) {
1552 if (isa<ConstantInt>(CE2->getOperand(i)))
1553 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1555 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1557 return ICmpInst::ICMP_EQ;
1566 return ICmpInst::BAD_ICMP_PREDICATE;
1569 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1570 Constant *C1, Constant *C2) {
1572 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1573 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1574 VT->getNumElements());
1576 ResultTy = Type::getInt1Ty(C1->getContext());
1578 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1579 if (pred == FCmpInst::FCMP_FALSE)
1580 return Constant::getNullValue(ResultTy);
1582 if (pred == FCmpInst::FCMP_TRUE)
1583 return Constant::getAllOnesValue(ResultTy);
1585 // Handle some degenerate cases first
1586 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1587 // For EQ and NE, we can always pick a value for the undef to make the
1588 // predicate pass or fail, so we can return undef.
1589 // Also, if both operands are undef, we can return undef.
1590 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1591 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1592 return UndefValue::get(ResultTy);
1593 // Otherwise, pick the same value as the non-undef operand, and fold
1594 // it to true or false.
1595 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1598 // No compile-time operations on this type yet.
1599 if (C1->getType()->isPPC_FP128Ty())
1602 // icmp eq/ne(null,GV) -> false/true
1603 if (C1->isNullValue()) {
1604 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1605 // Don't try to evaluate aliases. External weak GV can be null.
1606 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1607 if (pred == ICmpInst::ICMP_EQ)
1608 return ConstantInt::getFalse(C1->getContext());
1609 else if (pred == ICmpInst::ICMP_NE)
1610 return ConstantInt::getTrue(C1->getContext());
1612 // icmp eq/ne(GV,null) -> false/true
1613 } else if (C2->isNullValue()) {
1614 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1615 // Don't try to evaluate aliases. External weak GV can be null.
1616 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1617 if (pred == ICmpInst::ICMP_EQ)
1618 return ConstantInt::getFalse(C1->getContext());
1619 else if (pred == ICmpInst::ICMP_NE)
1620 return ConstantInt::getTrue(C1->getContext());
1624 // If the comparison is a comparison between two i1's, simplify it.
1625 if (C1->getType()->isIntegerTy(1)) {
1627 case ICmpInst::ICMP_EQ:
1628 if (isa<ConstantInt>(C2))
1629 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1630 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1631 case ICmpInst::ICMP_NE:
1632 return ConstantExpr::getXor(C1, C2);
1638 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1639 APInt V1 = cast<ConstantInt>(C1)->getValue();
1640 APInt V2 = cast<ConstantInt>(C2)->getValue();
1642 default: llvm_unreachable("Invalid ICmp Predicate");
1643 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1644 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1645 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1646 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1647 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1648 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1649 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1650 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1651 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1652 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1654 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1655 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1656 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1657 APFloat::cmpResult R = C1V.compare(C2V);
1659 default: llvm_unreachable("Invalid FCmp Predicate");
1660 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1661 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1662 case FCmpInst::FCMP_UNO:
1663 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1664 case FCmpInst::FCMP_ORD:
1665 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1666 case FCmpInst::FCMP_UEQ:
1667 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1668 R==APFloat::cmpEqual);
1669 case FCmpInst::FCMP_OEQ:
1670 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1671 case FCmpInst::FCMP_UNE:
1672 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1673 case FCmpInst::FCMP_ONE:
1674 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1675 R==APFloat::cmpGreaterThan);
1676 case FCmpInst::FCMP_ULT:
1677 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1678 R==APFloat::cmpLessThan);
1679 case FCmpInst::FCMP_OLT:
1680 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1681 case FCmpInst::FCMP_UGT:
1682 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1683 R==APFloat::cmpGreaterThan);
1684 case FCmpInst::FCMP_OGT:
1685 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1686 case FCmpInst::FCMP_ULE:
1687 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1688 case FCmpInst::FCMP_OLE:
1689 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1690 R==APFloat::cmpEqual);
1691 case FCmpInst::FCMP_UGE:
1692 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1693 case FCmpInst::FCMP_OGE:
1694 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1695 R==APFloat::cmpEqual);
1697 } else if (C1->getType()->isVectorTy()) {
1698 // If we can constant fold the comparison of each element, constant fold
1699 // the whole vector comparison.
1700 SmallVector<Constant*, 4> ResElts;
1701 // Compare the elements, producing an i1 result or constant expr.
1702 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1703 Constant *C1E = C1->getAggregateElement(i);
1704 Constant *C2E = C2->getAggregateElement(i);
1705 if (C1E == 0 || C2E == 0) break;
1707 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1710 if (ResElts.size() == C1->getType()->getVectorNumElements())
1711 return ConstantVector::get(ResElts);
1714 if (C1->getType()->isFloatingPointTy()) {
1715 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1716 switch (evaluateFCmpRelation(C1, C2)) {
1717 default: llvm_unreachable("Unknown relation!");
1718 case FCmpInst::FCMP_UNO:
1719 case FCmpInst::FCMP_ORD:
1720 case FCmpInst::FCMP_UEQ:
1721 case FCmpInst::FCMP_UNE:
1722 case FCmpInst::FCMP_ULT:
1723 case FCmpInst::FCMP_UGT:
1724 case FCmpInst::FCMP_ULE:
1725 case FCmpInst::FCMP_UGE:
1726 case FCmpInst::FCMP_TRUE:
1727 case FCmpInst::FCMP_FALSE:
1728 case FCmpInst::BAD_FCMP_PREDICATE:
1729 break; // Couldn't determine anything about these constants.
1730 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1731 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1732 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1733 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1735 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1736 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1737 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1738 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1740 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1741 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1742 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1743 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1745 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1746 // We can only partially decide this relation.
1747 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1749 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1752 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1753 // We can only partially decide this relation.
1754 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1756 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1759 case FCmpInst::FCMP_ONE: // We know that C1 != C2
1760 // We can only partially decide this relation.
1761 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1763 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1768 // If we evaluated the result, return it now.
1770 return ConstantInt::get(ResultTy, Result);
1773 // Evaluate the relation between the two constants, per the predicate.
1774 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1775 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1776 default: llvm_unreachable("Unknown relational!");
1777 case ICmpInst::BAD_ICMP_PREDICATE:
1778 break; // Couldn't determine anything about these constants.
1779 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1780 // If we know the constants are equal, we can decide the result of this
1781 // computation precisely.
1782 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1784 case ICmpInst::ICMP_ULT:
1786 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1788 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1792 case ICmpInst::ICMP_SLT:
1794 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1796 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1800 case ICmpInst::ICMP_UGT:
1802 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1804 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1808 case ICmpInst::ICMP_SGT:
1810 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1812 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1816 case ICmpInst::ICMP_ULE:
1817 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1818 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1820 case ICmpInst::ICMP_SLE:
1821 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1822 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1824 case ICmpInst::ICMP_UGE:
1825 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1826 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1828 case ICmpInst::ICMP_SGE:
1829 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1830 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1832 case ICmpInst::ICMP_NE:
1833 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1834 if (pred == ICmpInst::ICMP_NE) Result = 1;
1838 // If we evaluated the result, return it now.
1840 return ConstantInt::get(ResultTy, Result);
1842 // If the right hand side is a bitcast, try using its inverse to simplify
1843 // it by moving it to the left hand side. We can't do this if it would turn
1844 // a vector compare into a scalar compare or visa versa.
1845 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1846 Constant *CE2Op0 = CE2->getOperand(0);
1847 if (CE2->getOpcode() == Instruction::BitCast &&
1848 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1849 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1850 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1854 // If the left hand side is an extension, try eliminating it.
1855 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1856 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1857 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1858 Constant *CE1Op0 = CE1->getOperand(0);
1859 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1860 if (CE1Inverse == CE1Op0) {
1861 // Check whether we can safely truncate the right hand side.
1862 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1863 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1864 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1870 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1871 (C1->isNullValue() && !C2->isNullValue())) {
1872 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1873 // other way if possible.
1874 // Also, if C1 is null and C2 isn't, flip them around.
1875 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1876 return ConstantExpr::getICmp(pred, C2, C1);
1882 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1884 template<typename IndexTy>
1885 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1886 // No indices means nothing that could be out of bounds.
1887 if (Idxs.empty()) return true;
1889 // If the first index is zero, it's in bounds.
1890 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1892 // If the first index is one and all the rest are zero, it's in bounds,
1893 // by the one-past-the-end rule.
1894 if (!cast<ConstantInt>(Idxs[0])->isOne())
1896 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1897 if (!cast<Constant>(Idxs[i])->isNullValue())
1902 template<typename IndexTy>
1903 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1905 ArrayRef<IndexTy> Idxs) {
1906 if (Idxs.empty()) return C;
1907 Constant *Idx0 = cast<Constant>(Idxs[0]);
1908 if ((Idxs.size() == 1 && Idx0->isNullValue()))
1911 if (isa<UndefValue>(C)) {
1912 PointerType *Ptr = cast<PointerType>(C->getType());
1913 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1914 assert(Ty != 0 && "Invalid indices for GEP!");
1915 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1918 if (C->isNullValue()) {
1920 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1921 if (!cast<Constant>(Idxs[i])->isNullValue()) {
1926 PointerType *Ptr = cast<PointerType>(C->getType());
1927 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1928 assert(Ty != 0 && "Invalid indices for GEP!");
1929 return ConstantPointerNull::get(PointerType::get(Ty,
1930 Ptr->getAddressSpace()));
1934 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1935 // Combine Indices - If the source pointer to this getelementptr instruction
1936 // is a getelementptr instruction, combine the indices of the two
1937 // getelementptr instructions into a single instruction.
1939 if (CE->getOpcode() == Instruction::GetElementPtr) {
1941 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1945 if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
1946 SmallVector<Value*, 16> NewIndices;
1947 NewIndices.reserve(Idxs.size() + CE->getNumOperands());
1948 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1949 NewIndices.push_back(CE->getOperand(i));
1951 // Add the last index of the source with the first index of the new GEP.
1952 // Make sure to handle the case when they are actually different types.
1953 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1954 // Otherwise it must be an array.
1955 if (!Idx0->isNullValue()) {
1956 Type *IdxTy = Combined->getType();
1957 if (IdxTy != Idx0->getType()) {
1958 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
1959 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1960 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
1961 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1964 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1968 NewIndices.push_back(Combined);
1969 NewIndices.append(Idxs.begin() + 1, Idxs.end());
1971 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1973 cast<GEPOperator>(CE)->isInBounds());
1977 // Implement folding of:
1978 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1980 // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1982 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
1983 if (PointerType *SPT =
1984 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1985 if (ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1986 if (ArrayType *CAT =
1987 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1988 if (CAT->getElementType() == SAT->getElementType())
1990 ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
1995 // Check to see if any array indices are not within the corresponding
1996 // notional array bounds. If so, try to determine if they can be factored
1997 // out into preceding dimensions.
1998 bool Unknown = false;
1999 SmallVector<Constant *, 8> NewIdxs;
2000 Type *Ty = C->getType();
2002 for (unsigned i = 0, e = Idxs.size(); i != e;
2003 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2004 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2005 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2006 if (ATy->getNumElements() <= INT64_MAX &&
2007 ATy->getNumElements() != 0 &&
2008 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2009 if (isa<SequentialType>(Prev)) {
2010 // It's out of range, but we can factor it into the prior
2012 NewIdxs.resize(Idxs.size());
2013 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2014 ATy->getNumElements());
2015 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2017 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2018 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2020 // Before adding, extend both operands to i64 to avoid
2021 // overflow trouble.
2022 if (!PrevIdx->getType()->isIntegerTy(64))
2023 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2024 Type::getInt64Ty(Div->getContext()));
2025 if (!Div->getType()->isIntegerTy(64))
2026 Div = ConstantExpr::getSExt(Div,
2027 Type::getInt64Ty(Div->getContext()));
2029 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2031 // It's out of range, but the prior dimension is a struct
2032 // so we can't do anything about it.
2037 // We don't know if it's in range or not.
2042 // If we did any factoring, start over with the adjusted indices.
2043 if (!NewIdxs.empty()) {
2044 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2045 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2046 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2049 // If all indices are known integers and normalized, we can do a simple
2050 // check for the "inbounds" property.
2051 if (!Unknown && !inBounds &&
2052 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2053 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2058 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2060 ArrayRef<Constant *> Idxs) {
2061 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2064 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2066 ArrayRef<Value *> Idxs) {
2067 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);