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 DataLayout, and the pieces that do. This is to avoid
16 // a dependence in IR on Target.
18 //===----------------------------------------------------------------------===//
20 #include "ConstantFold.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/ErrorHandling.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 SmallVector<Constant*, 16> Result;
59 Type *Ty = IntegerType::get(CV->getContext(), 32);
60 for (unsigned i = 0; i != NumElts; ++i) {
62 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
63 C = ConstantExpr::getBitCast(C, DstEltTy);
67 return ConstantVector::get(Result);
70 /// This function determines which opcode to use to fold two constant cast
71 /// expressions together. It uses CastInst::isEliminableCastPair to determine
72 /// the opcode. Consequently its just a wrapper around that function.
73 /// @brief Determine if it is valid to fold a cast of a cast
76 unsigned opc, ///< opcode of the second cast constant expression
77 ConstantExpr *Op, ///< the first cast constant expression
78 Type *DstTy ///< destination type of the first cast
80 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
81 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
82 assert(CastInst::isCast(opc) && "Invalid cast opcode");
84 // The the types and opcodes for the two Cast constant expressions
85 Type *SrcTy = Op->getOperand(0)->getType();
86 Type *MidTy = Op->getType();
87 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
88 Instruction::CastOps secondOp = Instruction::CastOps(opc);
90 // Assume that pointers are never more than 64 bits wide, and only use this
91 // for the middle type. Otherwise we could end up folding away illegal
92 // bitcasts between address spaces with different sizes.
93 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
95 // Let CastInst::isEliminableCastPair do the heavy lifting.
96 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
97 nullptr, FakeIntPtrTy, nullptr);
100 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
101 Type *SrcTy = V->getType();
103 return V; // no-op cast
105 // Check to see if we are casting a pointer to an aggregate to a pointer to
106 // the first element. If so, return the appropriate GEP instruction.
107 if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
108 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
109 if (PTy->getAddressSpace() == DPTy->getAddressSpace()
110 && DPTy->getElementType()->isSized()) {
111 SmallVector<Value*, 8> IdxList;
113 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
114 IdxList.push_back(Zero);
115 Type *ElTy = PTy->getElementType();
116 while (ElTy != DPTy->getElementType()) {
117 if (StructType *STy = dyn_cast<StructType>(ElTy)) {
118 if (STy->getNumElements() == 0) break;
119 ElTy = STy->getElementType(0);
120 IdxList.push_back(Zero);
121 } else if (SequentialType *STy =
122 dyn_cast<SequentialType>(ElTy)) {
123 if (ElTy->isPointerTy()) break; // Can't index into pointers!
124 ElTy = STy->getElementType();
125 IdxList.push_back(Zero);
131 if (ElTy == DPTy->getElementType())
132 // This GEP is inbounds because all indices are zero.
133 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
136 // Handle casts from one vector constant to another. We know that the src
137 // and dest type have the same size (otherwise its an illegal cast).
138 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
139 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
140 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
141 "Not cast between same sized vectors!");
143 // First, check for null. Undef is already handled.
144 if (isa<ConstantAggregateZero>(V))
145 return Constant::getNullValue(DestTy);
147 // Handle ConstantVector and ConstantAggregateVector.
148 return BitCastConstantVector(V, DestPTy);
151 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
152 // This allows for other simplifications (although some of them
153 // can only be handled by Analysis/ConstantFolding.cpp).
154 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
155 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
158 // Finally, implement bitcast folding now. The code below doesn't handle
160 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
161 return ConstantPointerNull::get(cast<PointerType>(DestTy));
163 // Handle integral constant input.
164 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
165 if (DestTy->isIntegerTy())
166 // Integral -> Integral. This is a no-op because the bit widths must
167 // be the same. Consequently, we just fold to V.
170 if (DestTy->isFloatingPointTy())
171 return ConstantFP::get(DestTy->getContext(),
172 APFloat(DestTy->getFltSemantics(),
175 // Otherwise, can't fold this (vector?)
179 // Handle ConstantFP input: FP -> Integral.
180 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
181 return ConstantInt::get(FP->getContext(),
182 FP->getValueAPF().bitcastToAPInt());
188 /// ExtractConstantBytes - V is an integer constant which only has a subset of
189 /// its bytes used. The bytes used are indicated by ByteStart (which is the
190 /// first byte used, counting from the least significant byte) and ByteSize,
191 /// which is the number of bytes used.
193 /// This function analyzes the specified constant to see if the specified byte
194 /// range can be returned as a simplified constant. If so, the constant is
195 /// returned, otherwise null is returned.
197 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
199 assert(C->getType()->isIntegerTy() &&
200 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
201 "Non-byte sized integer input");
202 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
203 assert(ByteSize && "Must be accessing some piece");
204 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
205 assert(ByteSize != CSize && "Should not extract everything");
207 // Constant Integers are simple.
208 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
209 APInt V = CI->getValue();
211 V = V.lshr(ByteStart*8);
212 V = V.trunc(ByteSize*8);
213 return ConstantInt::get(CI->getContext(), V);
216 // In the input is a constant expr, we might be able to recursively simplify.
217 // If not, we definitely can't do anything.
218 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
219 if (!CE) return nullptr;
221 switch (CE->getOpcode()) {
222 default: return nullptr;
223 case Instruction::Or: {
224 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
229 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
230 if (RHSC->isAllOnesValue())
233 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
236 return ConstantExpr::getOr(LHS, RHS);
238 case Instruction::And: {
239 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
244 if (RHS->isNullValue())
247 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
250 return ConstantExpr::getAnd(LHS, RHS);
252 case Instruction::LShr: {
253 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
256 unsigned ShAmt = Amt->getZExtValue();
257 // Cannot analyze non-byte shifts.
258 if ((ShAmt & 7) != 0)
262 // If the extract is known to be all zeros, return zero.
263 if (ByteStart >= CSize-ShAmt)
264 return Constant::getNullValue(IntegerType::get(CE->getContext(),
266 // If the extract is known to be fully in the input, extract it.
267 if (ByteStart+ByteSize+ShAmt <= CSize)
268 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
270 // TODO: Handle the 'partially zero' case.
274 case Instruction::Shl: {
275 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
278 unsigned ShAmt = Amt->getZExtValue();
279 // Cannot analyze non-byte shifts.
280 if ((ShAmt & 7) != 0)
284 // If the extract is known to be all zeros, return zero.
285 if (ByteStart+ByteSize <= ShAmt)
286 return Constant::getNullValue(IntegerType::get(CE->getContext(),
288 // If the extract is known to be fully in the input, extract it.
289 if (ByteStart >= ShAmt)
290 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
292 // TODO: Handle the 'partially zero' case.
296 case Instruction::ZExt: {
297 unsigned SrcBitSize =
298 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
300 // If extracting something that is completely zero, return 0.
301 if (ByteStart*8 >= SrcBitSize)
302 return Constant::getNullValue(IntegerType::get(CE->getContext(),
305 // If exactly extracting the input, return it.
306 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
307 return CE->getOperand(0);
309 // If extracting something completely in the input, if if the input is a
310 // multiple of 8 bits, recurse.
311 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
312 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
314 // Otherwise, if extracting a subset of the input, which is not multiple of
315 // 8 bits, do a shift and trunc to get the bits.
316 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
317 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
318 Constant *Res = CE->getOperand(0);
320 Res = ConstantExpr::getLShr(Res,
321 ConstantInt::get(Res->getType(), ByteStart*8));
322 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
326 // TODO: Handle the 'partially zero' case.
332 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
333 /// on Ty, with any known factors factored out. If Folded is false,
334 /// return null if no factoring was possible, to avoid endlessly
335 /// bouncing an unfoldable expression back into the top-level folder.
337 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
339 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
340 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
341 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
342 return ConstantExpr::getNUWMul(E, N);
345 if (StructType *STy = dyn_cast<StructType>(Ty))
346 if (!STy->isPacked()) {
347 unsigned NumElems = STy->getNumElements();
348 // An empty struct has size zero.
350 return ConstantExpr::getNullValue(DestTy);
351 // Check for a struct with all members having the same size.
352 Constant *MemberSize =
353 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
355 for (unsigned i = 1; i != NumElems; ++i)
357 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
362 Constant *N = ConstantInt::get(DestTy, NumElems);
363 return ConstantExpr::getNUWMul(MemberSize, N);
367 // Pointer size doesn't depend on the pointee type, so canonicalize them
368 // to an arbitrary pointee.
369 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
370 if (!PTy->getElementType()->isIntegerTy(1))
372 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
373 PTy->getAddressSpace()),
376 // If there's no interesting folding happening, bail so that we don't create
377 // a constant that looks like it needs folding but really doesn't.
381 // Base case: Get a regular sizeof expression.
382 Constant *C = ConstantExpr::getSizeOf(Ty);
383 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
389 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
390 /// on Ty, with any known factors factored out. If Folded is false,
391 /// return null if no factoring was possible, to avoid endlessly
392 /// bouncing an unfoldable expression back into the top-level folder.
394 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
396 // The alignment of an array is equal to the alignment of the
397 // array element. Note that this is not always true for vectors.
398 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
399 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
400 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
407 if (StructType *STy = dyn_cast<StructType>(Ty)) {
408 // Packed structs always have an alignment of 1.
410 return ConstantInt::get(DestTy, 1);
412 // Otherwise, struct alignment is the maximum alignment of any member.
413 // Without target data, we can't compare much, but we can check to see
414 // if all the members have the same alignment.
415 unsigned NumElems = STy->getNumElements();
416 // An empty struct has minimal alignment.
418 return ConstantInt::get(DestTy, 1);
419 // Check for a struct with all members having the same alignment.
420 Constant *MemberAlign =
421 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
423 for (unsigned i = 1; i != NumElems; ++i)
424 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
432 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
433 // to an arbitrary pointee.
434 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
435 if (!PTy->getElementType()->isIntegerTy(1))
437 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
439 PTy->getAddressSpace()),
442 // If there's no interesting folding happening, bail so that we don't create
443 // a constant that looks like it needs folding but really doesn't.
447 // Base case: Get a regular alignof expression.
448 Constant *C = ConstantExpr::getAlignOf(Ty);
449 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
455 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
456 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
457 /// return null if no factoring was possible, to avoid endlessly
458 /// bouncing an unfoldable expression back into the top-level folder.
460 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
463 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
464 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
467 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
468 return ConstantExpr::getNUWMul(E, N);
471 if (StructType *STy = dyn_cast<StructType>(Ty))
472 if (!STy->isPacked()) {
473 unsigned NumElems = STy->getNumElements();
474 // An empty struct has no members.
477 // Check for a struct with all members having the same size.
478 Constant *MemberSize =
479 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
481 for (unsigned i = 1; i != NumElems; ++i)
483 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
488 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
493 return ConstantExpr::getNUWMul(MemberSize, N);
497 // If there's no interesting folding happening, bail so that we don't create
498 // a constant that looks like it needs folding but really doesn't.
502 // Base case: Get a regular offsetof expression.
503 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
504 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
510 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
512 if (isa<UndefValue>(V)) {
513 // zext(undef) = 0, because the top bits will be zero.
514 // sext(undef) = 0, because the top bits will all be the same.
515 // [us]itofp(undef) = 0, because the result value is bounded.
516 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
517 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
518 return Constant::getNullValue(DestTy);
519 return UndefValue::get(DestTy);
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 // Do not fold addrspacecast (gep 0, .., 0). It might make the
534 // addrspacecast uncanonicalized.
535 opc != Instruction::AddrSpaceCast) {
536 // If all of the indexes in the GEP are null values, there is no pointer
537 // adjustment going on. We might as well cast the source pointer.
538 bool isAllNull = true;
539 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
540 if (!CE->getOperand(i)->isNullValue()) {
545 // This is casting one pointer type to another, always BitCast
546 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
550 // If the cast operand is a constant vector, perform the cast by
551 // operating on each element. In the cast of bitcasts, the element
552 // count may be mismatched; don't attempt to handle that here.
553 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
554 DestTy->isVectorTy() &&
555 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
556 SmallVector<Constant*, 16> res;
557 VectorType *DestVecTy = cast<VectorType>(DestTy);
558 Type *DstEltTy = DestVecTy->getElementType();
559 Type *Ty = IntegerType::get(V->getContext(), 32);
560 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
562 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
563 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
565 return ConstantVector::get(res);
568 // We actually have to do a cast now. Perform the cast according to the
572 llvm_unreachable("Failed to cast constant expression");
573 case Instruction::FPTrunc:
574 case Instruction::FPExt:
575 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
577 APFloat Val = FPC->getValueAPF();
578 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
579 DestTy->isFloatTy() ? APFloat::IEEEsingle :
580 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
581 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
582 DestTy->isFP128Ty() ? APFloat::IEEEquad :
583 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
585 APFloat::rmNearestTiesToEven, &ignored);
586 return ConstantFP::get(V->getContext(), Val);
588 return nullptr; // Can't fold.
589 case Instruction::FPToUI:
590 case Instruction::FPToSI:
591 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
592 const APFloat &V = FPC->getValueAPF();
595 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
596 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
597 APFloat::rmTowardZero, &ignored);
598 APInt Val(DestBitWidth, x);
599 return ConstantInt::get(FPC->getContext(), Val);
601 return nullptr; // Can't fold.
602 case Instruction::IntToPtr: //always treated as unsigned
603 if (V->isNullValue()) // Is it an integral null value?
604 return ConstantPointerNull::get(cast<PointerType>(DestTy));
605 return nullptr; // Other pointer types cannot be casted
606 case Instruction::PtrToInt: // always treated as unsigned
607 // Is it a null pointer value?
608 if (V->isNullValue())
609 return ConstantInt::get(DestTy, 0);
610 // If this is a sizeof-like expression, pull out multiplications by
611 // known factors to expose them to subsequent folding. If it's an
612 // alignof-like expression, factor out known factors.
613 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
614 if (CE->getOpcode() == Instruction::GetElementPtr &&
615 CE->getOperand(0)->isNullValue()) {
617 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
618 if (CE->getNumOperands() == 2) {
619 // Handle a sizeof-like expression.
620 Constant *Idx = CE->getOperand(1);
621 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
622 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
623 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
626 return ConstantExpr::getMul(C, Idx);
628 } else if (CE->getNumOperands() == 3 &&
629 CE->getOperand(1)->isNullValue()) {
630 // Handle an alignof-like expression.
631 if (StructType *STy = dyn_cast<StructType>(Ty))
632 if (!STy->isPacked()) {
633 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
635 STy->getNumElements() == 2 &&
636 STy->getElementType(0)->isIntegerTy(1)) {
637 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
640 // Handle an offsetof-like expression.
641 if (Ty->isStructTy() || Ty->isArrayTy()) {
642 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
648 // Other pointer types cannot be casted
650 case Instruction::UIToFP:
651 case Instruction::SIToFP:
652 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
653 APInt api = CI->getValue();
654 APFloat apf(DestTy->getFltSemantics(),
655 APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
656 (void)apf.convertFromAPInt(api,
657 opc==Instruction::SIToFP,
658 APFloat::rmNearestTiesToEven);
659 return ConstantFP::get(V->getContext(), apf);
662 case Instruction::ZExt:
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().zext(BitWidth));
669 case Instruction::SExt:
670 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
671 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
672 return ConstantInt::get(V->getContext(),
673 CI->getValue().sext(BitWidth));
676 case Instruction::Trunc: {
677 if (V->getType()->isVectorTy())
680 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
681 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
682 return ConstantInt::get(V->getContext(),
683 CI->getValue().trunc(DestBitWidth));
686 // The input must be a constantexpr. See if we can simplify this based on
687 // the bytes we are demanding. Only do this if the source and dest are an
688 // even multiple of a byte.
689 if ((DestBitWidth & 7) == 0 &&
690 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
691 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
696 case Instruction::BitCast:
697 return FoldBitCast(V, DestTy);
698 case Instruction::AddrSpaceCast:
703 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
704 Constant *V1, Constant *V2) {
705 // Check for i1 and vector true/false conditions.
706 if (Cond->isNullValue()) return V2;
707 if (Cond->isAllOnesValue()) return V1;
709 // If the condition is a vector constant, fold the result elementwise.
710 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
711 SmallVector<Constant*, 16> Result;
712 Type *Ty = IntegerType::get(CondV->getContext(), 32);
713 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
715 Constant *V1Element = ConstantExpr::getExtractElement(V1,
716 ConstantInt::get(Ty, i));
717 Constant *V2Element = ConstantExpr::getExtractElement(V2,
718 ConstantInt::get(Ty, i));
719 Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
720 if (V1Element == V2Element) {
722 } else if (isa<UndefValue>(Cond)) {
723 V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
725 if (!isa<ConstantInt>(Cond)) break;
726 V = Cond->isNullValue() ? V2Element : V1Element;
731 // If we were able to build the vector, return it.
732 if (Result.size() == V1->getType()->getVectorNumElements())
733 return ConstantVector::get(Result);
736 if (isa<UndefValue>(Cond)) {
737 if (isa<UndefValue>(V1)) return V1;
740 if (isa<UndefValue>(V1)) return V2;
741 if (isa<UndefValue>(V2)) return V1;
742 if (V1 == V2) return V1;
744 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
745 if (TrueVal->getOpcode() == Instruction::Select)
746 if (TrueVal->getOperand(0) == Cond)
747 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
749 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
750 if (FalseVal->getOpcode() == Instruction::Select)
751 if (FalseVal->getOperand(0) == Cond)
752 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
758 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
760 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
761 return UndefValue::get(Val->getType()->getVectorElementType());
762 if (Val->isNullValue()) // ee(zero, x) -> zero
763 return Constant::getNullValue(Val->getType()->getVectorElementType());
764 // ee({w,x,y,z}, undef) -> undef
765 if (isa<UndefValue>(Idx))
766 return UndefValue::get(Val->getType()->getVectorElementType());
768 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
769 uint64_t Index = CIdx->getZExtValue();
770 // ee({w,x,y,z}, wrong_value) -> undef
771 if (Index >= Val->getType()->getVectorNumElements())
772 return UndefValue::get(Val->getType()->getVectorElementType());
773 return Val->getAggregateElement(Index);
778 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
781 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
782 if (!CIdx) return nullptr;
783 const APInt &IdxVal = CIdx->getValue();
785 SmallVector<Constant*, 16> Result;
786 Type *Ty = IntegerType::get(Val->getContext(), 32);
787 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
789 Result.push_back(Elt);
794 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
798 return ConstantVector::get(Result);
801 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
804 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
805 Type *EltTy = V1->getType()->getVectorElementType();
807 // Undefined shuffle mask -> undefined value.
808 if (isa<UndefValue>(Mask))
809 return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
811 // Don't break the bitcode reader hack.
812 if (isa<ConstantExpr>(Mask)) return nullptr;
814 unsigned SrcNumElts = V1->getType()->getVectorNumElements();
816 // Loop over the shuffle mask, evaluating each element.
817 SmallVector<Constant*, 32> Result;
818 for (unsigned i = 0; i != MaskNumElts; ++i) {
819 int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
821 Result.push_back(UndefValue::get(EltTy));
825 if (unsigned(Elt) >= SrcNumElts*2)
826 InElt = UndefValue::get(EltTy);
827 else if (unsigned(Elt) >= SrcNumElts) {
828 Type *Ty = IntegerType::get(V2->getContext(), 32);
830 ConstantExpr::getExtractElement(V2,
831 ConstantInt::get(Ty, Elt - SrcNumElts));
833 Type *Ty = IntegerType::get(V1->getContext(), 32);
834 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
836 Result.push_back(InElt);
839 return ConstantVector::get(Result);
842 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
843 ArrayRef<unsigned> Idxs) {
844 // Base case: no indices, so return the entire value.
848 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
849 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
854 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
856 ArrayRef<unsigned> Idxs) {
857 // Base case: no indices, so replace the entire value.
862 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
863 NumElts = ST->getNumElements();
864 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
865 NumElts = AT->getNumElements();
867 NumElts = Agg->getType()->getVectorNumElements();
869 SmallVector<Constant*, 32> Result;
870 for (unsigned i = 0; i != NumElts; ++i) {
871 Constant *C = Agg->getAggregateElement(i);
872 if (!C) return nullptr;
875 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
880 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
881 return ConstantStruct::get(ST, Result);
882 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
883 return ConstantArray::get(AT, Result);
884 return ConstantVector::get(Result);
888 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
889 Constant *C1, Constant *C2) {
890 // Handle UndefValue up front.
891 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
893 case Instruction::Xor:
894 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
895 // Handle undef ^ undef -> 0 special case. This is a common
897 return Constant::getNullValue(C1->getType());
899 case Instruction::Add:
900 case Instruction::Sub:
901 return UndefValue::get(C1->getType());
902 case Instruction::And:
903 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
905 return Constant::getNullValue(C1->getType()); // undef & X -> 0
906 case Instruction::Mul: {
908 // X * undef -> undef if X is odd or undef
909 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
910 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
911 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
912 return UndefValue::get(C1->getType());
914 // X * undef -> 0 otherwise
915 return Constant::getNullValue(C1->getType());
917 case Instruction::UDiv:
918 case Instruction::SDiv:
919 // undef / 1 -> undef
920 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
921 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
925 case Instruction::URem:
926 case Instruction::SRem:
927 if (!isa<UndefValue>(C2)) // undef / X -> 0
928 return Constant::getNullValue(C1->getType());
929 return C2; // X / undef -> undef
930 case Instruction::Or: // X | undef -> -1
931 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
933 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
934 case Instruction::LShr:
935 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
936 return C1; // undef lshr undef -> undef
937 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
939 case Instruction::AShr:
940 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
941 return Constant::getAllOnesValue(C1->getType());
942 else if (isa<UndefValue>(C1))
943 return C1; // undef ashr undef -> undef
945 return C1; // X ashr undef --> X
946 case Instruction::Shl:
947 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
948 return C1; // undef shl undef -> undef
949 // undef << X -> 0 or X << undef -> 0
950 return Constant::getNullValue(C1->getType());
954 // Handle simplifications when the RHS is a constant int.
955 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
957 case Instruction::Add:
958 if (CI2->equalsInt(0)) return C1; // X + 0 == X
960 case Instruction::Sub:
961 if (CI2->equalsInt(0)) return C1; // X - 0 == X
963 case Instruction::Mul:
964 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
965 if (CI2->equalsInt(1))
966 return C1; // X * 1 == X
968 case Instruction::UDiv:
969 case Instruction::SDiv:
970 if (CI2->equalsInt(1))
971 return C1; // X / 1 == X
972 if (CI2->equalsInt(0))
973 return UndefValue::get(CI2->getType()); // X / 0 == undef
975 case Instruction::URem:
976 case Instruction::SRem:
977 if (CI2->equalsInt(1))
978 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
979 if (CI2->equalsInt(0))
980 return UndefValue::get(CI2->getType()); // X % 0 == undef
982 case Instruction::And:
983 if (CI2->isZero()) return C2; // X & 0 == 0
984 if (CI2->isAllOnesValue())
985 return C1; // X & -1 == X
987 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
988 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
989 if (CE1->getOpcode() == Instruction::ZExt) {
990 unsigned DstWidth = CI2->getType()->getBitWidth();
992 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
993 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
994 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
998 // If and'ing the address of a global with a constant, fold it.
999 if (CE1->getOpcode() == Instruction::PtrToInt &&
1000 isa<GlobalValue>(CE1->getOperand(0))) {
1001 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1003 // Functions are at least 4-byte aligned.
1004 unsigned GVAlign = GV->getAlignment();
1005 if (isa<Function>(GV))
1006 GVAlign = std::max(GVAlign, 4U);
1009 unsigned DstWidth = CI2->getType()->getBitWidth();
1010 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1011 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1013 // If checking bits we know are clear, return zero.
1014 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1015 return Constant::getNullValue(CI2->getType());
1020 case Instruction::Or:
1021 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1022 if (CI2->isAllOnesValue())
1023 return C2; // X | -1 == -1
1025 case Instruction::Xor:
1026 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1028 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1029 switch (CE1->getOpcode()) {
1031 case Instruction::ICmp:
1032 case Instruction::FCmp:
1033 // cmp pred ^ true -> cmp !pred
1034 assert(CI2->equalsInt(1));
1035 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1036 pred = CmpInst::getInversePredicate(pred);
1037 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1038 CE1->getOperand(1));
1042 case Instruction::AShr:
1043 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1044 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1045 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1046 return ConstantExpr::getLShr(C1, C2);
1049 } else if (isa<ConstantInt>(C1)) {
1050 // If C1 is a ConstantInt and C2 is not, swap the operands.
1051 if (Instruction::isCommutative(Opcode))
1052 return ConstantExpr::get(Opcode, C2, C1);
1055 // At this point we know neither constant is an UndefValue.
1056 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1057 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1058 const APInt &C1V = CI1->getValue();
1059 const APInt &C2V = CI2->getValue();
1063 case Instruction::Add:
1064 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1065 case Instruction::Sub:
1066 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1067 case Instruction::Mul:
1068 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1069 case Instruction::UDiv:
1070 assert(!CI2->isNullValue() && "Div by zero handled above");
1071 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1072 case Instruction::SDiv:
1073 assert(!CI2->isNullValue() && "Div by zero handled above");
1074 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1075 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1076 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1077 case Instruction::URem:
1078 assert(!CI2->isNullValue() && "Div by zero handled above");
1079 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1080 case Instruction::SRem:
1081 assert(!CI2->isNullValue() && "Div by zero handled above");
1082 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1083 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1084 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1085 case Instruction::And:
1086 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1087 case Instruction::Or:
1088 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1089 case Instruction::Xor:
1090 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1091 case Instruction::Shl: {
1092 uint32_t shiftAmt = C2V.getZExtValue();
1093 if (shiftAmt < C1V.getBitWidth())
1094 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1096 return UndefValue::get(C1->getType()); // too big shift is undef
1098 case Instruction::LShr: {
1099 uint32_t shiftAmt = C2V.getZExtValue();
1100 if (shiftAmt < C1V.getBitWidth())
1101 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1103 return UndefValue::get(C1->getType()); // too big shift is undef
1105 case Instruction::AShr: {
1106 uint32_t shiftAmt = C2V.getZExtValue();
1107 if (shiftAmt < C1V.getBitWidth())
1108 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1110 return UndefValue::get(C1->getType()); // too big shift is undef
1116 case Instruction::SDiv:
1117 case Instruction::UDiv:
1118 case Instruction::URem:
1119 case Instruction::SRem:
1120 case Instruction::LShr:
1121 case Instruction::AShr:
1122 case Instruction::Shl:
1123 if (CI1->equalsInt(0)) return C1;
1128 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1129 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1130 APFloat C1V = CFP1->getValueAPF();
1131 APFloat C2V = CFP2->getValueAPF();
1132 APFloat C3V = C1V; // copy for modification
1136 case Instruction::FAdd:
1137 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1138 return ConstantFP::get(C1->getContext(), C3V);
1139 case Instruction::FSub:
1140 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1141 return ConstantFP::get(C1->getContext(), C3V);
1142 case Instruction::FMul:
1143 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1144 return ConstantFP::get(C1->getContext(), C3V);
1145 case Instruction::FDiv:
1146 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1147 return ConstantFP::get(C1->getContext(), C3V);
1148 case Instruction::FRem:
1149 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1150 return ConstantFP::get(C1->getContext(), C3V);
1153 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1154 // Perform elementwise folding.
1155 SmallVector<Constant*, 16> Result;
1156 Type *Ty = IntegerType::get(VTy->getContext(), 32);
1157 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1159 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1161 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1163 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1166 return ConstantVector::get(Result);
1169 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1170 // There are many possible foldings we could do here. We should probably
1171 // at least fold add of a pointer with an integer into the appropriate
1172 // getelementptr. This will improve alias analysis a bit.
1174 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1176 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1177 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1178 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1179 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1181 } else if (isa<ConstantExpr>(C2)) {
1182 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1183 // other way if possible.
1184 if (Instruction::isCommutative(Opcode))
1185 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1188 // i1 can be simplified in many cases.
1189 if (C1->getType()->isIntegerTy(1)) {
1191 case Instruction::Add:
1192 case Instruction::Sub:
1193 return ConstantExpr::getXor(C1, C2);
1194 case Instruction::Mul:
1195 return ConstantExpr::getAnd(C1, C2);
1196 case Instruction::Shl:
1197 case Instruction::LShr:
1198 case Instruction::AShr:
1199 // We can assume that C2 == 0. If it were one the result would be
1200 // undefined because the shift value is as large as the bitwidth.
1202 case Instruction::SDiv:
1203 case Instruction::UDiv:
1204 // We can assume that C2 == 1. If it were zero the result would be
1205 // undefined through division by zero.
1207 case Instruction::URem:
1208 case Instruction::SRem:
1209 // We can assume that C2 == 1. If it were zero the result would be
1210 // undefined through division by zero.
1211 return ConstantInt::getFalse(C1->getContext());
1217 // We don't know how to fold this.
1221 /// isZeroSizedType - This type is zero sized if its an array or structure of
1222 /// zero sized types. The only leaf zero sized type is an empty structure.
1223 static bool isMaybeZeroSizedType(Type *Ty) {
1224 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1225 if (STy->isOpaque()) return true; // Can't say.
1227 // If all of elements have zero size, this does too.
1228 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1229 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1232 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1233 return isMaybeZeroSizedType(ATy->getElementType());
1238 /// IdxCompare - Compare the two constants as though they were getelementptr
1239 /// indices. This allows coersion of the types to be the same thing.
1241 /// If the two constants are the "same" (after coersion), return 0. If the
1242 /// first is less than the second, return -1, if the second is less than the
1243 /// first, return 1. If the constants are not integral, return -2.
1245 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1246 if (C1 == C2) return 0;
1248 // Ok, we found a different index. If they are not ConstantInt, we can't do
1249 // anything with them.
1250 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1251 return -2; // don't know!
1253 // Ok, we have two differing integer indices. Sign extend them to be the same
1254 // type. Long is always big enough, so we use it.
1255 if (!C1->getType()->isIntegerTy(64))
1256 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1258 if (!C2->getType()->isIntegerTy(64))
1259 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1261 if (C1 == C2) return 0; // They are equal
1263 // If the type being indexed over is really just a zero sized type, there is
1264 // no pointer difference being made here.
1265 if (isMaybeZeroSizedType(ElTy))
1266 return -2; // dunno.
1268 // If they are really different, now that they are the same type, then we
1269 // found a difference!
1270 if (cast<ConstantInt>(C1)->getSExtValue() <
1271 cast<ConstantInt>(C2)->getSExtValue())
1277 /// evaluateFCmpRelation - This function determines if there is anything we can
1278 /// decide about the two constants provided. This doesn't need to handle simple
1279 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1280 /// If we can determine that the two constants have a particular relation to
1281 /// each other, we should return the corresponding FCmpInst predicate,
1282 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1283 /// ConstantFoldCompareInstruction.
1285 /// To simplify this code we canonicalize the relation so that the first
1286 /// operand is always the most "complex" of the two. We consider ConstantFP
1287 /// to be the simplest, and ConstantExprs to be the most complex.
1288 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1289 assert(V1->getType() == V2->getType() &&
1290 "Cannot compare values of different types!");
1292 // Handle degenerate case quickly
1293 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1295 if (!isa<ConstantExpr>(V1)) {
1296 if (!isa<ConstantExpr>(V2)) {
1297 // We distilled thisUse the standard constant folder for a few cases
1298 ConstantInt *R = nullptr;
1299 R = dyn_cast<ConstantInt>(
1300 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1301 if (R && !R->isZero())
1302 return FCmpInst::FCMP_OEQ;
1303 R = dyn_cast<ConstantInt>(
1304 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1305 if (R && !R->isZero())
1306 return FCmpInst::FCMP_OLT;
1307 R = dyn_cast<ConstantInt>(
1308 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1309 if (R && !R->isZero())
1310 return FCmpInst::FCMP_OGT;
1312 // Nothing more we can do
1313 return FCmpInst::BAD_FCMP_PREDICATE;
1316 // If the first operand is simple and second is ConstantExpr, swap operands.
1317 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1318 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1319 return FCmpInst::getSwappedPredicate(SwappedRelation);
1321 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1322 // constantexpr or a simple constant.
1323 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1324 switch (CE1->getOpcode()) {
1325 case Instruction::FPTrunc:
1326 case Instruction::FPExt:
1327 case Instruction::UIToFP:
1328 case Instruction::SIToFP:
1329 // We might be able to do something with these but we don't right now.
1335 // There are MANY other foldings that we could perform here. They will
1336 // probably be added on demand, as they seem needed.
1337 return FCmpInst::BAD_FCMP_PREDICATE;
1340 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1341 const GlobalValue *GV2) {
1342 // Don't try to decide equality of aliases.
1343 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1344 if (!GV1->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1345 return ICmpInst::ICMP_NE;
1346 return ICmpInst::BAD_ICMP_PREDICATE;
1349 /// evaluateICmpRelation - This function determines if there is anything we can
1350 /// decide about the two constants provided. This doesn't need to handle simple
1351 /// things like integer comparisons, but should instead handle ConstantExprs
1352 /// and GlobalValues. If we can determine that the two constants have a
1353 /// particular relation to each other, we should return the corresponding ICmp
1354 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1356 /// To simplify this code we canonicalize the relation so that the first
1357 /// operand is always the most "complex" of the two. We consider simple
1358 /// constants (like ConstantInt) to be the simplest, followed by
1359 /// GlobalValues, followed by ConstantExpr's (the most complex).
1361 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1363 assert(V1->getType() == V2->getType() &&
1364 "Cannot compare different types of values!");
1365 if (V1 == V2) return ICmpInst::ICMP_EQ;
1367 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1368 !isa<BlockAddress>(V1)) {
1369 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1370 !isa<BlockAddress>(V2)) {
1371 // We distilled this down to a simple case, use the standard constant
1373 ConstantInt *R = nullptr;
1374 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1375 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1376 if (R && !R->isZero())
1378 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1379 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1380 if (R && !R->isZero())
1382 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1383 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1384 if (R && !R->isZero())
1387 // If we couldn't figure it out, bail.
1388 return ICmpInst::BAD_ICMP_PREDICATE;
1391 // If the first operand is simple, swap operands.
1392 ICmpInst::Predicate SwappedRelation =
1393 evaluateICmpRelation(V2, V1, isSigned);
1394 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1395 return ICmpInst::getSwappedPredicate(SwappedRelation);
1397 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1398 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1399 ICmpInst::Predicate SwappedRelation =
1400 evaluateICmpRelation(V2, V1, isSigned);
1401 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1402 return ICmpInst::getSwappedPredicate(SwappedRelation);
1403 return ICmpInst::BAD_ICMP_PREDICATE;
1406 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1407 // constant (which, since the types must match, means that it's a
1408 // ConstantPointerNull).
1409 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1410 return areGlobalsPotentiallyEqual(GV, GV2);
1411 } else if (isa<BlockAddress>(V2)) {
1412 return ICmpInst::ICMP_NE; // Globals never equal labels.
1414 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1415 // GlobalVals can never be null unless they have external weak linkage.
1416 // We don't try to evaluate aliases here.
1417 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1418 return ICmpInst::ICMP_NE;
1420 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1421 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1422 ICmpInst::Predicate SwappedRelation =
1423 evaluateICmpRelation(V2, V1, isSigned);
1424 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1425 return ICmpInst::getSwappedPredicate(SwappedRelation);
1426 return ICmpInst::BAD_ICMP_PREDICATE;
1429 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1430 // constant (which, since the types must match, means that it is a
1431 // ConstantPointerNull).
1432 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1433 // Block address in another function can't equal this one, but block
1434 // addresses in the current function might be the same if blocks are
1436 if (BA2->getFunction() != BA->getFunction())
1437 return ICmpInst::ICMP_NE;
1439 // Block addresses aren't null, don't equal the address of globals.
1440 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1441 "Canonicalization guarantee!");
1442 return ICmpInst::ICMP_NE;
1445 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1446 // constantexpr, a global, block address, or a simple constant.
1447 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1448 Constant *CE1Op0 = CE1->getOperand(0);
1450 switch (CE1->getOpcode()) {
1451 case Instruction::Trunc:
1452 case Instruction::FPTrunc:
1453 case Instruction::FPExt:
1454 case Instruction::FPToUI:
1455 case Instruction::FPToSI:
1456 break; // We can't evaluate floating point casts or truncations.
1458 case Instruction::UIToFP:
1459 case Instruction::SIToFP:
1460 case Instruction::BitCast:
1461 case Instruction::ZExt:
1462 case Instruction::SExt:
1463 // If the cast is not actually changing bits, and the second operand is a
1464 // null pointer, do the comparison with the pre-casted value.
1465 if (V2->isNullValue() &&
1466 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1467 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1468 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1469 return evaluateICmpRelation(CE1Op0,
1470 Constant::getNullValue(CE1Op0->getType()),
1475 case Instruction::GetElementPtr: {
1476 GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1477 // Ok, since this is a getelementptr, we know that the constant has a
1478 // pointer type. Check the various cases.
1479 if (isa<ConstantPointerNull>(V2)) {
1480 // If we are comparing a GEP to a null pointer, check to see if the base
1481 // of the GEP equals the null pointer.
1482 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1483 if (GV->hasExternalWeakLinkage())
1484 // Weak linkage GVals could be zero or not. We're comparing that
1485 // to null pointer so its greater-or-equal
1486 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1488 // If its not weak linkage, the GVal must have a non-zero address
1489 // so the result is greater-than
1490 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1491 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1492 // If we are indexing from a null pointer, check to see if we have any
1493 // non-zero indices.
1494 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1495 if (!CE1->getOperand(i)->isNullValue())
1496 // Offsetting from null, must not be equal.
1497 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1498 // Only zero indexes from null, must still be zero.
1499 return ICmpInst::ICMP_EQ;
1501 // Otherwise, we can't really say if the first operand is null or not.
1502 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1503 if (isa<ConstantPointerNull>(CE1Op0)) {
1504 if (GV2->hasExternalWeakLinkage())
1505 // Weak linkage GVals could be zero or not. We're comparing it to
1506 // a null pointer, so its less-or-equal
1507 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1509 // If its not weak linkage, the GVal must have a non-zero address
1510 // so the result is less-than
1511 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1512 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1514 // If this is a getelementptr of the same global, then it must be
1515 // different. Because the types must match, the getelementptr could
1516 // only have at most one index, and because we fold getelementptr's
1517 // with a single zero index, it must be nonzero.
1518 assert(CE1->getNumOperands() == 2 &&
1519 !CE1->getOperand(1)->isNullValue() &&
1520 "Surprising getelementptr!");
1521 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1523 if (CE1GEP->hasAllZeroIndices())
1524 return areGlobalsPotentiallyEqual(GV, GV2);
1525 return ICmpInst::BAD_ICMP_PREDICATE;
1529 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1530 Constant *CE2Op0 = CE2->getOperand(0);
1532 // There are MANY other foldings that we could perform here. They will
1533 // probably be added on demand, as they seem needed.
1534 switch (CE2->getOpcode()) {
1536 case Instruction::GetElementPtr:
1537 // By far the most common case to handle is when the base pointers are
1538 // obviously to the same global.
1539 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1540 // Don't know relative ordering, but check for inequality.
1541 if (CE1Op0 != CE2Op0) {
1542 GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1543 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1544 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1545 cast<GlobalValue>(CE2Op0));
1546 return ICmpInst::BAD_ICMP_PREDICATE;
1548 // Ok, we know that both getelementptr instructions are based on the
1549 // same global. From this, we can precisely determine the relative
1550 // ordering of the resultant pointers.
1553 // The logic below assumes that the result of the comparison
1554 // can be determined by finding the first index that differs.
1555 // This doesn't work if there is over-indexing in any
1556 // subsequent indices, so check for that case first.
1557 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1558 !CE2->isGEPWithNoNotionalOverIndexing())
1559 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1561 // Compare all of the operands the GEP's have in common.
1562 gep_type_iterator GTI = gep_type_begin(CE1);
1563 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1565 switch (IdxCompare(CE1->getOperand(i),
1566 CE2->getOperand(i), GTI.getIndexedType())) {
1567 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1568 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1569 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1572 // Ok, we ran out of things they have in common. If any leftovers
1573 // are non-zero then we have a difference, otherwise we are equal.
1574 for (; i < CE1->getNumOperands(); ++i)
1575 if (!CE1->getOperand(i)->isNullValue()) {
1576 if (isa<ConstantInt>(CE1->getOperand(i)))
1577 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1579 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1582 for (; i < CE2->getNumOperands(); ++i)
1583 if (!CE2->getOperand(i)->isNullValue()) {
1584 if (isa<ConstantInt>(CE2->getOperand(i)))
1585 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1587 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1589 return ICmpInst::ICMP_EQ;
1599 return ICmpInst::BAD_ICMP_PREDICATE;
1602 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1603 Constant *C1, Constant *C2) {
1605 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1606 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1607 VT->getNumElements());
1609 ResultTy = Type::getInt1Ty(C1->getContext());
1611 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1612 if (pred == FCmpInst::FCMP_FALSE)
1613 return Constant::getNullValue(ResultTy);
1615 if (pred == FCmpInst::FCMP_TRUE)
1616 return Constant::getAllOnesValue(ResultTy);
1618 // Handle some degenerate cases first
1619 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1620 // For EQ and NE, we can always pick a value for the undef to make the
1621 // predicate pass or fail, so we can return undef.
1622 // Also, if both operands are undef, we can return undef.
1623 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1624 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1625 return UndefValue::get(ResultTy);
1626 // Otherwise, pick the same value as the non-undef operand, and fold
1627 // it to true or false.
1628 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1631 // icmp eq/ne(null,GV) -> false/true
1632 if (C1->isNullValue()) {
1633 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1634 // Don't try to evaluate aliases. External weak GV can be null.
1635 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1636 if (pred == ICmpInst::ICMP_EQ)
1637 return ConstantInt::getFalse(C1->getContext());
1638 else if (pred == ICmpInst::ICMP_NE)
1639 return ConstantInt::getTrue(C1->getContext());
1641 // icmp eq/ne(GV,null) -> false/true
1642 } else if (C2->isNullValue()) {
1643 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1644 // Don't try to evaluate aliases. External weak GV can be null.
1645 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1646 if (pred == ICmpInst::ICMP_EQ)
1647 return ConstantInt::getFalse(C1->getContext());
1648 else if (pred == ICmpInst::ICMP_NE)
1649 return ConstantInt::getTrue(C1->getContext());
1653 // If the comparison is a comparison between two i1's, simplify it.
1654 if (C1->getType()->isIntegerTy(1)) {
1656 case ICmpInst::ICMP_EQ:
1657 if (isa<ConstantInt>(C2))
1658 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1659 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1660 case ICmpInst::ICMP_NE:
1661 return ConstantExpr::getXor(C1, C2);
1667 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1668 APInt V1 = cast<ConstantInt>(C1)->getValue();
1669 APInt V2 = cast<ConstantInt>(C2)->getValue();
1671 default: llvm_unreachable("Invalid ICmp Predicate");
1672 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1673 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1674 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1675 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1676 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1677 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1678 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1679 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1680 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1681 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1683 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1684 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1685 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1686 APFloat::cmpResult R = C1V.compare(C2V);
1688 default: llvm_unreachable("Invalid FCmp Predicate");
1689 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1690 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1691 case FCmpInst::FCMP_UNO:
1692 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1693 case FCmpInst::FCMP_ORD:
1694 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1695 case FCmpInst::FCMP_UEQ:
1696 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1697 R==APFloat::cmpEqual);
1698 case FCmpInst::FCMP_OEQ:
1699 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1700 case FCmpInst::FCMP_UNE:
1701 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1702 case FCmpInst::FCMP_ONE:
1703 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1704 R==APFloat::cmpGreaterThan);
1705 case FCmpInst::FCMP_ULT:
1706 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1707 R==APFloat::cmpLessThan);
1708 case FCmpInst::FCMP_OLT:
1709 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1710 case FCmpInst::FCMP_UGT:
1711 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1712 R==APFloat::cmpGreaterThan);
1713 case FCmpInst::FCMP_OGT:
1714 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1715 case FCmpInst::FCMP_ULE:
1716 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1717 case FCmpInst::FCMP_OLE:
1718 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1719 R==APFloat::cmpEqual);
1720 case FCmpInst::FCMP_UGE:
1721 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1722 case FCmpInst::FCMP_OGE:
1723 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1724 R==APFloat::cmpEqual);
1726 } else if (C1->getType()->isVectorTy()) {
1727 // If we can constant fold the comparison of each element, constant fold
1728 // the whole vector comparison.
1729 SmallVector<Constant*, 4> ResElts;
1730 Type *Ty = IntegerType::get(C1->getContext(), 32);
1731 // Compare the elements, producing an i1 result or constant expr.
1732 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1734 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1736 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1738 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1741 return ConstantVector::get(ResElts);
1744 if (C1->getType()->isFloatingPointTy()) {
1745 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1746 switch (evaluateFCmpRelation(C1, C2)) {
1747 default: llvm_unreachable("Unknown relation!");
1748 case FCmpInst::FCMP_UNO:
1749 case FCmpInst::FCMP_ORD:
1750 case FCmpInst::FCMP_UEQ:
1751 case FCmpInst::FCMP_UNE:
1752 case FCmpInst::FCMP_ULT:
1753 case FCmpInst::FCMP_UGT:
1754 case FCmpInst::FCMP_ULE:
1755 case FCmpInst::FCMP_UGE:
1756 case FCmpInst::FCMP_TRUE:
1757 case FCmpInst::FCMP_FALSE:
1758 case FCmpInst::BAD_FCMP_PREDICATE:
1759 break; // Couldn't determine anything about these constants.
1760 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1761 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1762 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1763 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1765 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1766 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1767 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1768 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1770 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1771 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1772 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1773 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1775 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1776 // We can only partially decide this relation.
1777 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1779 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1782 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1783 // We can only partially decide this relation.
1784 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1786 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1789 case FCmpInst::FCMP_ONE: // We know that C1 != C2
1790 // We can only partially decide this relation.
1791 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1793 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1798 // If we evaluated the result, return it now.
1800 return ConstantInt::get(ResultTy, Result);
1803 // Evaluate the relation between the two constants, per the predicate.
1804 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1805 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1806 default: llvm_unreachable("Unknown relational!");
1807 case ICmpInst::BAD_ICMP_PREDICATE:
1808 break; // Couldn't determine anything about these constants.
1809 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1810 // If we know the constants are equal, we can decide the result of this
1811 // computation precisely.
1812 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1814 case ICmpInst::ICMP_ULT:
1816 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1818 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1822 case ICmpInst::ICMP_SLT:
1824 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1826 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1830 case ICmpInst::ICMP_UGT:
1832 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1834 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1838 case ICmpInst::ICMP_SGT:
1840 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1842 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1846 case ICmpInst::ICMP_ULE:
1847 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1848 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1850 case ICmpInst::ICMP_SLE:
1851 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1852 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1854 case ICmpInst::ICMP_UGE:
1855 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1856 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1858 case ICmpInst::ICMP_SGE:
1859 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1860 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1862 case ICmpInst::ICMP_NE:
1863 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1864 if (pred == ICmpInst::ICMP_NE) Result = 1;
1868 // If we evaluated the result, return it now.
1870 return ConstantInt::get(ResultTy, Result);
1872 // If the right hand side is a bitcast, try using its inverse to simplify
1873 // it by moving it to the left hand side. We can't do this if it would turn
1874 // a vector compare into a scalar compare or visa versa.
1875 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1876 Constant *CE2Op0 = CE2->getOperand(0);
1877 if (CE2->getOpcode() == Instruction::BitCast &&
1878 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1879 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1880 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1884 // If the left hand side is an extension, try eliminating it.
1885 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1886 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1887 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1888 Constant *CE1Op0 = CE1->getOperand(0);
1889 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1890 if (CE1Inverse == CE1Op0) {
1891 // Check whether we can safely truncate the right hand side.
1892 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1893 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
1894 C2->getType()) == C2)
1895 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1900 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1901 (C1->isNullValue() && !C2->isNullValue())) {
1902 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1903 // other way if possible.
1904 // Also, if C1 is null and C2 isn't, flip them around.
1905 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1906 return ConstantExpr::getICmp(pred, C2, C1);
1912 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1914 template<typename IndexTy>
1915 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1916 // No indices means nothing that could be out of bounds.
1917 if (Idxs.empty()) return true;
1919 // If the first index is zero, it's in bounds.
1920 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1922 // If the first index is one and all the rest are zero, it's in bounds,
1923 // by the one-past-the-end rule.
1924 if (!cast<ConstantInt>(Idxs[0])->isOne())
1926 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1927 if (!cast<Constant>(Idxs[i])->isNullValue())
1932 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
1933 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
1934 const ConstantInt *CI) {
1935 if (const PointerType *PTy = dyn_cast<PointerType>(STy))
1936 // Only handle pointers to sized types, not pointers to functions.
1937 return PTy->getElementType()->isSized();
1939 uint64_t NumElements = 0;
1940 // Determine the number of elements in our sequential type.
1941 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
1942 NumElements = ATy->getNumElements();
1943 else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
1944 NumElements = VTy->getNumElements();
1946 assert((isa<ArrayType>(STy) || NumElements > 0) &&
1947 "didn't expect non-array type to have zero elements!");
1949 // We cannot bounds check the index if it doesn't fit in an int64_t.
1950 if (CI->getValue().getActiveBits() > 64)
1953 // A negative index or an index past the end of our sequential type is
1954 // considered out-of-range.
1955 int64_t IndexVal = CI->getSExtValue();
1956 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
1959 // Otherwise, it is in-range.
1963 template<typename IndexTy>
1964 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1966 ArrayRef<IndexTy> Idxs) {
1967 if (Idxs.empty()) return C;
1968 Constant *Idx0 = cast<Constant>(Idxs[0]);
1969 if ((Idxs.size() == 1 && Idx0->isNullValue()))
1972 if (isa<UndefValue>(C)) {
1973 PointerType *Ptr = cast<PointerType>(C->getType());
1974 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1975 assert(Ty && "Invalid indices for GEP!");
1976 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1979 if (C->isNullValue()) {
1981 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1982 if (!cast<Constant>(Idxs[i])->isNullValue()) {
1987 PointerType *Ptr = cast<PointerType>(C->getType());
1988 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1989 assert(Ty && "Invalid indices for GEP!");
1990 return ConstantPointerNull::get(PointerType::get(Ty,
1991 Ptr->getAddressSpace()));
1995 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1996 // Combine Indices - If the source pointer to this getelementptr instruction
1997 // is a getelementptr instruction, combine the indices of the two
1998 // getelementptr instructions into a single instruction.
2000 if (CE->getOpcode() == Instruction::GetElementPtr) {
2001 Type *LastTy = nullptr;
2002 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2006 // We cannot combine indices if doing so would take us outside of an
2007 // array or vector. Doing otherwise could trick us if we evaluated such a
2008 // GEP as part of a load.
2010 // e.g. Consider if the original GEP was:
2011 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2012 // i32 0, i32 0, i64 0)
2014 // If we then tried to offset it by '8' to get to the third element,
2015 // an i8, we should *not* get:
2016 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2017 // i32 0, i32 0, i64 8)
2019 // This GEP tries to index array element '8 which runs out-of-bounds.
2020 // Subsequent evaluation would get confused and produce erroneous results.
2022 // The following prohibits such a GEP from being formed by checking to see
2023 // if the index is in-range with respect to an array or vector.
2024 bool PerformFold = false;
2025 if (Idx0->isNullValue())
2027 else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
2028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2029 PerformFold = isIndexInRangeOfSequentialType(STy, CI);
2032 SmallVector<Value*, 16> NewIndices;
2033 NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2034 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2035 NewIndices.push_back(CE->getOperand(i));
2037 // Add the last index of the source with the first index of the new GEP.
2038 // Make sure to handle the case when they are actually different types.
2039 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2040 // Otherwise it must be an array.
2041 if (!Idx0->isNullValue()) {
2042 Type *IdxTy = Combined->getType();
2043 if (IdxTy != Idx0->getType()) {
2044 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2045 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2046 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2047 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2050 ConstantExpr::get(Instruction::Add, Idx0, Combined);
2054 NewIndices.push_back(Combined);
2055 NewIndices.append(Idxs.begin() + 1, Idxs.end());
2057 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
2059 cast<GEPOperator>(CE)->isInBounds());
2063 // Attempt to fold casts to the same type away. For example, folding:
2065 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2069 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2071 // Don't fold if the cast is changing address spaces.
2072 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2073 PointerType *SrcPtrTy =
2074 dyn_cast<PointerType>(CE->getOperand(0)->getType());
2075 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2076 if (SrcPtrTy && DstPtrTy) {
2077 ArrayType *SrcArrayTy =
2078 dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2079 ArrayType *DstArrayTy =
2080 dyn_cast<ArrayType>(DstPtrTy->getElementType());
2081 if (SrcArrayTy && DstArrayTy
2082 && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2083 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2084 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
2090 // Check to see if any array indices are not within the corresponding
2091 // notional array or vector bounds. If so, try to determine if they can be
2092 // factored out into preceding dimensions.
2093 bool Unknown = false;
2094 SmallVector<Constant *, 8> NewIdxs;
2095 Type *Ty = C->getType();
2096 Type *Prev = nullptr;
2097 for (unsigned i = 0, e = Idxs.size(); i != e;
2098 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2099 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2100 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
2101 if (CI->getSExtValue() > 0 &&
2102 !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
2103 if (isa<SequentialType>(Prev)) {
2104 // It's out of range, but we can factor it into the prior
2106 NewIdxs.resize(Idxs.size());
2107 uint64_t NumElements = 0;
2108 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2109 NumElements = ATy->getNumElements();
2111 NumElements = cast<VectorType>(Ty)->getNumElements();
2113 ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
2114 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2116 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2117 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2119 // Before adding, extend both operands to i64 to avoid
2120 // overflow trouble.
2121 if (!PrevIdx->getType()->isIntegerTy(64))
2122 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2123 Type::getInt64Ty(Div->getContext()));
2124 if (!Div->getType()->isIntegerTy(64))
2125 Div = ConstantExpr::getSExt(Div,
2126 Type::getInt64Ty(Div->getContext()));
2128 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2130 // It's out of range, but the prior dimension is a struct
2131 // so we can't do anything about it.
2136 // We don't know if it's in range or not.
2141 // If we did any factoring, start over with the adjusted indices.
2142 if (!NewIdxs.empty()) {
2143 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2144 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2145 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2148 // If all indices are known integers and normalized, we can do a simple
2149 // check for the "inbounds" property.
2150 if (!Unknown && !inBounds)
2151 if (auto *GV = dyn_cast<GlobalVariable>(C))
2152 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2153 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2158 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2160 ArrayRef<Constant *> Idxs) {
2161 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2164 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2166 ArrayRef<Value *> Idxs) {
2167 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);