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/IR/PatternMatch.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
37 using namespace llvm::PatternMatch;
39 //===----------------------------------------------------------------------===//
40 // ConstantFold*Instruction Implementations
41 //===----------------------------------------------------------------------===//
43 /// BitCastConstantVector - Convert the specified vector Constant node to the
44 /// specified vector type. At this point, we know that the elements of the
45 /// input vector constant are all simple integer or FP values.
46 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
48 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
49 if (CV->isNullValue()) return Constant::getNullValue(DstTy);
51 // If this cast changes element count then we can't handle it here:
52 // doing so requires endianness information. This should be handled by
53 // Analysis/ConstantFolding.cpp
54 unsigned NumElts = DstTy->getNumElements();
55 if (NumElts != CV->getType()->getVectorNumElements())
58 Type *DstEltTy = DstTy->getElementType();
60 SmallVector<Constant*, 16> Result;
61 Type *Ty = IntegerType::get(CV->getContext(), 32);
62 for (unsigned i = 0; i != NumElts; ++i) {
64 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
65 C = ConstantExpr::getBitCast(C, DstEltTy);
69 return ConstantVector::get(Result);
72 /// This function determines which opcode to use to fold two constant cast
73 /// expressions together. It uses CastInst::isEliminableCastPair to determine
74 /// the opcode. Consequently its just a wrapper around that function.
75 /// @brief Determine if it is valid to fold a cast of a cast
78 unsigned opc, ///< opcode of the second cast constant expression
79 ConstantExpr *Op, ///< the first cast constant expression
80 Type *DstTy ///< destination type of the first cast
82 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
83 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
84 assert(CastInst::isCast(opc) && "Invalid cast opcode");
86 // The the types and opcodes for the two Cast constant expressions
87 Type *SrcTy = Op->getOperand(0)->getType();
88 Type *MidTy = Op->getType();
89 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
90 Instruction::CastOps secondOp = Instruction::CastOps(opc);
92 // Assume that pointers are never more than 64 bits wide, and only use this
93 // for the middle type. Otherwise we could end up folding away illegal
94 // bitcasts between address spaces with different sizes.
95 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
97 // Let CastInst::isEliminableCastPair do the heavy lifting.
98 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
99 nullptr, FakeIntPtrTy, nullptr);
102 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
103 Type *SrcTy = V->getType();
105 return V; // no-op cast
107 // Check to see if we are casting a pointer to an aggregate to a pointer to
108 // the first element. If so, return the appropriate GEP instruction.
109 if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
110 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
111 if (PTy->getAddressSpace() == DPTy->getAddressSpace()
112 && DPTy->getElementType()->isSized()) {
113 SmallVector<Value*, 8> IdxList;
115 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
116 IdxList.push_back(Zero);
117 Type *ElTy = PTy->getElementType();
118 while (ElTy != DPTy->getElementType()) {
119 if (StructType *STy = dyn_cast<StructType>(ElTy)) {
120 if (STy->getNumElements() == 0) break;
121 ElTy = STy->getElementType(0);
122 IdxList.push_back(Zero);
123 } else if (SequentialType *STy =
124 dyn_cast<SequentialType>(ElTy)) {
125 if (ElTy->isPointerTy()) break; // Can't index into pointers!
126 ElTy = STy->getElementType();
127 IdxList.push_back(Zero);
133 if (ElTy == DPTy->getElementType())
134 // This GEP is inbounds because all indices are zero.
135 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
138 // Handle casts from one vector constant to another. We know that the src
139 // and dest type have the same size (otherwise its an illegal cast).
140 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
141 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
142 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
143 "Not cast between same sized vectors!");
145 // First, check for null. Undef is already handled.
146 if (isa<ConstantAggregateZero>(V))
147 return Constant::getNullValue(DestTy);
149 // Handle ConstantVector and ConstantAggregateVector.
150 return BitCastConstantVector(V, DestPTy);
153 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
154 // This allows for other simplifications (although some of them
155 // can only be handled by Analysis/ConstantFolding.cpp).
156 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
157 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
160 // Finally, implement bitcast folding now. The code below doesn't handle
162 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
163 return ConstantPointerNull::get(cast<PointerType>(DestTy));
165 // Handle integral constant input.
166 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
167 if (DestTy->isIntegerTy())
168 // Integral -> Integral. This is a no-op because the bit widths must
169 // be the same. Consequently, we just fold to V.
172 if (DestTy->isFloatingPointTy())
173 return ConstantFP::get(DestTy->getContext(),
174 APFloat(DestTy->getFltSemantics(),
177 // Otherwise, can't fold this (vector?)
181 // Handle ConstantFP input: FP -> Integral.
182 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
183 return ConstantInt::get(FP->getContext(),
184 FP->getValueAPF().bitcastToAPInt());
190 /// ExtractConstantBytes - V is an integer constant which only has a subset of
191 /// its bytes used. The bytes used are indicated by ByteStart (which is the
192 /// first byte used, counting from the least significant byte) and ByteSize,
193 /// which is the number of bytes used.
195 /// This function analyzes the specified constant to see if the specified byte
196 /// range can be returned as a simplified constant. If so, the constant is
197 /// returned, otherwise null is returned.
199 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
201 assert(C->getType()->isIntegerTy() &&
202 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
203 "Non-byte sized integer input");
204 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
205 assert(ByteSize && "Must be accessing some piece");
206 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
207 assert(ByteSize != CSize && "Should not extract everything");
209 // Constant Integers are simple.
210 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
211 APInt V = CI->getValue();
213 V = V.lshr(ByteStart*8);
214 V = V.trunc(ByteSize*8);
215 return ConstantInt::get(CI->getContext(), V);
218 // In the input is a constant expr, we might be able to recursively simplify.
219 // If not, we definitely can't do anything.
220 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
221 if (!CE) return nullptr;
223 switch (CE->getOpcode()) {
224 default: return nullptr;
225 case Instruction::Or: {
226 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
231 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
232 if (RHSC->isAllOnesValue())
235 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
238 return ConstantExpr::getOr(LHS, RHS);
240 case Instruction::And: {
241 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
246 if (RHS->isNullValue())
249 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
252 return ConstantExpr::getAnd(LHS, RHS);
254 case Instruction::LShr: {
255 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
258 unsigned ShAmt = Amt->getZExtValue();
259 // Cannot analyze non-byte shifts.
260 if ((ShAmt & 7) != 0)
264 // If the extract is known to be all zeros, return zero.
265 if (ByteStart >= CSize-ShAmt)
266 return Constant::getNullValue(IntegerType::get(CE->getContext(),
268 // If the extract is known to be fully in the input, extract it.
269 if (ByteStart+ByteSize+ShAmt <= CSize)
270 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
272 // TODO: Handle the 'partially zero' case.
276 case Instruction::Shl: {
277 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
280 unsigned ShAmt = Amt->getZExtValue();
281 // Cannot analyze non-byte shifts.
282 if ((ShAmt & 7) != 0)
286 // If the extract is known to be all zeros, return zero.
287 if (ByteStart+ByteSize <= ShAmt)
288 return Constant::getNullValue(IntegerType::get(CE->getContext(),
290 // If the extract is known to be fully in the input, extract it.
291 if (ByteStart >= ShAmt)
292 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
294 // TODO: Handle the 'partially zero' case.
298 case Instruction::ZExt: {
299 unsigned SrcBitSize =
300 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
302 // If extracting something that is completely zero, return 0.
303 if (ByteStart*8 >= SrcBitSize)
304 return Constant::getNullValue(IntegerType::get(CE->getContext(),
307 // If exactly extracting the input, return it.
308 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
309 return CE->getOperand(0);
311 // If extracting something completely in the input, if if the input is a
312 // multiple of 8 bits, recurse.
313 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
314 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
316 // Otherwise, if extracting a subset of the input, which is not multiple of
317 // 8 bits, do a shift and trunc to get the bits.
318 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
319 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
320 Constant *Res = CE->getOperand(0);
322 Res = ConstantExpr::getLShr(Res,
323 ConstantInt::get(Res->getType(), ByteStart*8));
324 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
328 // TODO: Handle the 'partially zero' case.
334 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
335 /// on Ty, with any known factors factored out. If Folded is false,
336 /// return null if no factoring was possible, to avoid endlessly
337 /// bouncing an unfoldable expression back into the top-level folder.
339 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
341 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
342 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
343 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
344 return ConstantExpr::getNUWMul(E, N);
347 if (StructType *STy = dyn_cast<StructType>(Ty))
348 if (!STy->isPacked()) {
349 unsigned NumElems = STy->getNumElements();
350 // An empty struct has size zero.
352 return ConstantExpr::getNullValue(DestTy);
353 // Check for a struct with all members having the same size.
354 Constant *MemberSize =
355 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
357 for (unsigned i = 1; i != NumElems; ++i)
359 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
364 Constant *N = ConstantInt::get(DestTy, NumElems);
365 return ConstantExpr::getNUWMul(MemberSize, N);
369 // Pointer size doesn't depend on the pointee type, so canonicalize them
370 // to an arbitrary pointee.
371 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
372 if (!PTy->getElementType()->isIntegerTy(1))
374 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
375 PTy->getAddressSpace()),
378 // If there's no interesting folding happening, bail so that we don't create
379 // a constant that looks like it needs folding but really doesn't.
383 // Base case: Get a regular sizeof expression.
384 Constant *C = ConstantExpr::getSizeOf(Ty);
385 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
391 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
392 /// on Ty, with any known factors factored out. If Folded is false,
393 /// return null if no factoring was possible, to avoid endlessly
394 /// bouncing an unfoldable expression back into the top-level folder.
396 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
398 // The alignment of an array is equal to the alignment of the
399 // array element. Note that this is not always true for vectors.
400 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
401 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
402 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
409 if (StructType *STy = dyn_cast<StructType>(Ty)) {
410 // Packed structs always have an alignment of 1.
412 return ConstantInt::get(DestTy, 1);
414 // Otherwise, struct alignment is the maximum alignment of any member.
415 // Without target data, we can't compare much, but we can check to see
416 // if all the members have the same alignment.
417 unsigned NumElems = STy->getNumElements();
418 // An empty struct has minimal alignment.
420 return ConstantInt::get(DestTy, 1);
421 // Check for a struct with all members having the same alignment.
422 Constant *MemberAlign =
423 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
425 for (unsigned i = 1; i != NumElems; ++i)
426 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
434 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
435 // to an arbitrary pointee.
436 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
437 if (!PTy->getElementType()->isIntegerTy(1))
439 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
441 PTy->getAddressSpace()),
444 // If there's no interesting folding happening, bail so that we don't create
445 // a constant that looks like it needs folding but really doesn't.
449 // Base case: Get a regular alignof expression.
450 Constant *C = ConstantExpr::getAlignOf(Ty);
451 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
457 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
458 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
459 /// return null if no factoring was possible, to avoid endlessly
460 /// bouncing an unfoldable expression back into the top-level folder.
462 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
465 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
466 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
469 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
470 return ConstantExpr::getNUWMul(E, N);
473 if (StructType *STy = dyn_cast<StructType>(Ty))
474 if (!STy->isPacked()) {
475 unsigned NumElems = STy->getNumElements();
476 // An empty struct has no members.
479 // Check for a struct with all members having the same size.
480 Constant *MemberSize =
481 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
483 for (unsigned i = 1; i != NumElems; ++i)
485 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
490 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
495 return ConstantExpr::getNUWMul(MemberSize, N);
499 // If there's no interesting folding happening, bail so that we don't create
500 // a constant that looks like it needs folding but really doesn't.
504 // Base case: Get a regular offsetof expression.
505 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
506 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
512 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
514 if (isa<UndefValue>(V)) {
515 // zext(undef) = 0, because the top bits will be zero.
516 // sext(undef) = 0, because the top bits will all be the same.
517 // [us]itofp(undef) = 0, because the result value is bounded.
518 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
519 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
520 return Constant::getNullValue(DestTy);
521 return UndefValue::get(DestTy);
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 // Do not fold addrspacecast (gep 0, .., 0). It might make the
536 // addrspacecast uncanonicalized.
537 opc != Instruction::AddrSpaceCast) {
538 // If all of the indexes in the GEP are null values, there is no pointer
539 // adjustment going on. We might as well cast the source pointer.
540 bool isAllNull = true;
541 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
542 if (!CE->getOperand(i)->isNullValue()) {
547 // This is casting one pointer type to another, always BitCast
548 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
552 // If the cast operand is a constant vector, perform the cast by
553 // operating on each element. In the cast of bitcasts, the element
554 // count may be mismatched; don't attempt to handle that here.
555 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
556 DestTy->isVectorTy() &&
557 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
558 SmallVector<Constant*, 16> res;
559 VectorType *DestVecTy = cast<VectorType>(DestTy);
560 Type *DstEltTy = DestVecTy->getElementType();
561 Type *Ty = IntegerType::get(V->getContext(), 32);
562 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
564 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
565 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
567 return ConstantVector::get(res);
570 // We actually have to do a cast now. Perform the cast according to the
574 llvm_unreachable("Failed to cast constant expression");
575 case Instruction::FPTrunc:
576 case Instruction::FPExt:
577 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
579 APFloat Val = FPC->getValueAPF();
580 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
581 DestTy->isFloatTy() ? APFloat::IEEEsingle :
582 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
583 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
584 DestTy->isFP128Ty() ? APFloat::IEEEquad :
585 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
587 APFloat::rmNearestTiesToEven, &ignored);
588 return ConstantFP::get(V->getContext(), Val);
590 return nullptr; // Can't fold.
591 case Instruction::FPToUI:
592 case Instruction::FPToSI:
593 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
594 const APFloat &V = FPC->getValueAPF();
597 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
598 if (APFloat::opInvalidOp ==
599 V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
600 APFloat::rmTowardZero, &ignored)) {
601 // Undefined behavior invoked - the destination type can't represent
602 // the input constant.
603 return UndefValue::get(DestTy);
605 APInt Val(DestBitWidth, x);
606 return ConstantInt::get(FPC->getContext(), Val);
608 return nullptr; // Can't fold.
609 case Instruction::IntToPtr: //always treated as unsigned
610 if (V->isNullValue()) // Is it an integral null value?
611 return ConstantPointerNull::get(cast<PointerType>(DestTy));
612 return nullptr; // Other pointer types cannot be casted
613 case Instruction::PtrToInt: // always treated as unsigned
614 // Is it a null pointer value?
615 if (V->isNullValue())
616 return ConstantInt::get(DestTy, 0);
617 // If this is a sizeof-like expression, pull out multiplications by
618 // known factors to expose them to subsequent folding. If it's an
619 // alignof-like expression, factor out known factors.
620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
621 if (CE->getOpcode() == Instruction::GetElementPtr &&
622 CE->getOperand(0)->isNullValue()) {
624 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
625 if (CE->getNumOperands() == 2) {
626 // Handle a sizeof-like expression.
627 Constant *Idx = CE->getOperand(1);
628 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
629 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
630 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
633 return ConstantExpr::getMul(C, Idx);
635 } else if (CE->getNumOperands() == 3 &&
636 CE->getOperand(1)->isNullValue()) {
637 // Handle an alignof-like expression.
638 if (StructType *STy = dyn_cast<StructType>(Ty))
639 if (!STy->isPacked()) {
640 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
642 STy->getNumElements() == 2 &&
643 STy->getElementType(0)->isIntegerTy(1)) {
644 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
647 // Handle an offsetof-like expression.
648 if (Ty->isStructTy() || Ty->isArrayTy()) {
649 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
655 // Other pointer types cannot be casted
657 case Instruction::UIToFP:
658 case Instruction::SIToFP:
659 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
660 APInt api = CI->getValue();
661 APFloat apf(DestTy->getFltSemantics(),
662 APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
663 if (APFloat::opOverflow &
664 apf.convertFromAPInt(api, opc==Instruction::SIToFP,
665 APFloat::rmNearestTiesToEven)) {
666 // Undefined behavior invoked - the destination type can't represent
667 // the input constant.
668 return UndefValue::get(DestTy);
670 return ConstantFP::get(V->getContext(), apf);
673 case Instruction::ZExt:
674 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
676 return ConstantInt::get(V->getContext(),
677 CI->getValue().zext(BitWidth));
680 case Instruction::SExt:
681 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
682 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
683 return ConstantInt::get(V->getContext(),
684 CI->getValue().sext(BitWidth));
687 case Instruction::Trunc: {
688 if (V->getType()->isVectorTy())
691 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
692 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
693 return ConstantInt::get(V->getContext(),
694 CI->getValue().trunc(DestBitWidth));
697 // The input must be a constantexpr. See if we can simplify this based on
698 // the bytes we are demanding. Only do this if the source and dest are an
699 // even multiple of a byte.
700 if ((DestBitWidth & 7) == 0 &&
701 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
702 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
707 case Instruction::BitCast:
708 return FoldBitCast(V, DestTy);
709 case Instruction::AddrSpaceCast:
714 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
715 Constant *V1, Constant *V2) {
716 // Check for i1 and vector true/false conditions.
717 if (Cond->isNullValue()) return V2;
718 if (Cond->isAllOnesValue()) return V1;
720 // If the condition is a vector constant, fold the result elementwise.
721 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
722 SmallVector<Constant*, 16> Result;
723 Type *Ty = IntegerType::get(CondV->getContext(), 32);
724 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
726 Constant *V1Element = ConstantExpr::getExtractElement(V1,
727 ConstantInt::get(Ty, i));
728 Constant *V2Element = ConstantExpr::getExtractElement(V2,
729 ConstantInt::get(Ty, i));
730 Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
731 if (V1Element == V2Element) {
733 } else if (isa<UndefValue>(Cond)) {
734 V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
736 if (!isa<ConstantInt>(Cond)) break;
737 V = Cond->isNullValue() ? V2Element : V1Element;
742 // If we were able to build the vector, return it.
743 if (Result.size() == V1->getType()->getVectorNumElements())
744 return ConstantVector::get(Result);
747 if (isa<UndefValue>(Cond)) {
748 if (isa<UndefValue>(V1)) return V1;
751 if (isa<UndefValue>(V1)) return V2;
752 if (isa<UndefValue>(V2)) return V1;
753 if (V1 == V2) return V1;
755 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
756 if (TrueVal->getOpcode() == Instruction::Select)
757 if (TrueVal->getOperand(0) == Cond)
758 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
760 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
761 if (FalseVal->getOpcode() == Instruction::Select)
762 if (FalseVal->getOperand(0) == Cond)
763 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
769 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
771 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
772 return UndefValue::get(Val->getType()->getVectorElementType());
773 if (Val->isNullValue()) // ee(zero, x) -> zero
774 return Constant::getNullValue(Val->getType()->getVectorElementType());
775 // ee({w,x,y,z}, undef) -> undef
776 if (isa<UndefValue>(Idx))
777 return UndefValue::get(Val->getType()->getVectorElementType());
779 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
780 uint64_t Index = CIdx->getZExtValue();
781 // ee({w,x,y,z}, wrong_value) -> undef
782 if (Index >= Val->getType()->getVectorNumElements())
783 return UndefValue::get(Val->getType()->getVectorElementType());
784 return Val->getAggregateElement(Index);
789 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
792 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
793 if (!CIdx) return nullptr;
794 const APInt &IdxVal = CIdx->getValue();
796 SmallVector<Constant*, 16> Result;
797 Type *Ty = IntegerType::get(Val->getContext(), 32);
798 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
800 Result.push_back(Elt);
805 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
809 return ConstantVector::get(Result);
812 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
815 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
816 Type *EltTy = V1->getType()->getVectorElementType();
818 // Undefined shuffle mask -> undefined value.
819 if (isa<UndefValue>(Mask))
820 return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
822 // Don't break the bitcode reader hack.
823 if (isa<ConstantExpr>(Mask)) return nullptr;
825 unsigned SrcNumElts = V1->getType()->getVectorNumElements();
827 // Loop over the shuffle mask, evaluating each element.
828 SmallVector<Constant*, 32> Result;
829 for (unsigned i = 0; i != MaskNumElts; ++i) {
830 int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
832 Result.push_back(UndefValue::get(EltTy));
836 if (unsigned(Elt) >= SrcNumElts*2)
837 InElt = UndefValue::get(EltTy);
838 else if (unsigned(Elt) >= SrcNumElts) {
839 Type *Ty = IntegerType::get(V2->getContext(), 32);
841 ConstantExpr::getExtractElement(V2,
842 ConstantInt::get(Ty, Elt - SrcNumElts));
844 Type *Ty = IntegerType::get(V1->getContext(), 32);
845 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
847 Result.push_back(InElt);
850 return ConstantVector::get(Result);
853 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
854 ArrayRef<unsigned> Idxs) {
855 // Base case: no indices, so return the entire value.
859 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
860 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
865 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
867 ArrayRef<unsigned> Idxs) {
868 // Base case: no indices, so replace the entire value.
873 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
874 NumElts = ST->getNumElements();
875 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
876 NumElts = AT->getNumElements();
878 NumElts = Agg->getType()->getVectorNumElements();
880 SmallVector<Constant*, 32> Result;
881 for (unsigned i = 0; i != NumElts; ++i) {
882 Constant *C = Agg->getAggregateElement(i);
883 if (!C) return nullptr;
886 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
891 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
892 return ConstantStruct::get(ST, Result);
893 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
894 return ConstantArray::get(AT, Result);
895 return ConstantVector::get(Result);
899 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
900 Constant *C1, Constant *C2) {
901 // Handle UndefValue up front.
902 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
904 case Instruction::Xor:
905 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
906 // Handle undef ^ undef -> 0 special case. This is a common
908 return Constant::getNullValue(C1->getType());
910 case Instruction::Add:
911 case Instruction::Sub:
912 return UndefValue::get(C1->getType());
913 case Instruction::And:
914 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
916 return Constant::getNullValue(C1->getType()); // undef & X -> 0
917 case Instruction::Mul: {
919 // X * undef -> undef if X is odd or undef
920 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
921 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
922 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
923 return UndefValue::get(C1->getType());
925 // X * undef -> 0 otherwise
926 return Constant::getNullValue(C1->getType());
928 case Instruction::SDiv:
929 case Instruction::UDiv:
930 // X / undef -> undef
931 if (match(C1, m_Zero()))
933 // undef / 0 -> undef
934 // undef / 1 -> undef
935 if (match(C2, m_Zero()) || match(C2, m_One()))
937 // undef / X -> 0 otherwise
938 return Constant::getNullValue(C1->getType());
939 case Instruction::URem:
940 case Instruction::SRem:
941 // X % undef -> undef
942 if (match(C2, m_Undef()))
944 // undef % 0 -> undef
945 if (match(C2, m_Zero()))
947 // undef % X -> 0 otherwise
948 return Constant::getNullValue(C1->getType());
949 case Instruction::Or: // X | undef -> -1
950 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
952 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
953 case Instruction::LShr:
954 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
955 return C1; // undef lshr undef -> undef
956 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
958 case Instruction::AShr:
959 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones
960 return Constant::getAllOnesValue(C1->getType());
961 else if (isa<UndefValue>(C1))
962 return C1; // undef ashr undef -> undef
964 return C1; // X ashr undef --> X
965 case Instruction::Shl:
966 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
967 return C1; // undef shl undef -> undef
968 // undef << X -> 0 or X << undef -> 0
969 return Constant::getNullValue(C1->getType());
973 // Handle simplifications when the RHS is a constant int.
974 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
976 case Instruction::Add:
977 if (CI2->equalsInt(0)) return C1; // X + 0 == X
979 case Instruction::Sub:
980 if (CI2->equalsInt(0)) return C1; // X - 0 == X
982 case Instruction::Mul:
983 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
984 if (CI2->equalsInt(1))
985 return C1; // X * 1 == X
987 case Instruction::UDiv:
988 case Instruction::SDiv:
989 if (CI2->equalsInt(1))
990 return C1; // X / 1 == X
991 if (CI2->equalsInt(0))
992 return UndefValue::get(CI2->getType()); // X / 0 == undef
994 case Instruction::URem:
995 case Instruction::SRem:
996 if (CI2->equalsInt(1))
997 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
998 if (CI2->equalsInt(0))
999 return UndefValue::get(CI2->getType()); // X % 0 == undef
1001 case Instruction::And:
1002 if (CI2->isZero()) return C2; // X & 0 == 0
1003 if (CI2->isAllOnesValue())
1004 return C1; // X & -1 == X
1006 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1007 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1008 if (CE1->getOpcode() == Instruction::ZExt) {
1009 unsigned DstWidth = CI2->getType()->getBitWidth();
1011 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1012 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1013 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1017 // If and'ing the address of a global with a constant, fold it.
1018 if (CE1->getOpcode() == Instruction::PtrToInt &&
1019 isa<GlobalValue>(CE1->getOperand(0))) {
1020 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1022 // Functions are at least 4-byte aligned.
1023 unsigned GVAlign = GV->getAlignment();
1024 if (isa<Function>(GV))
1025 GVAlign = std::max(GVAlign, 4U);
1028 unsigned DstWidth = CI2->getType()->getBitWidth();
1029 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1030 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1032 // If checking bits we know are clear, return zero.
1033 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1034 return Constant::getNullValue(CI2->getType());
1039 case Instruction::Or:
1040 if (CI2->equalsInt(0)) return C1; // X | 0 == X
1041 if (CI2->isAllOnesValue())
1042 return C2; // X | -1 == -1
1044 case Instruction::Xor:
1045 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
1047 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1048 switch (CE1->getOpcode()) {
1050 case Instruction::ICmp:
1051 case Instruction::FCmp:
1052 // cmp pred ^ true -> cmp !pred
1053 assert(CI2->equalsInt(1));
1054 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1055 pred = CmpInst::getInversePredicate(pred);
1056 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1057 CE1->getOperand(1));
1061 case Instruction::AShr:
1062 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1063 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1064 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1065 return ConstantExpr::getLShr(C1, C2);
1068 } else if (isa<ConstantInt>(C1)) {
1069 // If C1 is a ConstantInt and C2 is not, swap the operands.
1070 if (Instruction::isCommutative(Opcode))
1071 return ConstantExpr::get(Opcode, C2, C1);
1074 // At this point we know neither constant is an UndefValue.
1075 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1076 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1077 const APInt &C1V = CI1->getValue();
1078 const APInt &C2V = CI2->getValue();
1082 case Instruction::Add:
1083 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1084 case Instruction::Sub:
1085 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1086 case Instruction::Mul:
1087 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1088 case Instruction::UDiv:
1089 assert(!CI2->isNullValue() && "Div by zero handled above");
1090 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1091 case Instruction::SDiv:
1092 assert(!CI2->isNullValue() && "Div by zero handled above");
1093 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1094 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
1095 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1096 case Instruction::URem:
1097 assert(!CI2->isNullValue() && "Div by zero handled above");
1098 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1099 case Instruction::SRem:
1100 assert(!CI2->isNullValue() && "Div by zero handled above");
1101 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1102 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
1103 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1104 case Instruction::And:
1105 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1106 case Instruction::Or:
1107 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1108 case Instruction::Xor:
1109 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1110 case Instruction::Shl: {
1111 uint32_t shiftAmt = C2V.getZExtValue();
1112 if (shiftAmt < C1V.getBitWidth())
1113 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1115 return UndefValue::get(C1->getType()); // too big shift is undef
1117 case Instruction::LShr: {
1118 uint32_t shiftAmt = C2V.getZExtValue();
1119 if (shiftAmt < C1V.getBitWidth())
1120 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1122 return UndefValue::get(C1->getType()); // too big shift is undef
1124 case Instruction::AShr: {
1125 uint32_t shiftAmt = C2V.getZExtValue();
1126 if (shiftAmt < C1V.getBitWidth())
1127 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1129 return UndefValue::get(C1->getType()); // too big shift is undef
1135 case Instruction::SDiv:
1136 case Instruction::UDiv:
1137 case Instruction::URem:
1138 case Instruction::SRem:
1139 case Instruction::LShr:
1140 case Instruction::AShr:
1141 case Instruction::Shl:
1142 if (CI1->equalsInt(0)) return C1;
1147 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1148 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1149 APFloat C1V = CFP1->getValueAPF();
1150 APFloat C2V = CFP2->getValueAPF();
1151 APFloat C3V = C1V; // copy for modification
1155 case Instruction::FAdd:
1156 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1157 return ConstantFP::get(C1->getContext(), C3V);
1158 case Instruction::FSub:
1159 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1160 return ConstantFP::get(C1->getContext(), C3V);
1161 case Instruction::FMul:
1162 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1163 return ConstantFP::get(C1->getContext(), C3V);
1164 case Instruction::FDiv:
1165 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1166 return ConstantFP::get(C1->getContext(), C3V);
1167 case Instruction::FRem:
1168 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1169 return ConstantFP::get(C1->getContext(), C3V);
1172 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1173 // Perform elementwise folding.
1174 SmallVector<Constant*, 16> Result;
1175 Type *Ty = IntegerType::get(VTy->getContext(), 32);
1176 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1178 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1180 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1182 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1185 return ConstantVector::get(Result);
1188 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1189 // There are many possible foldings we could do here. We should probably
1190 // at least fold add of a pointer with an integer into the appropriate
1191 // getelementptr. This will improve alias analysis a bit.
1193 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1195 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1196 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1197 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1198 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1200 } else if (isa<ConstantExpr>(C2)) {
1201 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1202 // other way if possible.
1203 if (Instruction::isCommutative(Opcode))
1204 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1207 // i1 can be simplified in many cases.
1208 if (C1->getType()->isIntegerTy(1)) {
1210 case Instruction::Add:
1211 case Instruction::Sub:
1212 return ConstantExpr::getXor(C1, C2);
1213 case Instruction::Mul:
1214 return ConstantExpr::getAnd(C1, C2);
1215 case Instruction::Shl:
1216 case Instruction::LShr:
1217 case Instruction::AShr:
1218 // We can assume that C2 == 0. If it were one the result would be
1219 // undefined because the shift value is as large as the bitwidth.
1221 case Instruction::SDiv:
1222 case Instruction::UDiv:
1223 // We can assume that C2 == 1. If it were zero the result would be
1224 // undefined through division by zero.
1226 case Instruction::URem:
1227 case Instruction::SRem:
1228 // We can assume that C2 == 1. If it were zero the result would be
1229 // undefined through division by zero.
1230 return ConstantInt::getFalse(C1->getContext());
1236 // We don't know how to fold this.
1240 /// isZeroSizedType - This type is zero sized if its an array or structure of
1241 /// zero sized types. The only leaf zero sized type is an empty structure.
1242 static bool isMaybeZeroSizedType(Type *Ty) {
1243 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1244 if (STy->isOpaque()) return true; // Can't say.
1246 // If all of elements have zero size, this does too.
1247 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1248 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1251 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1252 return isMaybeZeroSizedType(ATy->getElementType());
1257 /// IdxCompare - Compare the two constants as though they were getelementptr
1258 /// indices. This allows coersion of the types to be the same thing.
1260 /// If the two constants are the "same" (after coersion), return 0. If the
1261 /// first is less than the second, return -1, if the second is less than the
1262 /// first, return 1. If the constants are not integral, return -2.
1264 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1265 if (C1 == C2) return 0;
1267 // Ok, we found a different index. If they are not ConstantInt, we can't do
1268 // anything with them.
1269 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1270 return -2; // don't know!
1272 // Ok, we have two differing integer indices. Sign extend them to be the same
1273 // type. Long is always big enough, so we use it.
1274 if (!C1->getType()->isIntegerTy(64))
1275 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1277 if (!C2->getType()->isIntegerTy(64))
1278 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1280 if (C1 == C2) return 0; // They are equal
1282 // If the type being indexed over is really just a zero sized type, there is
1283 // no pointer difference being made here.
1284 if (isMaybeZeroSizedType(ElTy))
1285 return -2; // dunno.
1287 // If they are really different, now that they are the same type, then we
1288 // found a difference!
1289 if (cast<ConstantInt>(C1)->getSExtValue() <
1290 cast<ConstantInt>(C2)->getSExtValue())
1296 /// evaluateFCmpRelation - This function determines if there is anything we can
1297 /// decide about the two constants provided. This doesn't need to handle simple
1298 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1299 /// If we can determine that the two constants have a particular relation to
1300 /// each other, we should return the corresponding FCmpInst predicate,
1301 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1302 /// ConstantFoldCompareInstruction.
1304 /// To simplify this code we canonicalize the relation so that the first
1305 /// operand is always the most "complex" of the two. We consider ConstantFP
1306 /// to be the simplest, and ConstantExprs to be the most complex.
1307 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1308 assert(V1->getType() == V2->getType() &&
1309 "Cannot compare values of different types!");
1311 // Handle degenerate case quickly
1312 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1314 if (!isa<ConstantExpr>(V1)) {
1315 if (!isa<ConstantExpr>(V2)) {
1316 // We distilled thisUse the standard constant folder for a few cases
1317 ConstantInt *R = nullptr;
1318 R = dyn_cast<ConstantInt>(
1319 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1320 if (R && !R->isZero())
1321 return FCmpInst::FCMP_OEQ;
1322 R = dyn_cast<ConstantInt>(
1323 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1324 if (R && !R->isZero())
1325 return FCmpInst::FCMP_OLT;
1326 R = dyn_cast<ConstantInt>(
1327 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1328 if (R && !R->isZero())
1329 return FCmpInst::FCMP_OGT;
1331 // Nothing more we can do
1332 return FCmpInst::BAD_FCMP_PREDICATE;
1335 // If the first operand is simple and second is ConstantExpr, swap operands.
1336 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1337 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1338 return FCmpInst::getSwappedPredicate(SwappedRelation);
1340 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1341 // constantexpr or a simple constant.
1342 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1343 switch (CE1->getOpcode()) {
1344 case Instruction::FPTrunc:
1345 case Instruction::FPExt:
1346 case Instruction::UIToFP:
1347 case Instruction::SIToFP:
1348 // We might be able to do something with these but we don't right now.
1354 // There are MANY other foldings that we could perform here. They will
1355 // probably be added on demand, as they seem needed.
1356 return FCmpInst::BAD_FCMP_PREDICATE;
1359 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1360 const GlobalValue *GV2) {
1361 auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1362 if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
1364 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1365 Type *Ty = GVar->getType()->getPointerElementType();
1366 // A global with opaque type might end up being zero sized.
1369 // A global with an empty type might lie at the address of any other
1371 if (Ty->isEmptyTy())
1376 // Don't try to decide equality of aliases.
1377 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1378 if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1379 return ICmpInst::ICMP_NE;
1380 return ICmpInst::BAD_ICMP_PREDICATE;
1383 /// evaluateICmpRelation - This function determines if there is anything we can
1384 /// decide about the two constants provided. This doesn't need to handle simple
1385 /// things like integer comparisons, but should instead handle ConstantExprs
1386 /// and GlobalValues. If we can determine that the two constants have a
1387 /// particular relation to each other, we should return the corresponding ICmp
1388 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1390 /// To simplify this code we canonicalize the relation so that the first
1391 /// operand is always the most "complex" of the two. We consider simple
1392 /// constants (like ConstantInt) to be the simplest, followed by
1393 /// GlobalValues, followed by ConstantExpr's (the most complex).
1395 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1397 assert(V1->getType() == V2->getType() &&
1398 "Cannot compare different types of values!");
1399 if (V1 == V2) return ICmpInst::ICMP_EQ;
1401 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1402 !isa<BlockAddress>(V1)) {
1403 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1404 !isa<BlockAddress>(V2)) {
1405 // We distilled this down to a simple case, use the standard constant
1407 ConstantInt *R = nullptr;
1408 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1409 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1410 if (R && !R->isZero())
1412 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1413 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1414 if (R && !R->isZero())
1416 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1417 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1418 if (R && !R->isZero())
1421 // If we couldn't figure it out, bail.
1422 return ICmpInst::BAD_ICMP_PREDICATE;
1425 // If the first operand is simple, swap operands.
1426 ICmpInst::Predicate SwappedRelation =
1427 evaluateICmpRelation(V2, V1, isSigned);
1428 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1429 return ICmpInst::getSwappedPredicate(SwappedRelation);
1431 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1432 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1433 ICmpInst::Predicate SwappedRelation =
1434 evaluateICmpRelation(V2, V1, isSigned);
1435 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1436 return ICmpInst::getSwappedPredicate(SwappedRelation);
1437 return ICmpInst::BAD_ICMP_PREDICATE;
1440 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1441 // constant (which, since the types must match, means that it's a
1442 // ConstantPointerNull).
1443 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1444 return areGlobalsPotentiallyEqual(GV, GV2);
1445 } else if (isa<BlockAddress>(V2)) {
1446 return ICmpInst::ICMP_NE; // Globals never equal labels.
1448 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1449 // GlobalVals can never be null unless they have external weak linkage.
1450 // We don't try to evaluate aliases here.
1451 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1452 return ICmpInst::ICMP_NE;
1454 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1455 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1456 ICmpInst::Predicate SwappedRelation =
1457 evaluateICmpRelation(V2, V1, isSigned);
1458 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1459 return ICmpInst::getSwappedPredicate(SwappedRelation);
1460 return ICmpInst::BAD_ICMP_PREDICATE;
1463 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1464 // constant (which, since the types must match, means that it is a
1465 // ConstantPointerNull).
1466 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1467 // Block address in another function can't equal this one, but block
1468 // addresses in the current function might be the same if blocks are
1470 if (BA2->getFunction() != BA->getFunction())
1471 return ICmpInst::ICMP_NE;
1473 // Block addresses aren't null, don't equal the address of globals.
1474 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1475 "Canonicalization guarantee!");
1476 return ICmpInst::ICMP_NE;
1479 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1480 // constantexpr, a global, block address, or a simple constant.
1481 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1482 Constant *CE1Op0 = CE1->getOperand(0);
1484 switch (CE1->getOpcode()) {
1485 case Instruction::Trunc:
1486 case Instruction::FPTrunc:
1487 case Instruction::FPExt:
1488 case Instruction::FPToUI:
1489 case Instruction::FPToSI:
1490 break; // We can't evaluate floating point casts or truncations.
1492 case Instruction::UIToFP:
1493 case Instruction::SIToFP:
1494 case Instruction::BitCast:
1495 case Instruction::ZExt:
1496 case Instruction::SExt:
1497 // If the cast is not actually changing bits, and the second operand is a
1498 // null pointer, do the comparison with the pre-casted value.
1499 if (V2->isNullValue() &&
1500 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1501 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1502 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1503 return evaluateICmpRelation(CE1Op0,
1504 Constant::getNullValue(CE1Op0->getType()),
1509 case Instruction::GetElementPtr: {
1510 GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1511 // Ok, since this is a getelementptr, we know that the constant has a
1512 // pointer type. Check the various cases.
1513 if (isa<ConstantPointerNull>(V2)) {
1514 // If we are comparing a GEP to a null pointer, check to see if the base
1515 // of the GEP equals the null pointer.
1516 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1517 if (GV->hasExternalWeakLinkage())
1518 // Weak linkage GVals could be zero or not. We're comparing that
1519 // to null pointer so its greater-or-equal
1520 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1522 // If its not weak linkage, the GVal must have a non-zero address
1523 // so the result is greater-than
1524 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1525 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1526 // If we are indexing from a null pointer, check to see if we have any
1527 // non-zero indices.
1528 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1529 if (!CE1->getOperand(i)->isNullValue())
1530 // Offsetting from null, must not be equal.
1531 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1532 // Only zero indexes from null, must still be zero.
1533 return ICmpInst::ICMP_EQ;
1535 // Otherwise, we can't really say if the first operand is null or not.
1536 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1537 if (isa<ConstantPointerNull>(CE1Op0)) {
1538 if (GV2->hasExternalWeakLinkage())
1539 // Weak linkage GVals could be zero or not. We're comparing it to
1540 // a null pointer, so its less-or-equal
1541 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1543 // If its not weak linkage, the GVal must have a non-zero address
1544 // so the result is less-than
1545 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1546 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1548 // If this is a getelementptr of the same global, then it must be
1549 // different. Because the types must match, the getelementptr could
1550 // only have at most one index, and because we fold getelementptr's
1551 // with a single zero index, it must be nonzero.
1552 assert(CE1->getNumOperands() == 2 &&
1553 !CE1->getOperand(1)->isNullValue() &&
1554 "Surprising getelementptr!");
1555 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1557 if (CE1GEP->hasAllZeroIndices())
1558 return areGlobalsPotentiallyEqual(GV, GV2);
1559 return ICmpInst::BAD_ICMP_PREDICATE;
1563 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1564 Constant *CE2Op0 = CE2->getOperand(0);
1566 // There are MANY other foldings that we could perform here. They will
1567 // probably be added on demand, as they seem needed.
1568 switch (CE2->getOpcode()) {
1570 case Instruction::GetElementPtr:
1571 // By far the most common case to handle is when the base pointers are
1572 // obviously to the same global.
1573 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1574 // Don't know relative ordering, but check for inequality.
1575 if (CE1Op0 != CE2Op0) {
1576 GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1577 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1578 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1579 cast<GlobalValue>(CE2Op0));
1580 return ICmpInst::BAD_ICMP_PREDICATE;
1582 // Ok, we know that both getelementptr instructions are based on the
1583 // same global. From this, we can precisely determine the relative
1584 // ordering of the resultant pointers.
1587 // The logic below assumes that the result of the comparison
1588 // can be determined by finding the first index that differs.
1589 // This doesn't work if there is over-indexing in any
1590 // subsequent indices, so check for that case first.
1591 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1592 !CE2->isGEPWithNoNotionalOverIndexing())
1593 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1595 // Compare all of the operands the GEP's have in common.
1596 gep_type_iterator GTI = gep_type_begin(CE1);
1597 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1599 switch (IdxCompare(CE1->getOperand(i),
1600 CE2->getOperand(i), GTI.getIndexedType())) {
1601 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1602 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1603 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1606 // Ok, we ran out of things they have in common. If any leftovers
1607 // are non-zero then we have a difference, otherwise we are equal.
1608 for (; i < CE1->getNumOperands(); ++i)
1609 if (!CE1->getOperand(i)->isNullValue()) {
1610 if (isa<ConstantInt>(CE1->getOperand(i)))
1611 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1613 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1616 for (; i < CE2->getNumOperands(); ++i)
1617 if (!CE2->getOperand(i)->isNullValue()) {
1618 if (isa<ConstantInt>(CE2->getOperand(i)))
1619 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1621 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1623 return ICmpInst::ICMP_EQ;
1633 return ICmpInst::BAD_ICMP_PREDICATE;
1636 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1637 Constant *C1, Constant *C2) {
1639 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1640 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1641 VT->getNumElements());
1643 ResultTy = Type::getInt1Ty(C1->getContext());
1645 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1646 if (pred == FCmpInst::FCMP_FALSE)
1647 return Constant::getNullValue(ResultTy);
1649 if (pred == FCmpInst::FCMP_TRUE)
1650 return Constant::getAllOnesValue(ResultTy);
1652 // Handle some degenerate cases first
1653 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1654 // For EQ and NE, we can always pick a value for the undef to make the
1655 // predicate pass or fail, so we can return undef.
1656 // Also, if both operands are undef, we can return undef.
1657 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1658 (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1659 return UndefValue::get(ResultTy);
1660 // Otherwise, pick the same value as the non-undef operand, and fold
1661 // it to true or false.
1662 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1665 // icmp eq/ne(null,GV) -> false/true
1666 if (C1->isNullValue()) {
1667 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1668 // Don't try to evaluate aliases. External weak GV can be null.
1669 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1670 if (pred == ICmpInst::ICMP_EQ)
1671 return ConstantInt::getFalse(C1->getContext());
1672 else if (pred == ICmpInst::ICMP_NE)
1673 return ConstantInt::getTrue(C1->getContext());
1675 // icmp eq/ne(GV,null) -> false/true
1676 } else if (C2->isNullValue()) {
1677 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1678 // Don't try to evaluate aliases. External weak GV can be null.
1679 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1680 if (pred == ICmpInst::ICMP_EQ)
1681 return ConstantInt::getFalse(C1->getContext());
1682 else if (pred == ICmpInst::ICMP_NE)
1683 return ConstantInt::getTrue(C1->getContext());
1687 // If the comparison is a comparison between two i1's, simplify it.
1688 if (C1->getType()->isIntegerTy(1)) {
1690 case ICmpInst::ICMP_EQ:
1691 if (isa<ConstantInt>(C2))
1692 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1693 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1694 case ICmpInst::ICMP_NE:
1695 return ConstantExpr::getXor(C1, C2);
1701 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1702 APInt V1 = cast<ConstantInt>(C1)->getValue();
1703 APInt V2 = cast<ConstantInt>(C2)->getValue();
1705 default: llvm_unreachable("Invalid ICmp Predicate");
1706 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1707 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1708 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1709 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1710 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1711 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1712 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1713 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1714 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1715 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1717 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1718 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1719 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1720 APFloat::cmpResult R = C1V.compare(C2V);
1722 default: llvm_unreachable("Invalid FCmp Predicate");
1723 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1724 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
1725 case FCmpInst::FCMP_UNO:
1726 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1727 case FCmpInst::FCMP_ORD:
1728 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1729 case FCmpInst::FCMP_UEQ:
1730 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1731 R==APFloat::cmpEqual);
1732 case FCmpInst::FCMP_OEQ:
1733 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1734 case FCmpInst::FCMP_UNE:
1735 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1736 case FCmpInst::FCMP_ONE:
1737 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1738 R==APFloat::cmpGreaterThan);
1739 case FCmpInst::FCMP_ULT:
1740 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1741 R==APFloat::cmpLessThan);
1742 case FCmpInst::FCMP_OLT:
1743 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1744 case FCmpInst::FCMP_UGT:
1745 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1746 R==APFloat::cmpGreaterThan);
1747 case FCmpInst::FCMP_OGT:
1748 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1749 case FCmpInst::FCMP_ULE:
1750 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1751 case FCmpInst::FCMP_OLE:
1752 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1753 R==APFloat::cmpEqual);
1754 case FCmpInst::FCMP_UGE:
1755 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1756 case FCmpInst::FCMP_OGE:
1757 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1758 R==APFloat::cmpEqual);
1760 } else if (C1->getType()->isVectorTy()) {
1761 // If we can constant fold the comparison of each element, constant fold
1762 // the whole vector comparison.
1763 SmallVector<Constant*, 4> ResElts;
1764 Type *Ty = IntegerType::get(C1->getContext(), 32);
1765 // Compare the elements, producing an i1 result or constant expr.
1766 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1768 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1770 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1772 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1775 return ConstantVector::get(ResElts);
1778 if (C1->getType()->isFloatingPointTy()) {
1779 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1780 switch (evaluateFCmpRelation(C1, C2)) {
1781 default: llvm_unreachable("Unknown relation!");
1782 case FCmpInst::FCMP_UNO:
1783 case FCmpInst::FCMP_ORD:
1784 case FCmpInst::FCMP_UEQ:
1785 case FCmpInst::FCMP_UNE:
1786 case FCmpInst::FCMP_ULT:
1787 case FCmpInst::FCMP_UGT:
1788 case FCmpInst::FCMP_ULE:
1789 case FCmpInst::FCMP_UGE:
1790 case FCmpInst::FCMP_TRUE:
1791 case FCmpInst::FCMP_FALSE:
1792 case FCmpInst::BAD_FCMP_PREDICATE:
1793 break; // Couldn't determine anything about these constants.
1794 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1795 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1796 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1797 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1799 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1800 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1801 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1802 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1804 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1805 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1806 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1807 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1809 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1810 // We can only partially decide this relation.
1811 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1813 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1816 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1817 // We can only partially decide this relation.
1818 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1820 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1823 case FCmpInst::FCMP_ONE: // We know that C1 != C2
1824 // We can only partially decide this relation.
1825 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1827 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1832 // If we evaluated the result, return it now.
1834 return ConstantInt::get(ResultTy, Result);
1837 // Evaluate the relation between the two constants, per the predicate.
1838 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1839 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1840 default: llvm_unreachable("Unknown relational!");
1841 case ICmpInst::BAD_ICMP_PREDICATE:
1842 break; // Couldn't determine anything about these constants.
1843 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1844 // If we know the constants are equal, we can decide the result of this
1845 // computation precisely.
1846 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1848 case ICmpInst::ICMP_ULT:
1850 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1852 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1856 case ICmpInst::ICMP_SLT:
1858 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1860 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1864 case ICmpInst::ICMP_UGT:
1866 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1868 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1872 case ICmpInst::ICMP_SGT:
1874 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1876 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1880 case ICmpInst::ICMP_ULE:
1881 if (pred == ICmpInst::ICMP_UGT) Result = 0;
1882 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1884 case ICmpInst::ICMP_SLE:
1885 if (pred == ICmpInst::ICMP_SGT) Result = 0;
1886 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1888 case ICmpInst::ICMP_UGE:
1889 if (pred == ICmpInst::ICMP_ULT) Result = 0;
1890 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1892 case ICmpInst::ICMP_SGE:
1893 if (pred == ICmpInst::ICMP_SLT) Result = 0;
1894 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1896 case ICmpInst::ICMP_NE:
1897 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1898 if (pred == ICmpInst::ICMP_NE) Result = 1;
1902 // If we evaluated the result, return it now.
1904 return ConstantInt::get(ResultTy, Result);
1906 // If the right hand side is a bitcast, try using its inverse to simplify
1907 // it by moving it to the left hand side. We can't do this if it would turn
1908 // a vector compare into a scalar compare or visa versa.
1909 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1910 Constant *CE2Op0 = CE2->getOperand(0);
1911 if (CE2->getOpcode() == Instruction::BitCast &&
1912 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1913 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1914 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1918 // If the left hand side is an extension, try eliminating it.
1919 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1920 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1921 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1922 Constant *CE1Op0 = CE1->getOperand(0);
1923 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1924 if (CE1Inverse == CE1Op0) {
1925 // Check whether we can safely truncate the right hand side.
1926 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1927 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
1928 C2->getType()) == C2)
1929 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1934 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1935 (C1->isNullValue() && !C2->isNullValue())) {
1936 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1937 // other way if possible.
1938 // Also, if C1 is null and C2 isn't, flip them around.
1939 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1940 return ConstantExpr::getICmp(pred, C2, C1);
1946 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1948 template<typename IndexTy>
1949 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1950 // No indices means nothing that could be out of bounds.
1951 if (Idxs.empty()) return true;
1953 // If the first index is zero, it's in bounds.
1954 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1956 // If the first index is one and all the rest are zero, it's in bounds,
1957 // by the one-past-the-end rule.
1958 if (!cast<ConstantInt>(Idxs[0])->isOne())
1960 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1961 if (!cast<Constant>(Idxs[i])->isNullValue())
1966 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
1967 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
1968 const ConstantInt *CI) {
1969 if (const PointerType *PTy = dyn_cast<PointerType>(STy))
1970 // Only handle pointers to sized types, not pointers to functions.
1971 return PTy->getElementType()->isSized();
1973 uint64_t NumElements = 0;
1974 // Determine the number of elements in our sequential type.
1975 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
1976 NumElements = ATy->getNumElements();
1977 else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
1978 NumElements = VTy->getNumElements();
1980 assert((isa<ArrayType>(STy) || NumElements > 0) &&
1981 "didn't expect non-array type to have zero elements!");
1983 // We cannot bounds check the index if it doesn't fit in an int64_t.
1984 if (CI->getValue().getActiveBits() > 64)
1987 // A negative index or an index past the end of our sequential type is
1988 // considered out-of-range.
1989 int64_t IndexVal = CI->getSExtValue();
1990 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
1993 // Otherwise, it is in-range.
1997 template<typename IndexTy>
1998 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
2000 ArrayRef<IndexTy> Idxs) {
2001 if (Idxs.empty()) return C;
2002 Constant *Idx0 = cast<Constant>(Idxs[0]);
2003 if ((Idxs.size() == 1 && Idx0->isNullValue()))
2006 if (isa<UndefValue>(C)) {
2007 PointerType *Ptr = cast<PointerType>(C->getType());
2008 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
2009 assert(Ty && "Invalid indices for GEP!");
2010 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2013 if (C->isNullValue()) {
2015 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2016 if (!cast<Constant>(Idxs[i])->isNullValue()) {
2021 PointerType *Ptr = cast<PointerType>(C->getType());
2022 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
2023 assert(Ty && "Invalid indices for GEP!");
2024 return ConstantPointerNull::get(PointerType::get(Ty,
2025 Ptr->getAddressSpace()));
2029 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2030 // Combine Indices - If the source pointer to this getelementptr instruction
2031 // is a getelementptr instruction, combine the indices of the two
2032 // getelementptr instructions into a single instruction.
2034 if (CE->getOpcode() == Instruction::GetElementPtr) {
2035 Type *LastTy = nullptr;
2036 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2040 // We cannot combine indices if doing so would take us outside of an
2041 // array or vector. Doing otherwise could trick us if we evaluated such a
2042 // GEP as part of a load.
2044 // e.g. Consider if the original GEP was:
2045 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2046 // i32 0, i32 0, i64 0)
2048 // If we then tried to offset it by '8' to get to the third element,
2049 // an i8, we should *not* get:
2050 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2051 // i32 0, i32 0, i64 8)
2053 // This GEP tries to index array element '8 which runs out-of-bounds.
2054 // Subsequent evaluation would get confused and produce erroneous results.
2056 // The following prohibits such a GEP from being formed by checking to see
2057 // if the index is in-range with respect to an array or vector.
2058 bool PerformFold = false;
2059 if (Idx0->isNullValue())
2061 else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
2062 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2063 PerformFold = isIndexInRangeOfSequentialType(STy, CI);
2066 SmallVector<Value*, 16> NewIndices;
2067 NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2068 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2069 NewIndices.push_back(CE->getOperand(i));
2071 // Add the last index of the source with the first index of the new GEP.
2072 // Make sure to handle the case when they are actually different types.
2073 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2074 // Otherwise it must be an array.
2075 if (!Idx0->isNullValue()) {
2076 Type *IdxTy = Combined->getType();
2077 if (IdxTy != Idx0->getType()) {
2078 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2079 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2080 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2081 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2084 ConstantExpr::get(Instruction::Add, Idx0, Combined);
2088 NewIndices.push_back(Combined);
2089 NewIndices.append(Idxs.begin() + 1, Idxs.end());
2091 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
2093 cast<GEPOperator>(CE)->isInBounds());
2097 // Attempt to fold casts to the same type away. For example, folding:
2099 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2103 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2105 // Don't fold if the cast is changing address spaces.
2106 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2107 PointerType *SrcPtrTy =
2108 dyn_cast<PointerType>(CE->getOperand(0)->getType());
2109 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2110 if (SrcPtrTy && DstPtrTy) {
2111 ArrayType *SrcArrayTy =
2112 dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2113 ArrayType *DstArrayTy =
2114 dyn_cast<ArrayType>(DstPtrTy->getElementType());
2115 if (SrcArrayTy && DstArrayTy
2116 && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2117 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2118 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
2124 // Check to see if any array indices are not within the corresponding
2125 // notional array or vector bounds. If so, try to determine if they can be
2126 // factored out into preceding dimensions.
2127 bool Unknown = false;
2128 SmallVector<Constant *, 8> NewIdxs;
2129 Type *Ty = C->getType();
2130 Type *Prev = nullptr;
2131 for (unsigned i = 0, e = Idxs.size(); i != e;
2132 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2133 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2134 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
2135 if (CI->getSExtValue() > 0 &&
2136 !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
2137 if (isa<SequentialType>(Prev)) {
2138 // It's out of range, but we can factor it into the prior
2140 NewIdxs.resize(Idxs.size());
2141 uint64_t NumElements = 0;
2142 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2143 NumElements = ATy->getNumElements();
2145 NumElements = cast<VectorType>(Ty)->getNumElements();
2147 ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
2148 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2150 Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2151 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2153 // Before adding, extend both operands to i64 to avoid
2154 // overflow trouble.
2155 if (!PrevIdx->getType()->isIntegerTy(64))
2156 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2157 Type::getInt64Ty(Div->getContext()));
2158 if (!Div->getType()->isIntegerTy(64))
2159 Div = ConstantExpr::getSExt(Div,
2160 Type::getInt64Ty(Div->getContext()));
2162 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2164 // It's out of range, but the prior dimension is a struct
2165 // so we can't do anything about it.
2170 // We don't know if it's in range or not.
2175 // If we did any factoring, start over with the adjusted indices.
2176 if (!NewIdxs.empty()) {
2177 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2178 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2179 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2182 // If all indices are known integers and normalized, we can do a simple
2183 // check for the "inbounds" property.
2184 if (!Unknown && !inBounds)
2185 if (auto *GV = dyn_cast<GlobalVariable>(C))
2186 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2187 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2192 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2194 ArrayRef<Constant *> Idxs) {
2195 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2198 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2200 ArrayRef<Value *> Idxs) {
2201 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);