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 ConstantVector node to the
42 /// specified vector type. At this point, we know that the elements of the
43 /// input vector constant are all simple integer or FP values.
44 static Constant
*BitCastConstantVector(ConstantVector
*CV
,
45 const VectorType
*DstTy
) {
47 if (CV
->isAllOnesValue()) return Constant::getAllOnesValue(DstTy
);
48 if (CV
->isNullValue()) return Constant::getNullValue(DstTy
);
50 // If this cast changes element count then we can't handle it here:
51 // doing so requires endianness information. This should be handled by
52 // Analysis/ConstantFolding.cpp
53 unsigned NumElts
= DstTy
->getNumElements();
54 if (NumElts
!= CV
->getNumOperands())
57 // Check to verify that all elements of the input are simple.
58 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
59 if (!isa
<ConstantInt
>(CV
->getOperand(i
)) &&
60 !isa
<ConstantFP
>(CV
->getOperand(i
)))
64 // Bitcast each element now.
65 std::vector
<Constant
*> Result
;
66 const Type
*DstEltTy
= DstTy
->getElementType();
67 for (unsigned i
= 0; i
!= NumElts
; ++i
)
68 Result
.push_back(ConstantExpr::getBitCast(CV
->getOperand(i
),
70 return ConstantVector::get(Result
);
73 /// This function determines which opcode to use to fold two constant cast
74 /// expressions together. It uses CastInst::isEliminableCastPair to determine
75 /// the opcode. Consequently its just a wrapper around that function.
76 /// @brief Determine if it is valid to fold a cast of a cast
79 unsigned opc
, ///< opcode of the second cast constant expression
80 ConstantExpr
*Op
, ///< the first cast constant expression
81 const Type
*DstTy
///< desintation type of the first cast
83 assert(Op
&& Op
->isCast() && "Can't fold cast of cast without a cast!");
84 assert(DstTy
&& DstTy
->isFirstClassType() && "Invalid cast destination type");
85 assert(CastInst::isCast(opc
) && "Invalid cast opcode");
87 // The the types and opcodes for the two Cast constant expressions
88 const Type
*SrcTy
= Op
->getOperand(0)->getType();
89 const Type
*MidTy
= Op
->getType();
90 Instruction::CastOps firstOp
= Instruction::CastOps(Op
->getOpcode());
91 Instruction::CastOps secondOp
= Instruction::CastOps(opc
);
93 // Let CastInst::isEliminableCastPair do the heavy lifting.
94 return CastInst::isEliminableCastPair(firstOp
, secondOp
, SrcTy
, MidTy
, DstTy
,
95 Type::getInt64Ty(DstTy
->getContext()));
98 static Constant
*FoldBitCast(Constant
*V
, const Type
*DestTy
) {
99 const Type
*SrcTy
= V
->getType();
101 return V
; // no-op cast
103 // Check to see if we are casting a pointer to an aggregate to a pointer to
104 // the first element. If so, return the appropriate GEP instruction.
105 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(V
->getType()))
106 if (const PointerType
*DPTy
= dyn_cast
<PointerType
>(DestTy
))
107 if (PTy
->getAddressSpace() == DPTy
->getAddressSpace()) {
108 SmallVector
<Value
*, 8> IdxList
;
110 Constant::getNullValue(Type::getInt32Ty(DPTy
->getContext()));
111 IdxList
.push_back(Zero
);
112 const Type
*ElTy
= PTy
->getElementType();
113 while (ElTy
!= DPTy
->getElementType()) {
114 if (const StructType
*STy
= dyn_cast
<StructType
>(ElTy
)) {
115 if (STy
->getNumElements() == 0) break;
116 ElTy
= STy
->getElementType(0);
117 IdxList
.push_back(Zero
);
118 } else if (const SequentialType
*STy
=
119 dyn_cast
<SequentialType
>(ElTy
)) {
120 if (ElTy
->isPointerTy()) break; // Can't index into pointers!
121 ElTy
= STy
->getElementType();
122 IdxList
.push_back(Zero
);
128 if (ElTy
== DPTy
->getElementType())
129 // This GEP is inbounds because all indices are zero.
130 return ConstantExpr::getInBoundsGetElementPtr(V
, &IdxList
[0],
134 // Handle casts from one vector constant to another. We know that the src
135 // and dest type have the same size (otherwise its an illegal cast).
136 if (const VectorType
*DestPTy
= dyn_cast
<VectorType
>(DestTy
)) {
137 if (const VectorType
*SrcTy
= dyn_cast
<VectorType
>(V
->getType())) {
138 assert(DestPTy
->getBitWidth() == SrcTy
->getBitWidth() &&
139 "Not cast between same sized vectors!");
141 // First, check for null. Undef is already handled.
142 if (isa
<ConstantAggregateZero
>(V
))
143 return Constant::getNullValue(DestTy
);
145 if (ConstantVector
*CV
= dyn_cast
<ConstantVector
>(V
))
146 return BitCastConstantVector(CV
, DestPTy
);
149 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
150 // This allows for other simplifications (although some of them
151 // can only be handled by Analysis/ConstantFolding.cpp).
152 if (isa
<ConstantInt
>(V
) || isa
<ConstantFP
>(V
))
153 return ConstantExpr::getBitCast(ConstantVector::get(V
), DestPTy
);
156 // Finally, implement bitcast folding now. The code below doesn't handle
158 if (isa
<ConstantPointerNull
>(V
)) // ptr->ptr cast.
159 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
161 // Handle integral constant input.
162 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
163 if (DestTy
->isIntegerTy())
164 // Integral -> Integral. This is a no-op because the bit widths must
165 // be the same. Consequently, we just fold to V.
168 if (DestTy
->isFloatingPointTy())
169 return ConstantFP::get(DestTy
->getContext(),
170 APFloat(CI
->getValue(),
171 !DestTy
->isPPC_FP128Ty()));
173 // Otherwise, can't fold this (vector?)
177 // Handle ConstantFP input: FP -> Integral.
178 if (ConstantFP
*FP
= dyn_cast
<ConstantFP
>(V
))
179 return ConstantInt::get(FP
->getContext(),
180 FP
->getValueAPF().bitcastToAPInt());
186 /// ExtractConstantBytes - V is an integer constant which only has a subset of
187 /// its bytes used. The bytes used are indicated by ByteStart (which is the
188 /// first byte used, counting from the least significant byte) and ByteSize,
189 /// which is the number of bytes used.
191 /// This function analyzes the specified constant to see if the specified byte
192 /// range can be returned as a simplified constant. If so, the constant is
193 /// returned, otherwise null is returned.
195 static Constant
*ExtractConstantBytes(Constant
*C
, unsigned ByteStart
,
197 assert(C
->getType()->isIntegerTy() &&
198 (cast
<IntegerType
>(C
->getType())->getBitWidth() & 7) == 0 &&
199 "Non-byte sized integer input");
200 unsigned CSize
= cast
<IntegerType
>(C
->getType())->getBitWidth()/8;
201 assert(ByteSize
&& "Must be accessing some piece");
202 assert(ByteStart
+ByteSize
<= CSize
&& "Extracting invalid piece from input");
203 assert(ByteSize
!= CSize
&& "Should not extract everything");
205 // Constant Integers are simple.
206 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(C
)) {
207 APInt V
= CI
->getValue();
209 V
= V
.lshr(ByteStart
*8);
210 V
= V
.trunc(ByteSize
*8);
211 return ConstantInt::get(CI
->getContext(), V
);
214 // In the input is a constant expr, we might be able to recursively simplify.
215 // If not, we definitely can't do anything.
216 ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
);
217 if (CE
== 0) return 0;
219 switch (CE
->getOpcode()) {
221 case Instruction::Or
: {
222 Constant
*RHS
= ExtractConstantBytes(CE
->getOperand(1), ByteStart
,ByteSize
);
227 if (ConstantInt
*RHSC
= dyn_cast
<ConstantInt
>(RHS
))
228 if (RHSC
->isAllOnesValue())
231 Constant
*LHS
= ExtractConstantBytes(CE
->getOperand(0), ByteStart
,ByteSize
);
234 return ConstantExpr::getOr(LHS
, RHS
);
236 case Instruction::And
: {
237 Constant
*RHS
= ExtractConstantBytes(CE
->getOperand(1), ByteStart
,ByteSize
);
242 if (RHS
->isNullValue())
245 Constant
*LHS
= ExtractConstantBytes(CE
->getOperand(0), ByteStart
,ByteSize
);
248 return ConstantExpr::getAnd(LHS
, RHS
);
250 case Instruction::LShr
: {
251 ConstantInt
*Amt
= dyn_cast
<ConstantInt
>(CE
->getOperand(1));
254 unsigned ShAmt
= Amt
->getZExtValue();
255 // Cannot analyze non-byte shifts.
256 if ((ShAmt
& 7) != 0)
260 // If the extract is known to be all zeros, return zero.
261 if (ByteStart
>= CSize
-ShAmt
)
262 return Constant::getNullValue(IntegerType::get(CE
->getContext(),
264 // If the extract is known to be fully in the input, extract it.
265 if (ByteStart
+ByteSize
+ShAmt
<= CSize
)
266 return ExtractConstantBytes(CE
->getOperand(0), ByteStart
+ShAmt
, ByteSize
);
268 // TODO: Handle the 'partially zero' case.
272 case Instruction::Shl
: {
273 ConstantInt
*Amt
= dyn_cast
<ConstantInt
>(CE
->getOperand(1));
276 unsigned ShAmt
= Amt
->getZExtValue();
277 // Cannot analyze non-byte shifts.
278 if ((ShAmt
& 7) != 0)
282 // If the extract is known to be all zeros, return zero.
283 if (ByteStart
+ByteSize
<= ShAmt
)
284 return Constant::getNullValue(IntegerType::get(CE
->getContext(),
286 // If the extract is known to be fully in the input, extract it.
287 if (ByteStart
>= ShAmt
)
288 return ExtractConstantBytes(CE
->getOperand(0), ByteStart
-ShAmt
, ByteSize
);
290 // TODO: Handle the 'partially zero' case.
294 case Instruction::ZExt
: {
295 unsigned SrcBitSize
=
296 cast
<IntegerType
>(CE
->getOperand(0)->getType())->getBitWidth();
298 // If extracting something that is completely zero, return 0.
299 if (ByteStart
*8 >= SrcBitSize
)
300 return Constant::getNullValue(IntegerType::get(CE
->getContext(),
303 // If exactly extracting the input, return it.
304 if (ByteStart
== 0 && ByteSize
*8 == SrcBitSize
)
305 return CE
->getOperand(0);
307 // If extracting something completely in the input, if if the input is a
308 // multiple of 8 bits, recurse.
309 if ((SrcBitSize
&7) == 0 && (ByteStart
+ByteSize
)*8 <= SrcBitSize
)
310 return ExtractConstantBytes(CE
->getOperand(0), ByteStart
, ByteSize
);
312 // Otherwise, if extracting a subset of the input, which is not multiple of
313 // 8 bits, do a shift and trunc to get the bits.
314 if ((ByteStart
+ByteSize
)*8 < SrcBitSize
) {
315 assert((SrcBitSize
&7) && "Shouldn't get byte sized case here");
316 Constant
*Res
= CE
->getOperand(0);
318 Res
= ConstantExpr::getLShr(Res
,
319 ConstantInt::get(Res
->getType(), ByteStart
*8));
320 return ConstantExpr::getTrunc(Res
, IntegerType::get(C
->getContext(),
324 // TODO: Handle the 'partially zero' case.
330 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
331 /// on Ty, with any known factors factored out. If Folded is false,
332 /// return null if no factoring was possible, to avoid endlessly
333 /// bouncing an unfoldable expression back into the top-level folder.
335 static Constant
*getFoldedSizeOf(const Type
*Ty
, const Type
*DestTy
,
337 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
)) {
338 Constant
*N
= ConstantInt::get(DestTy
, ATy
->getNumElements());
339 Constant
*E
= getFoldedSizeOf(ATy
->getElementType(), DestTy
, true);
340 return ConstantExpr::getNUWMul(E
, N
);
343 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
))
344 if (!STy
->isPacked()) {
345 unsigned NumElems
= STy
->getNumElements();
346 // An empty struct has size zero.
348 return ConstantExpr::getNullValue(DestTy
);
349 // Check for a struct with all members having the same size.
350 Constant
*MemberSize
=
351 getFoldedSizeOf(STy
->getElementType(0), DestTy
, true);
353 for (unsigned i
= 1; i
!= NumElems
; ++i
)
355 getFoldedSizeOf(STy
->getElementType(i
), DestTy
, true)) {
360 Constant
*N
= ConstantInt::get(DestTy
, NumElems
);
361 return ConstantExpr::getNUWMul(MemberSize
, N
);
365 // Pointer size doesn't depend on the pointee type, so canonicalize them
366 // to an arbitrary pointee.
367 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
))
368 if (!PTy
->getElementType()->isIntegerTy(1))
370 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy
->getContext(), 1),
371 PTy
->getAddressSpace()),
374 // If there's no interesting folding happening, bail so that we don't create
375 // a constant that looks like it needs folding but really doesn't.
379 // Base case: Get a regular sizeof expression.
380 Constant
*C
= ConstantExpr::getSizeOf(Ty
);
381 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
387 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
388 /// on Ty, with any known factors factored out. If Folded is false,
389 /// return null if no factoring was possible, to avoid endlessly
390 /// bouncing an unfoldable expression back into the top-level folder.
392 static Constant
*getFoldedAlignOf(const Type
*Ty
, const Type
*DestTy
,
394 // The alignment of an array is equal to the alignment of the
395 // array element. Note that this is not always true for vectors.
396 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
)) {
397 Constant
*C
= ConstantExpr::getAlignOf(ATy
->getElementType());
398 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
405 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
)) {
406 // Packed structs always have an alignment of 1.
408 return ConstantInt::get(DestTy
, 1);
410 // Otherwise, struct alignment is the maximum alignment of any member.
411 // Without target data, we can't compare much, but we can check to see
412 // if all the members have the same alignment.
413 unsigned NumElems
= STy
->getNumElements();
414 // An empty struct has minimal alignment.
416 return ConstantInt::get(DestTy
, 1);
417 // Check for a struct with all members having the same alignment.
418 Constant
*MemberAlign
=
419 getFoldedAlignOf(STy
->getElementType(0), DestTy
, true);
421 for (unsigned i
= 1; i
!= NumElems
; ++i
)
422 if (MemberAlign
!= getFoldedAlignOf(STy
->getElementType(i
), DestTy
, true)) {
430 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
431 // to an arbitrary pointee.
432 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
))
433 if (!PTy
->getElementType()->isIntegerTy(1))
435 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy
->getContext(),
437 PTy
->getAddressSpace()),
440 // If there's no interesting folding happening, bail so that we don't create
441 // a constant that looks like it needs folding but really doesn't.
445 // Base case: Get a regular alignof expression.
446 Constant
*C
= ConstantExpr::getAlignOf(Ty
);
447 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
453 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
454 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
455 /// return null if no factoring was possible, to avoid endlessly
456 /// bouncing an unfoldable expression back into the top-level folder.
458 static Constant
*getFoldedOffsetOf(const Type
*Ty
, Constant
*FieldNo
,
461 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
)) {
462 Constant
*N
= ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo
, false,
465 Constant
*E
= getFoldedSizeOf(ATy
->getElementType(), DestTy
, true);
466 return ConstantExpr::getNUWMul(E
, N
);
469 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
))
470 if (!STy
->isPacked()) {
471 unsigned NumElems
= STy
->getNumElements();
472 // An empty struct has no members.
475 // Check for a struct with all members having the same size.
476 Constant
*MemberSize
=
477 getFoldedSizeOf(STy
->getElementType(0), DestTy
, true);
479 for (unsigned i
= 1; i
!= NumElems
; ++i
)
481 getFoldedSizeOf(STy
->getElementType(i
), DestTy
, true)) {
486 Constant
*N
= ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo
,
491 return ConstantExpr::getNUWMul(MemberSize
, N
);
495 // If there's no interesting folding happening, bail so that we don't create
496 // a constant that looks like it needs folding but really doesn't.
500 // Base case: Get a regular offsetof expression.
501 Constant
*C
= ConstantExpr::getOffsetOf(Ty
, FieldNo
);
502 C
= ConstantExpr::getCast(CastInst::getCastOpcode(C
, false,
508 Constant
*llvm::ConstantFoldCastInstruction(unsigned opc
, Constant
*V
,
509 const Type
*DestTy
) {
510 if (isa
<UndefValue
>(V
)) {
511 // zext(undef) = 0, because the top bits will be zero.
512 // sext(undef) = 0, because the top bits will all be the same.
513 // [us]itofp(undef) = 0, because the result value is bounded.
514 if (opc
== Instruction::ZExt
|| opc
== Instruction::SExt
||
515 opc
== Instruction::UIToFP
|| opc
== Instruction::SIToFP
)
516 return Constant::getNullValue(DestTy
);
517 return UndefValue::get(DestTy
);
520 // No compile-time operations on this type yet.
521 if (V
->getType()->isPPC_FP128Ty() || DestTy
->isPPC_FP128Ty())
524 if (V
->isNullValue() && !DestTy
->isX86_MMXTy())
525 return Constant::getNullValue(DestTy
);
527 // If the cast operand is a constant expression, there's a few things we can
528 // do to try to simplify it.
529 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
)) {
531 // Try hard to fold cast of cast because they are often eliminable.
532 if (unsigned newOpc
= foldConstantCastPair(opc
, CE
, DestTy
))
533 return ConstantExpr::getCast(newOpc
, CE
->getOperand(0), DestTy
);
534 } else if (CE
->getOpcode() == Instruction::GetElementPtr
) {
535 // If all of the indexes in the GEP are null values, there is no pointer
536 // adjustment going on. We might as well cast the source pointer.
537 bool isAllNull
= true;
538 for (unsigned i
= 1, e
= CE
->getNumOperands(); i
!= e
; ++i
)
539 if (!CE
->getOperand(i
)->isNullValue()) {
544 // This is casting one pointer type to another, always BitCast
545 return ConstantExpr::getPointerCast(CE
->getOperand(0), DestTy
);
549 // If the cast operand is a constant vector, perform the cast by
550 // operating on each element. In the cast of bitcasts, the element
551 // count may be mismatched; don't attempt to handle that here.
552 if (ConstantVector
*CV
= dyn_cast
<ConstantVector
>(V
))
553 if (DestTy
->isVectorTy() &&
554 cast
<VectorType
>(DestTy
)->getNumElements() ==
555 CV
->getType()->getNumElements()) {
556 std::vector
<Constant
*> res
;
557 const VectorType
*DestVecTy
= cast
<VectorType
>(DestTy
);
558 const Type
*DstEltTy
= DestVecTy
->getElementType();
559 for (unsigned i
= 0, e
= CV
->getType()->getNumElements(); i
!= e
; ++i
)
560 res
.push_back(ConstantExpr::getCast(opc
,
561 CV
->getOperand(i
), DstEltTy
));
562 return ConstantVector::get(res
);
565 // We actually have to do a cast now. Perform the cast according to the
569 llvm_unreachable("Failed to cast constant expression");
570 case Instruction::FPTrunc
:
571 case Instruction::FPExt
:
572 if (ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
574 APFloat Val
= FPC
->getValueAPF();
575 Val
.convert(DestTy
->isFloatTy() ? APFloat::IEEEsingle
:
576 DestTy
->isDoubleTy() ? APFloat::IEEEdouble
:
577 DestTy
->isX86_FP80Ty() ? APFloat::x87DoubleExtended
:
578 DestTy
->isFP128Ty() ? APFloat::IEEEquad
:
580 APFloat::rmNearestTiesToEven
, &ignored
);
581 return ConstantFP::get(V
->getContext(), Val
);
583 return 0; // Can't fold.
584 case Instruction::FPToUI
:
585 case Instruction::FPToSI
:
586 if (ConstantFP
*FPC
= dyn_cast
<ConstantFP
>(V
)) {
587 const APFloat
&V
= FPC
->getValueAPF();
590 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
591 (void) V
.convertToInteger(x
, DestBitWidth
, opc
==Instruction::FPToSI
,
592 APFloat::rmTowardZero
, &ignored
);
593 APInt
Val(DestBitWidth
, 2, x
);
594 return ConstantInt::get(FPC
->getContext(), Val
);
596 return 0; // Can't fold.
597 case Instruction::IntToPtr
: //always treated as unsigned
598 if (V
->isNullValue()) // Is it an integral null value?
599 return ConstantPointerNull::get(cast
<PointerType
>(DestTy
));
600 return 0; // Other pointer types cannot be casted
601 case Instruction::PtrToInt
: // always treated as unsigned
602 // Is it a null pointer value?
603 if (V
->isNullValue())
604 return ConstantInt::get(DestTy
, 0);
605 // If this is a sizeof-like expression, pull out multiplications by
606 // known factors to expose them to subsequent folding. If it's an
607 // alignof-like expression, factor out known factors.
608 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(V
))
609 if (CE
->getOpcode() == Instruction::GetElementPtr
&&
610 CE
->getOperand(0)->isNullValue()) {
612 cast
<PointerType
>(CE
->getOperand(0)->getType())->getElementType();
613 if (CE
->getNumOperands() == 2) {
614 // Handle a sizeof-like expression.
615 Constant
*Idx
= CE
->getOperand(1);
616 bool isOne
= isa
<ConstantInt
>(Idx
) && cast
<ConstantInt
>(Idx
)->isOne();
617 if (Constant
*C
= getFoldedSizeOf(Ty
, DestTy
, !isOne
)) {
618 Idx
= ConstantExpr::getCast(CastInst::getCastOpcode(Idx
, true,
621 return ConstantExpr::getMul(C
, Idx
);
623 } else if (CE
->getNumOperands() == 3 &&
624 CE
->getOperand(1)->isNullValue()) {
625 // Handle an alignof-like expression.
626 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
))
627 if (!STy
->isPacked()) {
628 ConstantInt
*CI
= cast
<ConstantInt
>(CE
->getOperand(2));
630 STy
->getNumElements() == 2 &&
631 STy
->getElementType(0)->isIntegerTy(1)) {
632 return getFoldedAlignOf(STy
->getElementType(1), DestTy
, false);
635 // Handle an offsetof-like expression.
636 if (Ty
->isStructTy() || Ty
->isArrayTy()) {
637 if (Constant
*C
= getFoldedOffsetOf(Ty
, CE
->getOperand(2),
643 // Other pointer types cannot be casted
645 case Instruction::UIToFP
:
646 case Instruction::SIToFP
:
647 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
648 APInt api
= CI
->getValue();
649 APFloat
apf(APInt::getNullValue(DestTy
->getPrimitiveSizeInBits()), true);
650 (void)apf
.convertFromAPInt(api
,
651 opc
==Instruction::SIToFP
,
652 APFloat::rmNearestTiesToEven
);
653 return ConstantFP::get(V
->getContext(), apf
);
656 case Instruction::ZExt
:
657 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
658 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
659 return ConstantInt::get(V
->getContext(),
660 CI
->getValue().zext(BitWidth
));
663 case Instruction::SExt
:
664 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
665 uint32_t BitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
666 return ConstantInt::get(V
->getContext(),
667 CI
->getValue().sext(BitWidth
));
670 case Instruction::Trunc
: {
671 uint32_t DestBitWidth
= cast
<IntegerType
>(DestTy
)->getBitWidth();
672 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(V
)) {
673 return ConstantInt::get(V
->getContext(),
674 CI
->getValue().trunc(DestBitWidth
));
677 // The input must be a constantexpr. See if we can simplify this based on
678 // the bytes we are demanding. Only do this if the source and dest are an
679 // even multiple of a byte.
680 if ((DestBitWidth
& 7) == 0 &&
681 (cast
<IntegerType
>(V
->getType())->getBitWidth() & 7) == 0)
682 if (Constant
*Res
= ExtractConstantBytes(V
, 0, DestBitWidth
/ 8))
687 case Instruction::BitCast
:
688 return FoldBitCast(V
, DestTy
);
692 Constant
*llvm::ConstantFoldSelectInstruction(Constant
*Cond
,
693 Constant
*V1
, Constant
*V2
) {
694 if (ConstantInt
*CB
= dyn_cast
<ConstantInt
>(Cond
))
695 return CB
->getZExtValue() ? V1
: V2
;
697 // Check for zero aggregate and ConstantVector of zeros
698 if (Cond
->isNullValue()) return V2
;
700 if (ConstantVector
* CondV
= dyn_cast
<ConstantVector
>(Cond
)) {
702 if (CondV
->isAllOnesValue()) return V1
;
704 const VectorType
*VTy
= cast
<VectorType
>(V1
->getType());
705 ConstantVector
*CP1
= dyn_cast
<ConstantVector
>(V1
);
706 ConstantVector
*CP2
= dyn_cast
<ConstantVector
>(V2
);
708 if ((CP1
|| isa
<ConstantAggregateZero
>(V1
)) &&
709 (CP2
|| isa
<ConstantAggregateZero
>(V2
))) {
711 // Find the element type of the returned vector
712 const Type
*EltTy
= VTy
->getElementType();
713 unsigned NumElem
= VTy
->getNumElements();
714 std::vector
<Constant
*> Res(NumElem
);
717 for (unsigned i
= 0; i
< NumElem
; ++i
) {
718 ConstantInt
* c
= dyn_cast
<ConstantInt
>(CondV
->getOperand(i
));
723 Constant
*C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
724 Constant
*C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
725 Res
[i
] = c
->getZExtValue() ? C1
: C2
;
727 // If we were able to build the vector, return it
728 if (Valid
) return ConstantVector::get(Res
);
733 if (isa
<UndefValue
>(Cond
)) {
734 if (isa
<UndefValue
>(V1
)) return V1
;
737 if (isa
<UndefValue
>(V1
)) return V2
;
738 if (isa
<UndefValue
>(V2
)) return V1
;
739 if (V1
== V2
) return V1
;
741 if (ConstantExpr
*TrueVal
= dyn_cast
<ConstantExpr
>(V1
)) {
742 if (TrueVal
->getOpcode() == Instruction::Select
)
743 if (TrueVal
->getOperand(0) == Cond
)
744 return ConstantExpr::getSelect(Cond
, TrueVal
->getOperand(1), V2
);
746 if (ConstantExpr
*FalseVal
= dyn_cast
<ConstantExpr
>(V2
)) {
747 if (FalseVal
->getOpcode() == Instruction::Select
)
748 if (FalseVal
->getOperand(0) == Cond
)
749 return ConstantExpr::getSelect(Cond
, V1
, FalseVal
->getOperand(2));
755 Constant
*llvm::ConstantFoldExtractElementInstruction(Constant
*Val
,
757 if (isa
<UndefValue
>(Val
)) // ee(undef, x) -> undef
758 return UndefValue::get(cast
<VectorType
>(Val
->getType())->getElementType());
759 if (Val
->isNullValue()) // ee(zero, x) -> zero
760 return Constant::getNullValue(
761 cast
<VectorType
>(Val
->getType())->getElementType());
763 if (ConstantVector
*CVal
= dyn_cast
<ConstantVector
>(Val
)) {
764 if (ConstantInt
*CIdx
= dyn_cast
<ConstantInt
>(Idx
)) {
765 return CVal
->getOperand(CIdx
->getZExtValue());
766 } else if (isa
<UndefValue
>(Idx
)) {
767 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
768 return CVal
->getOperand(0);
774 Constant
*llvm::ConstantFoldInsertElementInstruction(Constant
*Val
,
777 ConstantInt
*CIdx
= dyn_cast
<ConstantInt
>(Idx
);
779 APInt idxVal
= CIdx
->getValue();
780 if (isa
<UndefValue
>(Val
)) {
781 // Insertion of scalar constant into vector undef
782 // Optimize away insertion of undef
783 if (isa
<UndefValue
>(Elt
))
785 // Otherwise break the aggregate undef into multiple undefs and do
788 cast
<VectorType
>(Val
->getType())->getNumElements();
789 std::vector
<Constant
*> Ops
;
791 for (unsigned i
= 0; i
< numOps
; ++i
) {
793 (idxVal
== i
) ? Elt
: UndefValue::get(Elt
->getType());
796 return ConstantVector::get(Ops
);
798 if (isa
<ConstantAggregateZero
>(Val
)) {
799 // Insertion of scalar constant into vector aggregate zero
800 // Optimize away insertion of zero
801 if (Elt
->isNullValue())
803 // Otherwise break the aggregate zero into multiple zeros and do
806 cast
<VectorType
>(Val
->getType())->getNumElements();
807 std::vector
<Constant
*> Ops
;
809 for (unsigned i
= 0; i
< numOps
; ++i
) {
811 (idxVal
== i
) ? Elt
: Constant::getNullValue(Elt
->getType());
814 return ConstantVector::get(Ops
);
816 if (ConstantVector
*CVal
= dyn_cast
<ConstantVector
>(Val
)) {
817 // Insertion of scalar constant into vector constant
818 std::vector
<Constant
*> Ops
;
819 Ops
.reserve(CVal
->getNumOperands());
820 for (unsigned i
= 0; i
< CVal
->getNumOperands(); ++i
) {
822 (idxVal
== i
) ? Elt
: cast
<Constant
>(CVal
->getOperand(i
));
825 return ConstantVector::get(Ops
);
831 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
832 /// return the specified element value. Otherwise return null.
833 static Constant
*GetVectorElement(Constant
*C
, unsigned EltNo
) {
834 if (ConstantVector
*CV
= dyn_cast
<ConstantVector
>(C
))
835 return CV
->getOperand(EltNo
);
837 const Type
*EltTy
= cast
<VectorType
>(C
->getType())->getElementType();
838 if (isa
<ConstantAggregateZero
>(C
))
839 return Constant::getNullValue(EltTy
);
840 if (isa
<UndefValue
>(C
))
841 return UndefValue::get(EltTy
);
845 Constant
*llvm::ConstantFoldShuffleVectorInstruction(Constant
*V1
,
848 // Undefined shuffle mask -> undefined value.
849 if (isa
<UndefValue
>(Mask
)) return UndefValue::get(V1
->getType());
851 unsigned MaskNumElts
= cast
<VectorType
>(Mask
->getType())->getNumElements();
852 unsigned SrcNumElts
= cast
<VectorType
>(V1
->getType())->getNumElements();
853 const Type
*EltTy
= cast
<VectorType
>(V1
->getType())->getElementType();
855 // Loop over the shuffle mask, evaluating each element.
856 SmallVector
<Constant
*, 32> Result
;
857 for (unsigned i
= 0; i
!= MaskNumElts
; ++i
) {
858 Constant
*InElt
= GetVectorElement(Mask
, i
);
859 if (InElt
== 0) return 0;
861 if (isa
<UndefValue
>(InElt
))
862 InElt
= UndefValue::get(EltTy
);
863 else if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(InElt
)) {
864 unsigned Elt
= CI
->getZExtValue();
865 if (Elt
>= SrcNumElts
*2)
866 InElt
= UndefValue::get(EltTy
);
867 else if (Elt
>= SrcNumElts
)
868 InElt
= GetVectorElement(V2
, Elt
- SrcNumElts
);
870 InElt
= GetVectorElement(V1
, Elt
);
871 if (InElt
== 0) return 0;
876 Result
.push_back(InElt
);
879 return ConstantVector::get(Result
);
882 Constant
*llvm::ConstantFoldExtractValueInstruction(Constant
*Agg
,
883 const unsigned *Idxs
,
885 // Base case: no indices, so return the entire value.
889 if (isa
<UndefValue
>(Agg
)) // ev(undef, x) -> undef
890 return UndefValue::get(ExtractValueInst::getIndexedType(Agg
->getType(),
894 if (isa
<ConstantAggregateZero
>(Agg
)) // ev(0, x) -> 0
896 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg
->getType(),
900 // Otherwise recurse.
901 if (ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(Agg
))
902 return ConstantFoldExtractValueInstruction(CS
->getOperand(*Idxs
),
905 if (ConstantArray
*CA
= dyn_cast
<ConstantArray
>(Agg
))
906 return ConstantFoldExtractValueInstruction(CA
->getOperand(*Idxs
),
908 ConstantVector
*CV
= cast
<ConstantVector
>(Agg
);
909 return ConstantFoldExtractValueInstruction(CV
->getOperand(*Idxs
),
913 Constant
*llvm::ConstantFoldInsertValueInstruction(Constant
*Agg
,
915 const unsigned *Idxs
,
917 // Base case: no indices, so replace the entire value.
921 if (isa
<UndefValue
>(Agg
)) {
922 // Insertion of constant into aggregate undef
923 // Optimize away insertion of undef.
924 if (isa
<UndefValue
>(Val
))
927 // Otherwise break the aggregate undef into multiple undefs and do
929 const CompositeType
*AggTy
= cast
<CompositeType
>(Agg
->getType());
931 if (const ArrayType
*AR
= dyn_cast
<ArrayType
>(AggTy
))
932 numOps
= AR
->getNumElements();
934 numOps
= cast
<StructType
>(AggTy
)->getNumElements();
936 std::vector
<Constant
*> Ops(numOps
);
937 for (unsigned i
= 0; i
< numOps
; ++i
) {
938 const Type
*MemberTy
= AggTy
->getTypeAtIndex(i
);
941 ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy
),
942 Val
, Idxs
+1, NumIdx
-1) :
943 UndefValue::get(MemberTy
);
947 if (const StructType
* ST
= dyn_cast
<StructType
>(AggTy
))
948 return ConstantStruct::get(ST
, Ops
);
949 return ConstantArray::get(cast
<ArrayType
>(AggTy
), Ops
);
952 if (isa
<ConstantAggregateZero
>(Agg
)) {
953 // Insertion of constant into aggregate zero
954 // Optimize away insertion of zero.
955 if (Val
->isNullValue())
958 // Otherwise break the aggregate zero into multiple zeros and do
960 const CompositeType
*AggTy
= cast
<CompositeType
>(Agg
->getType());
962 if (const ArrayType
*AR
= dyn_cast
<ArrayType
>(AggTy
))
963 numOps
= AR
->getNumElements();
965 numOps
= cast
<StructType
>(AggTy
)->getNumElements();
967 std::vector
<Constant
*> Ops(numOps
);
968 for (unsigned i
= 0; i
< numOps
; ++i
) {
969 const Type
*MemberTy
= AggTy
->getTypeAtIndex(i
);
972 ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy
),
973 Val
, Idxs
+1, NumIdx
-1) :
974 Constant::getNullValue(MemberTy
);
978 if (const StructType
*ST
= dyn_cast
<StructType
>(AggTy
))
979 return ConstantStruct::get(ST
, Ops
);
980 return ConstantArray::get(cast
<ArrayType
>(AggTy
), Ops
);
983 if (isa
<ConstantStruct
>(Agg
) || isa
<ConstantArray
>(Agg
)) {
984 // Insertion of constant into aggregate constant.
985 std::vector
<Constant
*> Ops(Agg
->getNumOperands());
986 for (unsigned i
= 0; i
< Agg
->getNumOperands(); ++i
) {
987 Constant
*Op
= cast
<Constant
>(Agg
->getOperand(i
));
989 Op
= ConstantFoldInsertValueInstruction(Op
, Val
, Idxs
+1, NumIdx
-1);
993 if (const StructType
* ST
= dyn_cast
<StructType
>(Agg
->getType()))
994 return ConstantStruct::get(ST
, Ops
);
995 return ConstantArray::get(cast
<ArrayType
>(Agg
->getType()), Ops
);
1002 Constant
*llvm::ConstantFoldBinaryInstruction(unsigned Opcode
,
1003 Constant
*C1
, Constant
*C2
) {
1004 // No compile-time operations on this type yet.
1005 if (C1
->getType()->isPPC_FP128Ty())
1008 // Handle UndefValue up front.
1009 if (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
)) {
1011 case Instruction::Xor
:
1012 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
))
1013 // Handle undef ^ undef -> 0 special case. This is a common
1015 return Constant::getNullValue(C1
->getType());
1017 case Instruction::Add
:
1018 case Instruction::Sub
:
1019 return UndefValue::get(C1
->getType());
1020 case Instruction::And
:
1021 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)) // undef & undef -> undef
1023 return Constant::getNullValue(C1
->getType()); // undef & X -> 0
1024 case Instruction::Mul
: {
1026 // X * undef -> undef if X is odd or undef
1027 if (((CI
= dyn_cast
<ConstantInt
>(C1
)) && CI
->getValue()[0]) ||
1028 ((CI
= dyn_cast
<ConstantInt
>(C2
)) && CI
->getValue()[0]) ||
1029 (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)))
1030 return UndefValue::get(C1
->getType());
1032 // X * undef -> 0 otherwise
1033 return Constant::getNullValue(C1
->getType());
1035 case Instruction::UDiv
:
1036 case Instruction::SDiv
:
1037 // undef / 1 -> undef
1038 if (Opcode
== Instruction::UDiv
|| Opcode
== Instruction::SDiv
)
1039 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
))
1043 case Instruction::URem
:
1044 case Instruction::SRem
:
1045 if (!isa
<UndefValue
>(C2
)) // undef / X -> 0
1046 return Constant::getNullValue(C1
->getType());
1047 return C2
; // X / undef -> undef
1048 case Instruction::Or
: // X | undef -> -1
1049 if (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)) // undef | undef -> undef
1051 return Constant::getAllOnesValue(C1
->getType()); // undef | X -> ~0
1052 case Instruction::LShr
:
1053 if (isa
<UndefValue
>(C2
) && isa
<UndefValue
>(C1
))
1054 return C1
; // undef lshr undef -> undef
1055 return Constant::getNullValue(C1
->getType()); // X lshr undef -> 0
1056 // undef lshr X -> 0
1057 case Instruction::AShr
:
1058 if (!isa
<UndefValue
>(C2
)) // undef ashr X --> all ones
1059 return Constant::getAllOnesValue(C1
->getType());
1060 else if (isa
<UndefValue
>(C1
))
1061 return C1
; // undef ashr undef -> undef
1063 return C1
; // X ashr undef --> X
1064 case Instruction::Shl
:
1065 if (isa
<UndefValue
>(C2
) && isa
<UndefValue
>(C1
))
1066 return C1
; // undef shl undef -> undef
1067 // undef << X -> 0 or X << undef -> 0
1068 return Constant::getNullValue(C1
->getType());
1072 // Handle simplifications when the RHS is a constant int.
1073 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
1075 case Instruction::Add
:
1076 if (CI2
->equalsInt(0)) return C1
; // X + 0 == X
1078 case Instruction::Sub
:
1079 if (CI2
->equalsInt(0)) return C1
; // X - 0 == X
1081 case Instruction::Mul
:
1082 if (CI2
->equalsInt(0)) return C2
; // X * 0 == 0
1083 if (CI2
->equalsInt(1))
1084 return C1
; // X * 1 == X
1086 case Instruction::UDiv
:
1087 case Instruction::SDiv
:
1088 if (CI2
->equalsInt(1))
1089 return C1
; // X / 1 == X
1090 if (CI2
->equalsInt(0))
1091 return UndefValue::get(CI2
->getType()); // X / 0 == undef
1093 case Instruction::URem
:
1094 case Instruction::SRem
:
1095 if (CI2
->equalsInt(1))
1096 return Constant::getNullValue(CI2
->getType()); // X % 1 == 0
1097 if (CI2
->equalsInt(0))
1098 return UndefValue::get(CI2
->getType()); // X % 0 == undef
1100 case Instruction::And
:
1101 if (CI2
->isZero()) return C2
; // X & 0 == 0
1102 if (CI2
->isAllOnesValue())
1103 return C1
; // X & -1 == X
1105 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1106 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1107 if (CE1
->getOpcode() == Instruction::ZExt
) {
1108 unsigned DstWidth
= CI2
->getType()->getBitWidth();
1110 CE1
->getOperand(0)->getType()->getPrimitiveSizeInBits();
1111 APInt
PossiblySetBits(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
1112 if ((PossiblySetBits
& CI2
->getValue()) == PossiblySetBits
)
1116 // If and'ing the address of a global with a constant, fold it.
1117 if (CE1
->getOpcode() == Instruction::PtrToInt
&&
1118 isa
<GlobalValue
>(CE1
->getOperand(0))) {
1119 GlobalValue
*GV
= cast
<GlobalValue
>(CE1
->getOperand(0));
1121 // Functions are at least 4-byte aligned.
1122 unsigned GVAlign
= GV
->getAlignment();
1123 if (isa
<Function
>(GV
))
1124 GVAlign
= std::max(GVAlign
, 4U);
1127 unsigned DstWidth
= CI2
->getType()->getBitWidth();
1128 unsigned SrcWidth
= std::min(DstWidth
, Log2_32(GVAlign
));
1129 APInt
BitsNotSet(APInt::getLowBitsSet(DstWidth
, SrcWidth
));
1131 // If checking bits we know are clear, return zero.
1132 if ((CI2
->getValue() & BitsNotSet
) == CI2
->getValue())
1133 return Constant::getNullValue(CI2
->getType());
1138 case Instruction::Or
:
1139 if (CI2
->equalsInt(0)) return C1
; // X | 0 == X
1140 if (CI2
->isAllOnesValue())
1141 return C2
; // X | -1 == -1
1143 case Instruction::Xor
:
1144 if (CI2
->equalsInt(0)) return C1
; // X ^ 0 == X
1146 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1147 switch (CE1
->getOpcode()) {
1149 case Instruction::ICmp
:
1150 case Instruction::FCmp
:
1151 // cmp pred ^ true -> cmp !pred
1152 assert(CI2
->equalsInt(1));
1153 CmpInst::Predicate pred
= (CmpInst::Predicate
)CE1
->getPredicate();
1154 pred
= CmpInst::getInversePredicate(pred
);
1155 return ConstantExpr::getCompare(pred
, CE1
->getOperand(0),
1156 CE1
->getOperand(1));
1160 case Instruction::AShr
:
1161 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1162 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
))
1163 if (CE1
->getOpcode() == Instruction::ZExt
) // Top bits known zero.
1164 return ConstantExpr::getLShr(C1
, C2
);
1167 } else if (isa
<ConstantInt
>(C1
)) {
1168 // If C1 is a ConstantInt and C2 is not, swap the operands.
1169 if (Instruction::isCommutative(Opcode
))
1170 return ConstantExpr::get(Opcode
, C2
, C1
);
1173 // At this point we know neither constant is an UndefValue.
1174 if (ConstantInt
*CI1
= dyn_cast
<ConstantInt
>(C1
)) {
1175 if (ConstantInt
*CI2
= dyn_cast
<ConstantInt
>(C2
)) {
1176 using namespace APIntOps
;
1177 const APInt
&C1V
= CI1
->getValue();
1178 const APInt
&C2V
= CI2
->getValue();
1182 case Instruction::Add
:
1183 return ConstantInt::get(CI1
->getContext(), C1V
+ C2V
);
1184 case Instruction::Sub
:
1185 return ConstantInt::get(CI1
->getContext(), C1V
- C2V
);
1186 case Instruction::Mul
:
1187 return ConstantInt::get(CI1
->getContext(), C1V
* C2V
);
1188 case Instruction::UDiv
:
1189 assert(!CI2
->isNullValue() && "Div by zero handled above");
1190 return ConstantInt::get(CI1
->getContext(), C1V
.udiv(C2V
));
1191 case Instruction::SDiv
:
1192 assert(!CI2
->isNullValue() && "Div by zero handled above");
1193 if (C2V
.isAllOnesValue() && C1V
.isMinSignedValue())
1194 return UndefValue::get(CI1
->getType()); // MIN_INT / -1 -> undef
1195 return ConstantInt::get(CI1
->getContext(), C1V
.sdiv(C2V
));
1196 case Instruction::URem
:
1197 assert(!CI2
->isNullValue() && "Div by zero handled above");
1198 return ConstantInt::get(CI1
->getContext(), C1V
.urem(C2V
));
1199 case Instruction::SRem
:
1200 assert(!CI2
->isNullValue() && "Div by zero handled above");
1201 if (C2V
.isAllOnesValue() && C1V
.isMinSignedValue())
1202 return UndefValue::get(CI1
->getType()); // MIN_INT % -1 -> undef
1203 return ConstantInt::get(CI1
->getContext(), C1V
.srem(C2V
));
1204 case Instruction::And
:
1205 return ConstantInt::get(CI1
->getContext(), C1V
& C2V
);
1206 case Instruction::Or
:
1207 return ConstantInt::get(CI1
->getContext(), C1V
| C2V
);
1208 case Instruction::Xor
:
1209 return ConstantInt::get(CI1
->getContext(), C1V
^ C2V
);
1210 case Instruction::Shl
: {
1211 uint32_t shiftAmt
= C2V
.getZExtValue();
1212 if (shiftAmt
< C1V
.getBitWidth())
1213 return ConstantInt::get(CI1
->getContext(), C1V
.shl(shiftAmt
));
1215 return UndefValue::get(C1
->getType()); // too big shift is undef
1217 case Instruction::LShr
: {
1218 uint32_t shiftAmt
= C2V
.getZExtValue();
1219 if (shiftAmt
< C1V
.getBitWidth())
1220 return ConstantInt::get(CI1
->getContext(), C1V
.lshr(shiftAmt
));
1222 return UndefValue::get(C1
->getType()); // too big shift is undef
1224 case Instruction::AShr
: {
1225 uint32_t shiftAmt
= C2V
.getZExtValue();
1226 if (shiftAmt
< C1V
.getBitWidth())
1227 return ConstantInt::get(CI1
->getContext(), C1V
.ashr(shiftAmt
));
1229 return UndefValue::get(C1
->getType()); // too big shift is undef
1235 case Instruction::SDiv
:
1236 case Instruction::UDiv
:
1237 case Instruction::URem
:
1238 case Instruction::SRem
:
1239 case Instruction::LShr
:
1240 case Instruction::AShr
:
1241 case Instruction::Shl
:
1242 if (CI1
->equalsInt(0)) return C1
;
1247 } else if (ConstantFP
*CFP1
= dyn_cast
<ConstantFP
>(C1
)) {
1248 if (ConstantFP
*CFP2
= dyn_cast
<ConstantFP
>(C2
)) {
1249 APFloat C1V
= CFP1
->getValueAPF();
1250 APFloat C2V
= CFP2
->getValueAPF();
1251 APFloat C3V
= C1V
; // copy for modification
1255 case Instruction::FAdd
:
1256 (void)C3V
.add(C2V
, APFloat::rmNearestTiesToEven
);
1257 return ConstantFP::get(C1
->getContext(), C3V
);
1258 case Instruction::FSub
:
1259 (void)C3V
.subtract(C2V
, APFloat::rmNearestTiesToEven
);
1260 return ConstantFP::get(C1
->getContext(), C3V
);
1261 case Instruction::FMul
:
1262 (void)C3V
.multiply(C2V
, APFloat::rmNearestTiesToEven
);
1263 return ConstantFP::get(C1
->getContext(), C3V
);
1264 case Instruction::FDiv
:
1265 (void)C3V
.divide(C2V
, APFloat::rmNearestTiesToEven
);
1266 return ConstantFP::get(C1
->getContext(), C3V
);
1267 case Instruction::FRem
:
1268 (void)C3V
.mod(C2V
, APFloat::rmNearestTiesToEven
);
1269 return ConstantFP::get(C1
->getContext(), C3V
);
1272 } else if (const VectorType
*VTy
= dyn_cast
<VectorType
>(C1
->getType())) {
1273 ConstantVector
*CP1
= dyn_cast
<ConstantVector
>(C1
);
1274 ConstantVector
*CP2
= dyn_cast
<ConstantVector
>(C2
);
1275 if ((CP1
!= NULL
|| isa
<ConstantAggregateZero
>(C1
)) &&
1276 (CP2
!= NULL
|| isa
<ConstantAggregateZero
>(C2
))) {
1277 std::vector
<Constant
*> Res
;
1278 const Type
* EltTy
= VTy
->getElementType();
1284 case Instruction::Add
:
1285 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1286 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1287 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1288 Res
.push_back(ConstantExpr::getAdd(C1
, C2
));
1290 return ConstantVector::get(Res
);
1291 case Instruction::FAdd
:
1292 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1293 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1294 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1295 Res
.push_back(ConstantExpr::getFAdd(C1
, C2
));
1297 return ConstantVector::get(Res
);
1298 case Instruction::Sub
:
1299 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1300 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1301 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1302 Res
.push_back(ConstantExpr::getSub(C1
, C2
));
1304 return ConstantVector::get(Res
);
1305 case Instruction::FSub
:
1306 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1307 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1308 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1309 Res
.push_back(ConstantExpr::getFSub(C1
, C2
));
1311 return ConstantVector::get(Res
);
1312 case Instruction::Mul
:
1313 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1314 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1315 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1316 Res
.push_back(ConstantExpr::getMul(C1
, C2
));
1318 return ConstantVector::get(Res
);
1319 case Instruction::FMul
:
1320 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1321 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1322 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1323 Res
.push_back(ConstantExpr::getFMul(C1
, C2
));
1325 return ConstantVector::get(Res
);
1326 case Instruction::UDiv
:
1327 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1328 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1329 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1330 Res
.push_back(ConstantExpr::getUDiv(C1
, C2
));
1332 return ConstantVector::get(Res
);
1333 case Instruction::SDiv
:
1334 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1335 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1336 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1337 Res
.push_back(ConstantExpr::getSDiv(C1
, C2
));
1339 return ConstantVector::get(Res
);
1340 case Instruction::FDiv
:
1341 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1342 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1343 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1344 Res
.push_back(ConstantExpr::getFDiv(C1
, C2
));
1346 return ConstantVector::get(Res
);
1347 case Instruction::URem
:
1348 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1349 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1350 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1351 Res
.push_back(ConstantExpr::getURem(C1
, C2
));
1353 return ConstantVector::get(Res
);
1354 case Instruction::SRem
:
1355 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1356 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1357 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1358 Res
.push_back(ConstantExpr::getSRem(C1
, C2
));
1360 return ConstantVector::get(Res
);
1361 case Instruction::FRem
:
1362 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1363 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1364 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1365 Res
.push_back(ConstantExpr::getFRem(C1
, C2
));
1367 return ConstantVector::get(Res
);
1368 case Instruction::And
:
1369 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1370 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1371 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1372 Res
.push_back(ConstantExpr::getAnd(C1
, C2
));
1374 return ConstantVector::get(Res
);
1375 case Instruction::Or
:
1376 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1377 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1378 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1379 Res
.push_back(ConstantExpr::getOr(C1
, C2
));
1381 return ConstantVector::get(Res
);
1382 case Instruction::Xor
:
1383 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1384 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1385 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1386 Res
.push_back(ConstantExpr::getXor(C1
, C2
));
1388 return ConstantVector::get(Res
);
1389 case Instruction::LShr
:
1390 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1391 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1392 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1393 Res
.push_back(ConstantExpr::getLShr(C1
, C2
));
1395 return ConstantVector::get(Res
);
1396 case Instruction::AShr
:
1397 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1398 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1399 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1400 Res
.push_back(ConstantExpr::getAShr(C1
, C2
));
1402 return ConstantVector::get(Res
);
1403 case Instruction::Shl
:
1404 for (unsigned i
= 0, e
= VTy
->getNumElements(); i
!= e
; ++i
) {
1405 C1
= CP1
? CP1
->getOperand(i
) : Constant::getNullValue(EltTy
);
1406 C2
= CP2
? CP2
->getOperand(i
) : Constant::getNullValue(EltTy
);
1407 Res
.push_back(ConstantExpr::getShl(C1
, C2
));
1409 return ConstantVector::get(Res
);
1414 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
1415 // There are many possible foldings we could do here. We should probably
1416 // at least fold add of a pointer with an integer into the appropriate
1417 // getelementptr. This will improve alias analysis a bit.
1419 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1421 if (Instruction::isAssociative(Opcode
) && CE1
->getOpcode() == Opcode
) {
1422 Constant
*T
= ConstantExpr::get(Opcode
, CE1
->getOperand(1), C2
);
1423 if (!isa
<ConstantExpr
>(T
) || cast
<ConstantExpr
>(T
)->getOpcode() != Opcode
)
1424 return ConstantExpr::get(Opcode
, CE1
->getOperand(0), T
);
1426 } else if (isa
<ConstantExpr
>(C2
)) {
1427 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1428 // other way if possible.
1429 if (Instruction::isCommutative(Opcode
))
1430 return ConstantFoldBinaryInstruction(Opcode
, C2
, C1
);
1433 // i1 can be simplified in many cases.
1434 if (C1
->getType()->isIntegerTy(1)) {
1436 case Instruction::Add
:
1437 case Instruction::Sub
:
1438 return ConstantExpr::getXor(C1
, C2
);
1439 case Instruction::Mul
:
1440 return ConstantExpr::getAnd(C1
, C2
);
1441 case Instruction::Shl
:
1442 case Instruction::LShr
:
1443 case Instruction::AShr
:
1444 // We can assume that C2 == 0. If it were one the result would be
1445 // undefined because the shift value is as large as the bitwidth.
1447 case Instruction::SDiv
:
1448 case Instruction::UDiv
:
1449 // We can assume that C2 == 1. If it were zero the result would be
1450 // undefined through division by zero.
1452 case Instruction::URem
:
1453 case Instruction::SRem
:
1454 // We can assume that C2 == 1. If it were zero the result would be
1455 // undefined through division by zero.
1456 return ConstantInt::getFalse(C1
->getContext());
1462 // We don't know how to fold this.
1466 /// isZeroSizedType - This type is zero sized if its an array or structure of
1467 /// zero sized types. The only leaf zero sized type is an empty structure.
1468 static bool isMaybeZeroSizedType(const Type
*Ty
) {
1469 if (const StructType
*STy
= dyn_cast
<StructType
>(Ty
)) {
1470 if (STy
->isOpaque()) return true; // Can't say.
1472 // If all of elements have zero size, this does too.
1473 for (unsigned i
= 0, e
= STy
->getNumElements(); i
!= e
; ++i
)
1474 if (!isMaybeZeroSizedType(STy
->getElementType(i
))) return false;
1477 } else if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
)) {
1478 return isMaybeZeroSizedType(ATy
->getElementType());
1483 /// IdxCompare - Compare the two constants as though they were getelementptr
1484 /// indices. This allows coersion of the types to be the same thing.
1486 /// If the two constants are the "same" (after coersion), return 0. If the
1487 /// first is less than the second, return -1, if the second is less than the
1488 /// first, return 1. If the constants are not integral, return -2.
1490 static int IdxCompare(Constant
*C1
, Constant
*C2
, const Type
*ElTy
) {
1491 if (C1
== C2
) return 0;
1493 // Ok, we found a different index. If they are not ConstantInt, we can't do
1494 // anything with them.
1495 if (!isa
<ConstantInt
>(C1
) || !isa
<ConstantInt
>(C2
))
1496 return -2; // don't know!
1498 // Ok, we have two differing integer indices. Sign extend them to be the same
1499 // type. Long is always big enough, so we use it.
1500 if (!C1
->getType()->isIntegerTy(64))
1501 C1
= ConstantExpr::getSExt(C1
, Type::getInt64Ty(C1
->getContext()));
1503 if (!C2
->getType()->isIntegerTy(64))
1504 C2
= ConstantExpr::getSExt(C2
, Type::getInt64Ty(C1
->getContext()));
1506 if (C1
== C2
) return 0; // They are equal
1508 // If the type being indexed over is really just a zero sized type, there is
1509 // no pointer difference being made here.
1510 if (isMaybeZeroSizedType(ElTy
))
1511 return -2; // dunno.
1513 // If they are really different, now that they are the same type, then we
1514 // found a difference!
1515 if (cast
<ConstantInt
>(C1
)->getSExtValue() <
1516 cast
<ConstantInt
>(C2
)->getSExtValue())
1522 /// evaluateFCmpRelation - This function determines if there is anything we can
1523 /// decide about the two constants provided. This doesn't need to handle simple
1524 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1525 /// If we can determine that the two constants have a particular relation to
1526 /// each other, we should return the corresponding FCmpInst predicate,
1527 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1528 /// ConstantFoldCompareInstruction.
1530 /// To simplify this code we canonicalize the relation so that the first
1531 /// operand is always the most "complex" of the two. We consider ConstantFP
1532 /// to be the simplest, and ConstantExprs to be the most complex.
1533 static FCmpInst::Predicate
evaluateFCmpRelation(Constant
*V1
, Constant
*V2
) {
1534 assert(V1
->getType() == V2
->getType() &&
1535 "Cannot compare values of different types!");
1537 // No compile-time operations on this type yet.
1538 if (V1
->getType()->isPPC_FP128Ty())
1539 return FCmpInst::BAD_FCMP_PREDICATE
;
1541 // Handle degenerate case quickly
1542 if (V1
== V2
) return FCmpInst::FCMP_OEQ
;
1544 if (!isa
<ConstantExpr
>(V1
)) {
1545 if (!isa
<ConstantExpr
>(V2
)) {
1546 // We distilled thisUse the standard constant folder for a few cases
1548 R
= dyn_cast
<ConstantInt
>(
1549 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ
, V1
, V2
));
1550 if (R
&& !R
->isZero())
1551 return FCmpInst::FCMP_OEQ
;
1552 R
= dyn_cast
<ConstantInt
>(
1553 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT
, V1
, V2
));
1554 if (R
&& !R
->isZero())
1555 return FCmpInst::FCMP_OLT
;
1556 R
= dyn_cast
<ConstantInt
>(
1557 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT
, V1
, V2
));
1558 if (R
&& !R
->isZero())
1559 return FCmpInst::FCMP_OGT
;
1561 // Nothing more we can do
1562 return FCmpInst::BAD_FCMP_PREDICATE
;
1565 // If the first operand is simple and second is ConstantExpr, swap operands.
1566 FCmpInst::Predicate SwappedRelation
= evaluateFCmpRelation(V2
, V1
);
1567 if (SwappedRelation
!= FCmpInst::BAD_FCMP_PREDICATE
)
1568 return FCmpInst::getSwappedPredicate(SwappedRelation
);
1570 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1571 // constantexpr or a simple constant.
1572 ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1573 switch (CE1
->getOpcode()) {
1574 case Instruction::FPTrunc
:
1575 case Instruction::FPExt
:
1576 case Instruction::UIToFP
:
1577 case Instruction::SIToFP
:
1578 // We might be able to do something with these but we don't right now.
1584 // There are MANY other foldings that we could perform here. They will
1585 // probably be added on demand, as they seem needed.
1586 return FCmpInst::BAD_FCMP_PREDICATE
;
1589 /// evaluateICmpRelation - This function determines if there is anything we can
1590 /// decide about the two constants provided. This doesn't need to handle simple
1591 /// things like integer comparisons, but should instead handle ConstantExprs
1592 /// and GlobalValues. If we can determine that the two constants have a
1593 /// particular relation to each other, we should return the corresponding ICmp
1594 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1596 /// To simplify this code we canonicalize the relation so that the first
1597 /// operand is always the most "complex" of the two. We consider simple
1598 /// constants (like ConstantInt) to be the simplest, followed by
1599 /// GlobalValues, followed by ConstantExpr's (the most complex).
1601 static ICmpInst::Predicate
evaluateICmpRelation(Constant
*V1
, Constant
*V2
,
1603 assert(V1
->getType() == V2
->getType() &&
1604 "Cannot compare different types of values!");
1605 if (V1
== V2
) return ICmpInst::ICMP_EQ
;
1607 if (!isa
<ConstantExpr
>(V1
) && !isa
<GlobalValue
>(V1
) &&
1608 !isa
<BlockAddress
>(V1
)) {
1609 if (!isa
<GlobalValue
>(V2
) && !isa
<ConstantExpr
>(V2
) &&
1610 !isa
<BlockAddress
>(V2
)) {
1611 // We distilled this down to a simple case, use the standard constant
1614 ICmpInst::Predicate pred
= ICmpInst::ICMP_EQ
;
1615 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1616 if (R
&& !R
->isZero())
1618 pred
= isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1619 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1620 if (R
&& !R
->isZero())
1622 pred
= isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1623 R
= dyn_cast
<ConstantInt
>(ConstantExpr::getICmp(pred
, V1
, V2
));
1624 if (R
&& !R
->isZero())
1627 // If we couldn't figure it out, bail.
1628 return ICmpInst::BAD_ICMP_PREDICATE
;
1631 // If the first operand is simple, swap operands.
1632 ICmpInst::Predicate SwappedRelation
=
1633 evaluateICmpRelation(V2
, V1
, isSigned
);
1634 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1635 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1637 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V1
)) {
1638 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1639 ICmpInst::Predicate SwappedRelation
=
1640 evaluateICmpRelation(V2
, V1
, isSigned
);
1641 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1642 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1643 return ICmpInst::BAD_ICMP_PREDICATE
;
1646 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1647 // constant (which, since the types must match, means that it's a
1648 // ConstantPointerNull).
1649 if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
)) {
1650 // Don't try to decide equality of aliases.
1651 if (!isa
<GlobalAlias
>(GV
) && !isa
<GlobalAlias
>(GV2
))
1652 if (!GV
->hasExternalWeakLinkage() || !GV2
->hasExternalWeakLinkage())
1653 return ICmpInst::ICMP_NE
;
1654 } else if (isa
<BlockAddress
>(V2
)) {
1655 return ICmpInst::ICMP_NE
; // Globals never equal labels.
1657 assert(isa
<ConstantPointerNull
>(V2
) && "Canonicalization guarantee!");
1658 // GlobalVals can never be null unless they have external weak linkage.
1659 // We don't try to evaluate aliases here.
1660 if (!GV
->hasExternalWeakLinkage() && !isa
<GlobalAlias
>(GV
))
1661 return ICmpInst::ICMP_NE
;
1663 } else if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(V1
)) {
1664 if (isa
<ConstantExpr
>(V2
)) { // Swap as necessary.
1665 ICmpInst::Predicate SwappedRelation
=
1666 evaluateICmpRelation(V2
, V1
, isSigned
);
1667 if (SwappedRelation
!= ICmpInst::BAD_ICMP_PREDICATE
)
1668 return ICmpInst::getSwappedPredicate(SwappedRelation
);
1669 return ICmpInst::BAD_ICMP_PREDICATE
;
1672 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1673 // constant (which, since the types must match, means that it is a
1674 // ConstantPointerNull).
1675 if (const BlockAddress
*BA2
= dyn_cast
<BlockAddress
>(V2
)) {
1676 // Block address in another function can't equal this one, but block
1677 // addresses in the current function might be the same if blocks are
1679 if (BA2
->getFunction() != BA
->getFunction())
1680 return ICmpInst::ICMP_NE
;
1682 // Block addresses aren't null, don't equal the address of globals.
1683 assert((isa
<ConstantPointerNull
>(V2
) || isa
<GlobalValue
>(V2
)) &&
1684 "Canonicalization guarantee!");
1685 return ICmpInst::ICMP_NE
;
1688 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1689 // constantexpr, a global, block address, or a simple constant.
1690 ConstantExpr
*CE1
= cast
<ConstantExpr
>(V1
);
1691 Constant
*CE1Op0
= CE1
->getOperand(0);
1693 switch (CE1
->getOpcode()) {
1694 case Instruction::Trunc
:
1695 case Instruction::FPTrunc
:
1696 case Instruction::FPExt
:
1697 case Instruction::FPToUI
:
1698 case Instruction::FPToSI
:
1699 break; // We can't evaluate floating point casts or truncations.
1701 case Instruction::UIToFP
:
1702 case Instruction::SIToFP
:
1703 case Instruction::BitCast
:
1704 case Instruction::ZExt
:
1705 case Instruction::SExt
:
1706 // If the cast is not actually changing bits, and the second operand is a
1707 // null pointer, do the comparison with the pre-casted value.
1708 if (V2
->isNullValue() &&
1709 (CE1
->getType()->isPointerTy() || CE1
->getType()->isIntegerTy())) {
1710 if (CE1
->getOpcode() == Instruction::ZExt
) isSigned
= false;
1711 if (CE1
->getOpcode() == Instruction::SExt
) isSigned
= true;
1712 return evaluateICmpRelation(CE1Op0
,
1713 Constant::getNullValue(CE1Op0
->getType()),
1718 case Instruction::GetElementPtr
:
1719 // Ok, since this is a getelementptr, we know that the constant has a
1720 // pointer type. Check the various cases.
1721 if (isa
<ConstantPointerNull
>(V2
)) {
1722 // If we are comparing a GEP to a null pointer, check to see if the base
1723 // of the GEP equals the null pointer.
1724 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1725 if (GV
->hasExternalWeakLinkage())
1726 // Weak linkage GVals could be zero or not. We're comparing that
1727 // to null pointer so its greater-or-equal
1728 return isSigned
? ICmpInst::ICMP_SGE
: ICmpInst::ICMP_UGE
;
1730 // If its not weak linkage, the GVal must have a non-zero address
1731 // so the result is greater-than
1732 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1733 } else if (isa
<ConstantPointerNull
>(CE1Op0
)) {
1734 // If we are indexing from a null pointer, check to see if we have any
1735 // non-zero indices.
1736 for (unsigned i
= 1, e
= CE1
->getNumOperands(); i
!= e
; ++i
)
1737 if (!CE1
->getOperand(i
)->isNullValue())
1738 // Offsetting from null, must not be equal.
1739 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1740 // Only zero indexes from null, must still be zero.
1741 return ICmpInst::ICMP_EQ
;
1743 // Otherwise, we can't really say if the first operand is null or not.
1744 } else if (const GlobalValue
*GV2
= dyn_cast
<GlobalValue
>(V2
)) {
1745 if (isa
<ConstantPointerNull
>(CE1Op0
)) {
1746 if (GV2
->hasExternalWeakLinkage())
1747 // Weak linkage GVals could be zero or not. We're comparing it to
1748 // a null pointer, so its less-or-equal
1749 return isSigned
? ICmpInst::ICMP_SLE
: ICmpInst::ICMP_ULE
;
1751 // If its not weak linkage, the GVal must have a non-zero address
1752 // so the result is less-than
1753 return isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1754 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(CE1Op0
)) {
1756 // If this is a getelementptr of the same global, then it must be
1757 // different. Because the types must match, the getelementptr could
1758 // only have at most one index, and because we fold getelementptr's
1759 // with a single zero index, it must be nonzero.
1760 assert(CE1
->getNumOperands() == 2 &&
1761 !CE1
->getOperand(1)->isNullValue() &&
1762 "Surprising getelementptr!");
1763 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1765 // If they are different globals, we don't know what the value is,
1766 // but they can't be equal.
1767 return ICmpInst::ICMP_NE
;
1771 ConstantExpr
*CE2
= cast
<ConstantExpr
>(V2
);
1772 Constant
*CE2Op0
= CE2
->getOperand(0);
1774 // There are MANY other foldings that we could perform here. They will
1775 // probably be added on demand, as they seem needed.
1776 switch (CE2
->getOpcode()) {
1778 case Instruction::GetElementPtr
:
1779 // By far the most common case to handle is when the base pointers are
1780 // obviously to the same or different globals.
1781 if (isa
<GlobalValue
>(CE1Op0
) && isa
<GlobalValue
>(CE2Op0
)) {
1782 if (CE1Op0
!= CE2Op0
) // Don't know relative ordering, but not equal
1783 return ICmpInst::ICMP_NE
;
1784 // Ok, we know that both getelementptr instructions are based on the
1785 // same global. From this, we can precisely determine the relative
1786 // ordering of the resultant pointers.
1789 // The logic below assumes that the result of the comparison
1790 // can be determined by finding the first index that differs.
1791 // This doesn't work if there is over-indexing in any
1792 // subsequent indices, so check for that case first.
1793 if (!CE1
->isGEPWithNoNotionalOverIndexing() ||
1794 !CE2
->isGEPWithNoNotionalOverIndexing())
1795 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1797 // Compare all of the operands the GEP's have in common.
1798 gep_type_iterator GTI
= gep_type_begin(CE1
);
1799 for (;i
!= CE1
->getNumOperands() && i
!= CE2
->getNumOperands();
1801 switch (IdxCompare(CE1
->getOperand(i
),
1802 CE2
->getOperand(i
), GTI
.getIndexedType())) {
1803 case -1: return isSigned
? ICmpInst::ICMP_SLT
:ICmpInst::ICMP_ULT
;
1804 case 1: return isSigned
? ICmpInst::ICMP_SGT
:ICmpInst::ICMP_UGT
;
1805 case -2: return ICmpInst::BAD_ICMP_PREDICATE
;
1808 // Ok, we ran out of things they have in common. If any leftovers
1809 // are non-zero then we have a difference, otherwise we are equal.
1810 for (; i
< CE1
->getNumOperands(); ++i
)
1811 if (!CE1
->getOperand(i
)->isNullValue()) {
1812 if (isa
<ConstantInt
>(CE1
->getOperand(i
)))
1813 return isSigned
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
;
1815 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1818 for (; i
< CE2
->getNumOperands(); ++i
)
1819 if (!CE2
->getOperand(i
)->isNullValue()) {
1820 if (isa
<ConstantInt
>(CE2
->getOperand(i
)))
1821 return isSigned
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
;
1823 return ICmpInst::BAD_ICMP_PREDICATE
; // Might be equal.
1825 return ICmpInst::ICMP_EQ
;
1834 return ICmpInst::BAD_ICMP_PREDICATE
;
1837 Constant
*llvm::ConstantFoldCompareInstruction(unsigned short pred
,
1838 Constant
*C1
, Constant
*C2
) {
1839 const Type
*ResultTy
;
1840 if (const VectorType
*VT
= dyn_cast
<VectorType
>(C1
->getType()))
1841 ResultTy
= VectorType::get(Type::getInt1Ty(C1
->getContext()),
1842 VT
->getNumElements());
1844 ResultTy
= Type::getInt1Ty(C1
->getContext());
1846 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1847 if (pred
== FCmpInst::FCMP_FALSE
)
1848 return Constant::getNullValue(ResultTy
);
1850 if (pred
== FCmpInst::FCMP_TRUE
)
1851 return Constant::getAllOnesValue(ResultTy
);
1853 // Handle some degenerate cases first
1854 if (isa
<UndefValue
>(C1
) || isa
<UndefValue
>(C2
)) {
1855 // For EQ and NE, we can always pick a value for the undef to make the
1856 // predicate pass or fail, so we can return undef.
1857 // Also, if both operands are undef, we can return undef.
1858 if (ICmpInst::isEquality(ICmpInst::Predicate(pred
)) ||
1859 (isa
<UndefValue
>(C1
) && isa
<UndefValue
>(C2
)))
1860 return UndefValue::get(ResultTy
);
1861 // Otherwise, pick the same value as the non-undef operand, and fold
1862 // it to true or false.
1863 return ConstantInt::get(ResultTy
, CmpInst::isTrueWhenEqual(pred
));
1866 // No compile-time operations on this type yet.
1867 if (C1
->getType()->isPPC_FP128Ty())
1870 // icmp eq/ne(null,GV) -> false/true
1871 if (C1
->isNullValue()) {
1872 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C2
))
1873 // Don't try to evaluate aliases. External weak GV can be null.
1874 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage()) {
1875 if (pred
== ICmpInst::ICMP_EQ
)
1876 return ConstantInt::getFalse(C1
->getContext());
1877 else if (pred
== ICmpInst::ICMP_NE
)
1878 return ConstantInt::getTrue(C1
->getContext());
1880 // icmp eq/ne(GV,null) -> false/true
1881 } else if (C2
->isNullValue()) {
1882 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(C1
))
1883 // Don't try to evaluate aliases. External weak GV can be null.
1884 if (!isa
<GlobalAlias
>(GV
) && !GV
->hasExternalWeakLinkage()) {
1885 if (pred
== ICmpInst::ICMP_EQ
)
1886 return ConstantInt::getFalse(C1
->getContext());
1887 else if (pred
== ICmpInst::ICMP_NE
)
1888 return ConstantInt::getTrue(C1
->getContext());
1892 // If the comparison is a comparison between two i1's, simplify it.
1893 if (C1
->getType()->isIntegerTy(1)) {
1895 case ICmpInst::ICMP_EQ
:
1896 if (isa
<ConstantInt
>(C2
))
1897 return ConstantExpr::getXor(C1
, ConstantExpr::getNot(C2
));
1898 return ConstantExpr::getXor(ConstantExpr::getNot(C1
), C2
);
1899 case ICmpInst::ICMP_NE
:
1900 return ConstantExpr::getXor(C1
, C2
);
1906 if (isa
<ConstantInt
>(C1
) && isa
<ConstantInt
>(C2
)) {
1907 APInt V1
= cast
<ConstantInt
>(C1
)->getValue();
1908 APInt V2
= cast
<ConstantInt
>(C2
)->getValue();
1910 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1911 case ICmpInst::ICMP_EQ
: return ConstantInt::get(ResultTy
, V1
== V2
);
1912 case ICmpInst::ICMP_NE
: return ConstantInt::get(ResultTy
, V1
!= V2
);
1913 case ICmpInst::ICMP_SLT
: return ConstantInt::get(ResultTy
, V1
.slt(V2
));
1914 case ICmpInst::ICMP_SGT
: return ConstantInt::get(ResultTy
, V1
.sgt(V2
));
1915 case ICmpInst::ICMP_SLE
: return ConstantInt::get(ResultTy
, V1
.sle(V2
));
1916 case ICmpInst::ICMP_SGE
: return ConstantInt::get(ResultTy
, V1
.sge(V2
));
1917 case ICmpInst::ICMP_ULT
: return ConstantInt::get(ResultTy
, V1
.ult(V2
));
1918 case ICmpInst::ICMP_UGT
: return ConstantInt::get(ResultTy
, V1
.ugt(V2
));
1919 case ICmpInst::ICMP_ULE
: return ConstantInt::get(ResultTy
, V1
.ule(V2
));
1920 case ICmpInst::ICMP_UGE
: return ConstantInt::get(ResultTy
, V1
.uge(V2
));
1922 } else if (isa
<ConstantFP
>(C1
) && isa
<ConstantFP
>(C2
)) {
1923 APFloat C1V
= cast
<ConstantFP
>(C1
)->getValueAPF();
1924 APFloat C2V
= cast
<ConstantFP
>(C2
)->getValueAPF();
1925 APFloat::cmpResult R
= C1V
.compare(C2V
);
1927 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1928 case FCmpInst::FCMP_FALSE
: return Constant::getNullValue(ResultTy
);
1929 case FCmpInst::FCMP_TRUE
: return Constant::getAllOnesValue(ResultTy
);
1930 case FCmpInst::FCMP_UNO
:
1931 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
);
1932 case FCmpInst::FCMP_ORD
:
1933 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpUnordered
);
1934 case FCmpInst::FCMP_UEQ
:
1935 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
||
1936 R
==APFloat::cmpEqual
);
1937 case FCmpInst::FCMP_OEQ
:
1938 return ConstantInt::get(ResultTy
, R
==APFloat::cmpEqual
);
1939 case FCmpInst::FCMP_UNE
:
1940 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpEqual
);
1941 case FCmpInst::FCMP_ONE
:
1942 return ConstantInt::get(ResultTy
, R
==APFloat::cmpLessThan
||
1943 R
==APFloat::cmpGreaterThan
);
1944 case FCmpInst::FCMP_ULT
:
1945 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
||
1946 R
==APFloat::cmpLessThan
);
1947 case FCmpInst::FCMP_OLT
:
1948 return ConstantInt::get(ResultTy
, R
==APFloat::cmpLessThan
);
1949 case FCmpInst::FCMP_UGT
:
1950 return ConstantInt::get(ResultTy
, R
==APFloat::cmpUnordered
||
1951 R
==APFloat::cmpGreaterThan
);
1952 case FCmpInst::FCMP_OGT
:
1953 return ConstantInt::get(ResultTy
, R
==APFloat::cmpGreaterThan
);
1954 case FCmpInst::FCMP_ULE
:
1955 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpGreaterThan
);
1956 case FCmpInst::FCMP_OLE
:
1957 return ConstantInt::get(ResultTy
, R
==APFloat::cmpLessThan
||
1958 R
==APFloat::cmpEqual
);
1959 case FCmpInst::FCMP_UGE
:
1960 return ConstantInt::get(ResultTy
, R
!=APFloat::cmpLessThan
);
1961 case FCmpInst::FCMP_OGE
:
1962 return ConstantInt::get(ResultTy
, R
==APFloat::cmpGreaterThan
||
1963 R
==APFloat::cmpEqual
);
1965 } else if (C1
->getType()->isVectorTy()) {
1966 SmallVector
<Constant
*, 16> C1Elts
, C2Elts
;
1967 C1
->getVectorElements(C1Elts
);
1968 C2
->getVectorElements(C2Elts
);
1969 if (C1Elts
.empty() || C2Elts
.empty())
1972 // If we can constant fold the comparison of each element, constant fold
1973 // the whole vector comparison.
1974 SmallVector
<Constant
*, 4> ResElts
;
1975 // Compare the elements, producing an i1 result or constant expr.
1976 for (unsigned i
= 0, e
= C1Elts
.size(); i
!= e
; ++i
)
1977 ResElts
.push_back(ConstantExpr::getCompare(pred
, C1Elts
[i
], C2Elts
[i
]));
1979 return ConstantVector::get(ResElts
);
1982 if (C1
->getType()->isFloatingPointTy()) {
1983 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
1984 switch (evaluateFCmpRelation(C1
, C2
)) {
1985 default: llvm_unreachable("Unknown relation!");
1986 case FCmpInst::FCMP_UNO
:
1987 case FCmpInst::FCMP_ORD
:
1988 case FCmpInst::FCMP_UEQ
:
1989 case FCmpInst::FCMP_UNE
:
1990 case FCmpInst::FCMP_ULT
:
1991 case FCmpInst::FCMP_UGT
:
1992 case FCmpInst::FCMP_ULE
:
1993 case FCmpInst::FCMP_UGE
:
1994 case FCmpInst::FCMP_TRUE
:
1995 case FCmpInst::FCMP_FALSE
:
1996 case FCmpInst::BAD_FCMP_PREDICATE
:
1997 break; // Couldn't determine anything about these constants.
1998 case FCmpInst::FCMP_OEQ
: // We know that C1 == C2
1999 Result
= (pred
== FCmpInst::FCMP_UEQ
|| pred
== FCmpInst::FCMP_OEQ
||
2000 pred
== FCmpInst::FCMP_ULE
|| pred
== FCmpInst::FCMP_OLE
||
2001 pred
== FCmpInst::FCMP_UGE
|| pred
== FCmpInst::FCMP_OGE
);
2003 case FCmpInst::FCMP_OLT
: // We know that C1 < C2
2004 Result
= (pred
== FCmpInst::FCMP_UNE
|| pred
== FCmpInst::FCMP_ONE
||
2005 pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
||
2006 pred
== FCmpInst::FCMP_ULE
|| pred
== FCmpInst::FCMP_OLE
);
2008 case FCmpInst::FCMP_OGT
: // We know that C1 > C2
2009 Result
= (pred
== FCmpInst::FCMP_UNE
|| pred
== FCmpInst::FCMP_ONE
||
2010 pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
||
2011 pred
== FCmpInst::FCMP_UGE
|| pred
== FCmpInst::FCMP_OGE
);
2013 case FCmpInst::FCMP_OLE
: // We know that C1 <= C2
2014 // We can only partially decide this relation.
2015 if (pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
)
2017 else if (pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
)
2020 case FCmpInst::FCMP_OGE
: // We known that C1 >= C2
2021 // We can only partially decide this relation.
2022 if (pred
== FCmpInst::FCMP_ULT
|| pred
== FCmpInst::FCMP_OLT
)
2024 else if (pred
== FCmpInst::FCMP_UGT
|| pred
== FCmpInst::FCMP_OGT
)
2027 case FCmpInst::FCMP_ONE
: // We know that C1 != C2
2028 // We can only partially decide this relation.
2029 if (pred
== FCmpInst::FCMP_OEQ
|| pred
== FCmpInst::FCMP_UEQ
)
2031 else if (pred
== FCmpInst::FCMP_ONE
|| pred
== FCmpInst::FCMP_UNE
)
2036 // If we evaluated the result, return it now.
2038 return ConstantInt::get(ResultTy
, Result
);
2041 // Evaluate the relation between the two constants, per the predicate.
2042 int Result
= -1; // -1 = unknown, 0 = known false, 1 = known true.
2043 switch (evaluateICmpRelation(C1
, C2
, CmpInst::isSigned(pred
))) {
2044 default: llvm_unreachable("Unknown relational!");
2045 case ICmpInst::BAD_ICMP_PREDICATE
:
2046 break; // Couldn't determine anything about these constants.
2047 case ICmpInst::ICMP_EQ
: // We know the constants are equal!
2048 // If we know the constants are equal, we can decide the result of this
2049 // computation precisely.
2050 Result
= ICmpInst::isTrueWhenEqual((ICmpInst::Predicate
)pred
);
2052 case ICmpInst::ICMP_ULT
:
2054 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_ULE
:
2056 case ICmpInst::ICMP_UGT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_UGE
:
2060 case ICmpInst::ICMP_SLT
:
2062 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_SLE
:
2064 case ICmpInst::ICMP_SGT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_SGE
:
2068 case ICmpInst::ICMP_UGT
:
2070 case ICmpInst::ICMP_UGT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_UGE
:
2072 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_ULE
:
2076 case ICmpInst::ICMP_SGT
:
2078 case ICmpInst::ICMP_SGT
: case ICmpInst::ICMP_NE
: case ICmpInst::ICMP_SGE
:
2080 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_EQ
: case ICmpInst::ICMP_SLE
:
2084 case ICmpInst::ICMP_ULE
:
2085 if (pred
== ICmpInst::ICMP_UGT
) Result
= 0;
2086 if (pred
== ICmpInst::ICMP_ULT
|| pred
== ICmpInst::ICMP_ULE
) Result
= 1;
2088 case ICmpInst::ICMP_SLE
:
2089 if (pred
== ICmpInst::ICMP_SGT
) Result
= 0;
2090 if (pred
== ICmpInst::ICMP_SLT
|| pred
== ICmpInst::ICMP_SLE
) Result
= 1;
2092 case ICmpInst::ICMP_UGE
:
2093 if (pred
== ICmpInst::ICMP_ULT
) Result
= 0;
2094 if (pred
== ICmpInst::ICMP_UGT
|| pred
== ICmpInst::ICMP_UGE
) Result
= 1;
2096 case ICmpInst::ICMP_SGE
:
2097 if (pred
== ICmpInst::ICMP_SLT
) Result
= 0;
2098 if (pred
== ICmpInst::ICMP_SGT
|| pred
== ICmpInst::ICMP_SGE
) Result
= 1;
2100 case ICmpInst::ICMP_NE
:
2101 if (pred
== ICmpInst::ICMP_EQ
) Result
= 0;
2102 if (pred
== ICmpInst::ICMP_NE
) Result
= 1;
2106 // If we evaluated the result, return it now.
2108 return ConstantInt::get(ResultTy
, Result
);
2110 // If the right hand side is a bitcast, try using its inverse to simplify
2111 // it by moving it to the left hand side. We can't do this if it would turn
2112 // a vector compare into a scalar compare or visa versa.
2113 if (ConstantExpr
*CE2
= dyn_cast
<ConstantExpr
>(C2
)) {
2114 Constant
*CE2Op0
= CE2
->getOperand(0);
2115 if (CE2
->getOpcode() == Instruction::BitCast
&&
2116 CE2
->getType()->isVectorTy() == CE2Op0
->getType()->isVectorTy()) {
2117 Constant
*Inverse
= ConstantExpr::getBitCast(C1
, CE2Op0
->getType());
2118 return ConstantExpr::getICmp(pred
, Inverse
, CE2Op0
);
2122 // If the left hand side is an extension, try eliminating it.
2123 if (ConstantExpr
*CE1
= dyn_cast
<ConstantExpr
>(C1
)) {
2124 if ((CE1
->getOpcode() == Instruction::SExt
&& ICmpInst::isSigned(pred
)) ||
2125 (CE1
->getOpcode() == Instruction::ZExt
&& !ICmpInst::isSigned(pred
))){
2126 Constant
*CE1Op0
= CE1
->getOperand(0);
2127 Constant
*CE1Inverse
= ConstantExpr::getTrunc(CE1
, CE1Op0
->getType());
2128 if (CE1Inverse
== CE1Op0
) {
2129 // Check whether we can safely truncate the right hand side.
2130 Constant
*C2Inverse
= ConstantExpr::getTrunc(C2
, CE1Op0
->getType());
2131 if (ConstantExpr::getZExt(C2Inverse
, C2
->getType()) == C2
) {
2132 return ConstantExpr::getICmp(pred
, CE1Inverse
, C2Inverse
);
2138 if ((!isa
<ConstantExpr
>(C1
) && isa
<ConstantExpr
>(C2
)) ||
2139 (C1
->isNullValue() && !C2
->isNullValue())) {
2140 // If C2 is a constant expr and C1 isn't, flip them around and fold the
2141 // other way if possible.
2142 // Also, if C1 is null and C2 isn't, flip them around.
2143 pred
= ICmpInst::getSwappedPredicate((ICmpInst::Predicate
)pred
);
2144 return ConstantExpr::getICmp(pred
, C2
, C1
);
2150 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2152 template<typename IndexTy
>
2153 static bool isInBoundsIndices(IndexTy
const *Idxs
, size_t NumIdx
) {
2154 // No indices means nothing that could be out of bounds.
2155 if (NumIdx
== 0) return true;
2157 // If the first index is zero, it's in bounds.
2158 if (cast
<Constant
>(Idxs
[0])->isNullValue()) return true;
2160 // If the first index is one and all the rest are zero, it's in bounds,
2161 // by the one-past-the-end rule.
2162 if (!cast
<ConstantInt
>(Idxs
[0])->isOne())
2164 for (unsigned i
= 1, e
= NumIdx
; i
!= e
; ++i
)
2165 if (!cast
<Constant
>(Idxs
[i
])->isNullValue())
2170 template<typename IndexTy
>
2171 static Constant
*ConstantFoldGetElementPtrImpl(Constant
*C
,
2173 IndexTy
const *Idxs
,
2175 if (NumIdx
== 0) return C
;
2176 Constant
*Idx0
= cast
<Constant
>(Idxs
[0]);
2177 if ((NumIdx
== 1 && Idx0
->isNullValue()))
2180 if (isa
<UndefValue
>(C
)) {
2181 const PointerType
*Ptr
= cast
<PointerType
>(C
->getType());
2182 const Type
*Ty
= GetElementPtrInst::getIndexedType(Ptr
, Idxs
, Idxs
+NumIdx
);
2183 assert(Ty
!= 0 && "Invalid indices for GEP!");
2184 return UndefValue::get(PointerType::get(Ty
, Ptr
->getAddressSpace()));
2187 if (C
->isNullValue()) {
2189 for (unsigned i
= 0, e
= NumIdx
; i
!= e
; ++i
)
2190 if (!cast
<Constant
>(Idxs
[i
])->isNullValue()) {
2195 const PointerType
*Ptr
= cast
<PointerType
>(C
->getType());
2196 const Type
*Ty
= GetElementPtrInst::getIndexedType(Ptr
, Idxs
,
2198 assert(Ty
!= 0 && "Invalid indices for GEP!");
2199 return ConstantPointerNull::get(PointerType::get(Ty
,
2200 Ptr
->getAddressSpace()));
2204 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
2205 // Combine Indices - If the source pointer to this getelementptr instruction
2206 // is a getelementptr instruction, combine the indices of the two
2207 // getelementptr instructions into a single instruction.
2209 if (CE
->getOpcode() == Instruction::GetElementPtr
) {
2210 const Type
*LastTy
= 0;
2211 for (gep_type_iterator I
= gep_type_begin(CE
), E
= gep_type_end(CE
);
2215 if ((LastTy
&& LastTy
->isArrayTy()) || Idx0
->isNullValue()) {
2216 SmallVector
<Value
*, 16> NewIndices
;
2217 NewIndices
.reserve(NumIdx
+ CE
->getNumOperands());
2218 for (unsigned i
= 1, e
= CE
->getNumOperands()-1; i
!= e
; ++i
)
2219 NewIndices
.push_back(CE
->getOperand(i
));
2221 // Add the last index of the source with the first index of the new GEP.
2222 // Make sure to handle the case when they are actually different types.
2223 Constant
*Combined
= CE
->getOperand(CE
->getNumOperands()-1);
2224 // Otherwise it must be an array.
2225 if (!Idx0
->isNullValue()) {
2226 const Type
*IdxTy
= Combined
->getType();
2227 if (IdxTy
!= Idx0
->getType()) {
2228 const Type
*Int64Ty
= Type::getInt64Ty(IdxTy
->getContext());
2229 Constant
*C1
= ConstantExpr::getSExtOrBitCast(Idx0
, Int64Ty
);
2230 Constant
*C2
= ConstantExpr::getSExtOrBitCast(Combined
, Int64Ty
);
2231 Combined
= ConstantExpr::get(Instruction::Add
, C1
, C2
);
2234 ConstantExpr::get(Instruction::Add
, Idx0
, Combined
);
2238 NewIndices
.push_back(Combined
);
2239 NewIndices
.append(Idxs
+1, Idxs
+NumIdx
);
2240 return (inBounds
&& cast
<GEPOperator
>(CE
)->isInBounds()) ?
2241 ConstantExpr::getInBoundsGetElementPtr(CE
->getOperand(0),
2243 NewIndices
.size()) :
2244 ConstantExpr::getGetElementPtr(CE
->getOperand(0),
2250 // Implement folding of:
2251 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2253 // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2255 if (CE
->isCast() && NumIdx
> 1 && Idx0
->isNullValue()) {
2256 if (const PointerType
*SPT
=
2257 dyn_cast
<PointerType
>(CE
->getOperand(0)->getType()))
2258 if (const ArrayType
*SAT
= dyn_cast
<ArrayType
>(SPT
->getElementType()))
2259 if (const ArrayType
*CAT
=
2260 dyn_cast
<ArrayType
>(cast
<PointerType
>(C
->getType())->getElementType()))
2261 if (CAT
->getElementType() == SAT
->getElementType())
2263 ConstantExpr::getInBoundsGetElementPtr(
2264 (Constant
*)CE
->getOperand(0), Idxs
, NumIdx
) :
2265 ConstantExpr::getGetElementPtr(
2266 (Constant
*)CE
->getOperand(0), Idxs
, NumIdx
);
2270 // Check to see if any array indices are not within the corresponding
2271 // notional array bounds. If so, try to determine if they can be factored
2272 // out into preceding dimensions.
2273 bool Unknown
= false;
2274 SmallVector
<Constant
*, 8> NewIdxs
;
2275 const Type
*Ty
= C
->getType();
2276 const Type
*Prev
= 0;
2277 for (unsigned i
= 0; i
!= NumIdx
;
2278 Prev
= Ty
, Ty
= cast
<CompositeType
>(Ty
)->getTypeAtIndex(Idxs
[i
]), ++i
) {
2279 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(Idxs
[i
])) {
2280 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(Ty
))
2281 if (ATy
->getNumElements() <= INT64_MAX
&&
2282 ATy
->getNumElements() != 0 &&
2283 CI
->getSExtValue() >= (int64_t)ATy
->getNumElements()) {
2284 if (isa
<SequentialType
>(Prev
)) {
2285 // It's out of range, but we can factor it into the prior
2287 NewIdxs
.resize(NumIdx
);
2288 ConstantInt
*Factor
= ConstantInt::get(CI
->getType(),
2289 ATy
->getNumElements());
2290 NewIdxs
[i
] = ConstantExpr::getSRem(CI
, Factor
);
2292 Constant
*PrevIdx
= cast
<Constant
>(Idxs
[i
-1]);
2293 Constant
*Div
= ConstantExpr::getSDiv(CI
, Factor
);
2295 // Before adding, extend both operands to i64 to avoid
2296 // overflow trouble.
2297 if (!PrevIdx
->getType()->isIntegerTy(64))
2298 PrevIdx
= ConstantExpr::getSExt(PrevIdx
,
2299 Type::getInt64Ty(Div
->getContext()));
2300 if (!Div
->getType()->isIntegerTy(64))
2301 Div
= ConstantExpr::getSExt(Div
,
2302 Type::getInt64Ty(Div
->getContext()));
2304 NewIdxs
[i
-1] = ConstantExpr::getAdd(PrevIdx
, Div
);
2306 // It's out of range, but the prior dimension is a struct
2307 // so we can't do anything about it.
2312 // We don't know if it's in range or not.
2317 // If we did any factoring, start over with the adjusted indices.
2318 if (!NewIdxs
.empty()) {
2319 for (unsigned i
= 0; i
!= NumIdx
; ++i
)
2320 if (!NewIdxs
[i
]) NewIdxs
[i
] = cast
<Constant
>(Idxs
[i
]);
2322 ConstantExpr::getInBoundsGetElementPtr(C
, NewIdxs
.data(),
2324 ConstantExpr::getGetElementPtr(C
, NewIdxs
.data(), NewIdxs
.size());
2327 // If all indices are known integers and normalized, we can do a simple
2328 // check for the "inbounds" property.
2329 if (!Unknown
&& !inBounds
&&
2330 isa
<GlobalVariable
>(C
) && isInBoundsIndices(Idxs
, NumIdx
))
2331 return ConstantExpr::getInBoundsGetElementPtr(C
, Idxs
, NumIdx
);
2336 Constant
*llvm::ConstantFoldGetElementPtr(Constant
*C
,
2338 Constant
* const *Idxs
,
2340 return ConstantFoldGetElementPtrImpl(C
, inBounds
, Idxs
, NumIdx
);
2343 Constant
*llvm::ConstantFoldGetElementPtr(Constant
*C
,
2347 return ConstantFoldGetElementPtrImpl(C
, inBounds
, Idxs
, NumIdx
);