blob: 4dc1340f908cc0ffc9c40b23471e81e4543fa666 [file] [log] [blame]
Reid Spencer81658a82007-02-27 06:23:51 +00001//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner5a945e32004-01-12 21:13:12 +000010// This file implements folding of constants for LLVM. This implements the
Reid Spencer81658a82007-02-27 06:23:51 +000011// (internal) ConstantFold.h interface, which is used by the
Chris Lattner5a945e32004-01-12 21:13:12 +000012// ConstantExpr::get* methods to automatically fold constants when possible.
Chris Lattner2f7c9632001-06-06 20:29:01 +000013//
Chris Lattner1dd054c2004-01-12 22:07:24 +000014// The current constant folding implementation is implemented in two pieces: the
15// template-based folder for simple primitive constants like ConstantInt, and
16// the special case hackery that we use to symbolically evaluate expressions
17// that use ConstantExprs.
18//
Chris Lattner2f7c9632001-06-06 20:29:01 +000019//===----------------------------------------------------------------------===//
20
Chris Lattner33e93b82007-02-27 03:05:06 +000021#include "ConstantFold.h"
Chris Lattner6ff6cea2004-01-12 21:02:29 +000022#include "llvm/Constants.h"
Chris Lattnera9eddae2004-02-22 06:25:38 +000023#include "llvm/Instructions.h"
Chris Lattner1f0049c2003-04-17 19:24:18 +000024#include "llvm/DerivedTypes.h"
Chris Lattnerea0789c2004-03-08 06:17:35 +000025#include "llvm/Function.h"
Chris Lattner52fe8692007-09-10 23:42:42 +000026#include "llvm/GlobalAlias.h"
Chris Lattner302116a2007-01-31 04:40:28 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000028#include "llvm/Support/Compiler.h"
Chris Lattner057083f2006-10-13 17:22:21 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
30#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000032#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000033using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000034
Chris Lattner1dd054c2004-01-12 22:07:24 +000035//===----------------------------------------------------------------------===//
36// ConstantFold*Instruction Implementations
37//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000038
Reid Spencerd84d35b2007-02-15 02:26:10 +000039/// CastConstantVector - Convert the specified ConstantVector node to the
Reid Spencer09575ba2007-02-15 03:39:18 +000040/// specified vector type. At this point, we know that the elements of the
Dan Gohman06c60b62007-07-16 14:29:03 +000041/// input vector constant are all simple integer or FP values.
Reid Spencer81658a82007-02-27 06:23:51 +000042static Constant *CastConstantVector(ConstantVector *CV,
Reid Spencerd84d35b2007-02-15 02:26:10 +000043 const VectorType *DstTy) {
Reid Spencer81658a82007-02-27 06:23:51 +000044 unsigned SrcNumElts = CV->getType()->getNumElements();
Chris Lattner6b3f4752006-04-02 01:38:28 +000045 unsigned DstNumElts = DstTy->getNumElements();
Reid Spencer81658a82007-02-27 06:23:51 +000046 const Type *SrcEltTy = CV->getType()->getElementType();
Chris Lattner6b3f4752006-04-02 01:38:28 +000047 const Type *DstEltTy = DstTy->getElementType();
48
49 // If both vectors have the same number of elements (thus, the elements
50 // are the same size), perform the conversion now.
51 if (SrcNumElts == DstNumElts) {
52 std::vector<Constant*> Result;
53
Reid Spencer6c38f0b2006-11-27 01:05:10 +000054 // If the src and dest elements are both integers, or both floats, we can
55 // just BitCast each element because the elements are the same size.
Chris Lattner03c49532007-01-15 02:27:26 +000056 if ((SrcEltTy->isInteger() && DstEltTy->isInteger()) ||
Reid Spencer6c38f0b2006-11-27 01:05:10 +000057 (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
Chris Lattner6b3f4752006-04-02 01:38:28 +000058 for (unsigned i = 0; i != SrcNumElts; ++i)
Reid Spencer6c38f0b2006-11-27 01:05:10 +000059 Result.push_back(
Reid Spencer81658a82007-02-27 06:23:51 +000060 ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
Reid Spencerd84d35b2007-02-15 02:26:10 +000061 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000062 }
63
Reid Spencer6c38f0b2006-11-27 01:05:10 +000064 // If this is an int-to-fp cast ..
Chris Lattner03c49532007-01-15 02:27:26 +000065 if (SrcEltTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +000066 // Ensure that it is int-to-fp cast
Chris Lattner6b3f4752006-04-02 01:38:28 +000067 assert(DstEltTy->isFloatingPoint());
68 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
69 for (unsigned i = 0; i != SrcNumElts; ++i) {
Reid Spencer4326cf52007-03-01 20:44:23 +000070 ConstantInt *CI = cast<ConstantInt>(CV->getOperand(i));
71 double V = CI->getValue().bitsToDouble();
Dale Johannesenbed9dc42007-09-06 18:13:44 +000072 Result.push_back(ConstantFP::get(Type::DoubleTy, APFloat(V)));
Chris Lattner6b3f4752006-04-02 01:38:28 +000073 }
Reid Spencerd84d35b2007-02-15 02:26:10 +000074 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000075 }
76 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
77 for (unsigned i = 0; i != SrcNumElts; ++i) {
Reid Spencer4326cf52007-03-01 20:44:23 +000078 ConstantInt *CI = cast<ConstantInt>(CV->getOperand(i));
79 float V = CI->getValue().bitsToFloat();
Dale Johannesenbed9dc42007-09-06 18:13:44 +000080 Result.push_back(ConstantFP::get(Type::FloatTy, APFloat(V)));
Chris Lattner6b3f4752006-04-02 01:38:28 +000081 }
Reid Spencerd84d35b2007-02-15 02:26:10 +000082 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000083 }
84
85 // Otherwise, this is an fp-to-int cast.
Chris Lattner03c49532007-01-15 02:27:26 +000086 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isInteger());
Chris Lattner6b3f4752006-04-02 01:38:28 +000087
88 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
89 for (unsigned i = 0; i != SrcNumElts; ++i) {
Reid Spencer50d7ad92007-03-03 08:32:46 +000090 uint64_t V =
Dale Johannesenbed9dc42007-09-06 18:13:44 +000091 DoubleToBits(cast<ConstantFP>(CV->getOperand(i))->
92 getValueAPF().convertToDouble());
Reid Spencer50d7ad92007-03-03 08:32:46 +000093 Constant *C = ConstantInt::get(Type::Int64Ty, V);
Reid Spencera16f9302006-12-05 07:18:07 +000094 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
Chris Lattner6b3f4752006-04-02 01:38:28 +000095 }
Reid Spencerd84d35b2007-02-15 02:26:10 +000096 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000097 }
98
99 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
100 for (unsigned i = 0; i != SrcNumElts; ++i) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000101 uint32_t V = FloatToBits(cast<ConstantFP>(CV->getOperand(i))->
102 getValueAPF().convertToFloat());
Reid Spencer8d9336d2006-12-31 05:26:44 +0000103 Constant *C = ConstantInt::get(Type::Int32Ty, V);
Reid Spencera16f9302006-12-05 07:18:07 +0000104 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
Chris Lattner6b3f4752006-04-02 01:38:28 +0000105 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000106 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000107 }
108
109 // Otherwise, this is a cast that changes element count and size. Handle
110 // casts which shrink the elements here.
111
112 // FIXME: We need to know endianness to do this!
113
114 return 0;
115}
116
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000117/// This function determines which opcode to use to fold two constant cast
118/// expressions together. It uses CastInst::isEliminableCastPair to determine
119/// the opcode. Consequently its just a wrapper around that function.
Reid Spencer05d55b32007-08-05 19:27:01 +0000120/// @brief Determine if it is valid to fold a cast of a cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000121static unsigned
122foldConstantCastPair(
123 unsigned opc, ///< opcode of the second cast constant expression
124 const ConstantExpr*Op, ///< the first cast constant expression
125 const Type *DstTy ///< desintation type of the first cast
126) {
127 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
128 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
129 assert(CastInst::isCast(opc) && "Invalid cast opcode");
130
131 // The the types and opcodes for the two Cast constant expressions
132 const Type *SrcTy = Op->getOperand(0)->getType();
133 const Type *MidTy = Op->getType();
134 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
135 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000136
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000137 // Let CastInst::isEliminableCastPair do the heavy lifting.
138 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Reid Spencer8d9336d2006-12-31 05:26:44 +0000139 Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000140}
141
142Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
Chris Lattner1dd054c2004-01-12 22:07:24 +0000143 const Type *DestTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000144 const Type *SrcTy = V->getType();
Chris Lattner1dd054c2004-01-12 22:07:24 +0000145
Chris Lattner363485d2007-07-20 22:09:02 +0000146 if (isa<UndefValue>(V)) {
147 // zext(undef) = 0, because the top bits will be zero.
148 // sext(undef) = 0, because the top bits will all be the same.
149 if (opc == Instruction::ZExt || opc == Instruction::SExt)
150 return Constant::getNullValue(DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000151 return UndefValue::get(DestTy);
Chris Lattner363485d2007-07-20 22:09:02 +0000152 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000153
154 // If the cast operand is a constant expression, there's a few things we can
155 // do to try to simplify it.
156 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
157 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000158 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000159 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
160 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000161 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
162 // If all of the indexes in the GEP are null values, there is no pointer
163 // adjustment going on. We might as well cast the source pointer.
164 bool isAllNull = true;
165 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
166 if (!CE->getOperand(i)->isNullValue()) {
167 isAllNull = false;
168 break;
169 }
170 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000171 // This is casting one pointer type to another, always BitCast
Reid Spencer27720a92006-12-05 03:30:09 +0000172 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000173 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000174 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000175
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000176 // We actually have to do a cast now. Perform the cast according to the
177 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000178 switch (opc) {
179 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000180 case Instruction::FPExt:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000181 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
182 APFloat Val = FPC->getValueAPF();
183 Val.convert(DestTy==Type::FloatTy ? APFloat::IEEEsingle :
184 APFloat::IEEEdouble,
185 APFloat::rmNearestTiesToEven);
186 return ConstantFP::get(DestTy, Val);
187 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000188 return 0; // Can't fold.
189 case Instruction::FPToUI:
Reid Spencer81658a82007-02-27 06:23:51 +0000190 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000191 APFloat V = FPC->getValueAPF();
192 bool isDouble = &V.getSemantics()==&APFloat::IEEEdouble;
Reid Spencer81658a82007-02-27 06:23:51 +0000193 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000194 APInt Val(APIntOps::RoundDoubleToAPInt(isDouble ? V.convertToDouble() :
195 (double)V.convertToFloat(), DestBitWidth));
Reid Spencera1276332007-03-01 19:31:12 +0000196 return ConstantInt::get(Val);
Reid Spencer81658a82007-02-27 06:23:51 +0000197 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000198 return 0; // Can't fold.
199 case Instruction::FPToSI:
Reid Spencer81658a82007-02-27 06:23:51 +0000200 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000201 APFloat V = FPC->getValueAPF();
202 bool isDouble = &V.getSemantics()==&APFloat::IEEEdouble;
Reid Spencer81658a82007-02-27 06:23:51 +0000203 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000204 APInt Val(APIntOps::RoundDoubleToAPInt(isDouble ? V.convertToDouble() :
205 (double)V.convertToFloat(), DestBitWidth));
Reid Spencera1276332007-03-01 19:31:12 +0000206 return ConstantInt::get(Val);
Reid Spencer81658a82007-02-27 06:23:51 +0000207 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000208 return 0; // Can't fold.
209 case Instruction::IntToPtr: //always treated as unsigned
210 if (V->isNullValue()) // Is it an integral null value?
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000211 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000212 return 0; // Other pointer types cannot be casted
213 case Instruction::PtrToInt: // always treated as unsigned
214 if (V->isNullValue()) // is it a null pointer value?
Zhou Sheng75b871f2007-01-11 12:24:14 +0000215 return ConstantInt::get(DestTy, 0);
Reid Spencer8dabca42006-12-19 07:41:40 +0000216 return 0; // Other pointer types cannot be casted
217 case Instruction::UIToFP:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000218 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
219 if (DestTy==Type::FloatTy)
220 return ConstantFP::get(DestTy,
221 APFloat((float)CI->getValue().roundToDouble()));
222 else
223 return ConstantFP::get(DestTy, APFloat(CI->getValue().roundToDouble()));
224 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000225 return 0;
226 case Instruction::SIToFP:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000227 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
228 double d = CI->getValue().signedRoundToDouble();
229 if (DestTy==Type::FloatTy)
230 return ConstantFP::get(DestTy, APFloat((float)d));
231 else
232 return ConstantFP::get(DestTy, APFloat(d));
233 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000234 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000235 case Instruction::ZExt:
Reid Spencer81658a82007-02-27 06:23:51 +0000236 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
237 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
238 APInt Result(CI->getValue());
239 Result.zext(BitWidth);
Reid Spencera1276332007-03-01 19:31:12 +0000240 return ConstantInt::get(Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000241 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000242 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000243 case Instruction::SExt:
Reid Spencer81658a82007-02-27 06:23:51 +0000244 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
245 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
246 APInt Result(CI->getValue());
247 Result.sext(BitWidth);
Reid Spencera1276332007-03-01 19:31:12 +0000248 return ConstantInt::get(Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000249 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000250 return 0;
Chris Lattner710ebaf2006-12-01 19:22:41 +0000251 case Instruction::Trunc:
Reid Spencer81658a82007-02-27 06:23:51 +0000252 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
253 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
254 APInt Result(CI->getValue());
255 Result.trunc(BitWidth);
Reid Spencera1276332007-03-01 19:31:12 +0000256 return ConstantInt::get(Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000257 }
Chris Lattner710ebaf2006-12-01 19:22:41 +0000258 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000259 case Instruction::BitCast:
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000260 if (SrcTy == DestTy)
261 return (Constant*)V; // no-op cast
Chris Lattner4d1da162006-12-11 18:30:27 +0000262
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000263 // Check to see if we are casting a pointer to an aggregate to a pointer to
264 // the first element. If so, return the appropriate GEP instruction.
265 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
266 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattner302116a2007-01-31 04:40:28 +0000267 SmallVector<Value*, 8> IdxList;
Reid Spencer8d9336d2006-12-31 05:26:44 +0000268 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000269 const Type *ElTy = PTy->getElementType();
270 while (ElTy != DPTy->getElementType()) {
271 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
272 if (STy->getNumElements() == 0) break;
273 ElTy = STy->getElementType(0);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000274 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000275 } else if (const SequentialType *STy =
276 dyn_cast<SequentialType>(ElTy)) {
277 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
278 ElTy = STy->getElementType();
279 IdxList.push_back(IdxList[0]);
280 } else {
Chris Lattner6b3f4752006-04-02 01:38:28 +0000281 break;
282 }
283 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000284
285 if (ElTy == DPTy->getElementType())
286 return ConstantExpr::getGetElementPtr(
Chris Lattner302116a2007-01-31 04:40:28 +0000287 const_cast<Constant*>(V), &IdxList[0], IdxList.size());
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000288 }
289
Dan Gohman06c60b62007-07-16 14:29:03 +0000290 // Handle casts from one vector constant to another. We know that the src
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000291 // and dest type have the same size (otherwise its an illegal cast).
Reid Spencerd84d35b2007-02-15 02:26:10 +0000292 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
293 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000294 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
295 "Not cast between same sized vectors!");
296 // First, check for null and undef
297 if (isa<ConstantAggregateZero>(V))
298 return Constant::getNullValue(DestTy);
299 if (isa<UndefValue>(V))
300 return UndefValue::get(DestTy);
301
Reid Spencer81658a82007-02-27 06:23:51 +0000302 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000303 // This is a cast from a ConstantVector of one type to a
304 // ConstantVector of another type. Check to see if all elements of
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000305 // the input are simple.
306 bool AllSimpleConstants = true;
Reid Spencer81658a82007-02-27 06:23:51 +0000307 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
308 if (!isa<ConstantInt>(CV->getOperand(i)) &&
309 !isa<ConstantFP>(CV->getOperand(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000310 AllSimpleConstants = false;
311 break;
312 }
313 }
314
315 // If all of the elements are simple constants, we can fold this.
316 if (AllSimpleConstants)
Reid Spencer81658a82007-02-27 06:23:51 +0000317 return CastConstantVector(const_cast<ConstantVector*>(CV), DestPTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000318 }
Chris Lattner6b3f4752006-04-02 01:38:28 +0000319 }
320 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000321
Chris Lattner4d1da162006-12-11 18:30:27 +0000322 // Finally, implement bitcast folding now. The code below doesn't handle
323 // bitcast right.
324 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
325 return ConstantPointerNull::get(cast<PointerType>(DestTy));
326
327 // Handle integral constant input.
328 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner03c49532007-01-15 02:27:26 +0000329 if (DestTy->isInteger())
Reid Spencer81658a82007-02-27 06:23:51 +0000330 // Integral -> Integral. This is a no-op because the bit widths must
331 // be the same. Consequently, we just fold to V.
332 return const_cast<Constant*>(V);
Chris Lattner4d1da162006-12-11 18:30:27 +0000333
334 if (DestTy->isFloatingPoint()) {
335 if (DestTy == Type::FloatTy)
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000336 return ConstantFP::get(DestTy, APFloat(CI->getValue().bitsToFloat()));
Chris Lattner4d1da162006-12-11 18:30:27 +0000337 assert(DestTy == Type::DoubleTy && "Unknown FP type!");
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000338 return ConstantFP::get(DestTy, APFloat(CI->getValue().bitsToDouble()));
Chris Lattner4d1da162006-12-11 18:30:27 +0000339 }
Dan Gohman06c60b62007-07-16 14:29:03 +0000340 // Otherwise, can't fold this (vector?)
Chris Lattner4d1da162006-12-11 18:30:27 +0000341 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000342 }
Chris Lattner4d1da162006-12-11 18:30:27 +0000343
344 // Handle ConstantFP input.
345 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
346 // FP -> Integral.
Chris Lattnere62c89a2007-02-06 02:22:56 +0000347 if (DestTy == Type::Int32Ty) {
Reid Spencer4326cf52007-03-01 20:44:23 +0000348 APInt Val(32, 0);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000349 return ConstantInt::get(Val.floatToBits(FP->
350 getValueAPF().convertToFloat()));
Chris Lattnere62c89a2007-02-06 02:22:56 +0000351 } else {
352 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
Reid Spencer4326cf52007-03-01 20:44:23 +0000353 APInt Val(64, 0);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000354 return ConstantInt::get(Val.doubleToBits(FP->
355 getValueAPF().convertToDouble()));
Chris Lattnere62c89a2007-02-06 02:22:56 +0000356 }
Chris Lattner4d1da162006-12-11 18:30:27 +0000357 }
358 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000359 default:
360 assert(!"Invalid CE CastInst opcode");
361 break;
Chris Lattner6b3f4752006-04-02 01:38:28 +0000362 }
Chris Lattnerb2b7f902004-10-11 03:57:30 +0000363
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000364 assert(0 && "Failed to cast constant expression");
365 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +0000366}
367
Chris Lattner6ea4b522004-03-12 05:53:32 +0000368Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
369 const Constant *V1,
370 const Constant *V2) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000371 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
Reid Spencercddc9df2007-01-12 04:24:46 +0000372 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000373
374 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
375 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
376 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000377 if (V1 == V2) return const_cast<Constant*>(V1);
Chris Lattner6ea4b522004-03-12 05:53:32 +0000378 return 0;
379}
380
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000381Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
382 const Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000383 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
Reid Spencerd84d35b2007-02-15 02:26:10 +0000384 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000385 if (Val->isNullValue()) // ee(zero, x) -> zero
386 return Constant::getNullValue(
Reid Spencerd84d35b2007-02-15 02:26:10 +0000387 cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000388
Reid Spencerd84d35b2007-02-15 02:26:10 +0000389 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000390 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
391 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
Chris Lattnere52f29b2006-03-31 18:31:40 +0000392 } else if (isa<UndefValue>(Idx)) {
393 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
394 return const_cast<Constant*>(CVal->getOperand(0));
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000395 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000396 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000397 return 0;
398}
399
Robert Bocchinoca27f032006-01-17 20:07:22 +0000400Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
401 const Constant *Elt,
402 const Constant *Idx) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000403 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000404 if (!CIdx) return 0;
Reid Spencer81658a82007-02-27 06:23:51 +0000405 APInt idxVal = CIdx->getValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000406 if (isa<UndefValue>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000407 // Insertion of scalar constant into vector undef
Robert Bocchinoca27f032006-01-17 20:07:22 +0000408 // Optimize away insertion of undef
409 if (isa<UndefValue>(Elt))
410 return const_cast<Constant*>(Val);
411 // Otherwise break the aggregate undef into multiple undefs and do
412 // the insertion
413 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000414 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000415 std::vector<Constant*> Ops;
416 Ops.reserve(numOps);
417 for (unsigned i = 0; i < numOps; ++i) {
418 const Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000419 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
Robert Bocchinoca27f032006-01-17 20:07:22 +0000420 Ops.push_back(const_cast<Constant*>(Op));
421 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000422 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000423 }
Reid Spencer3054b142006-11-02 08:18:15 +0000424 if (isa<ConstantAggregateZero>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000425 // Insertion of scalar constant into vector aggregate zero
Robert Bocchinoca27f032006-01-17 20:07:22 +0000426 // Optimize away insertion of zero
427 if (Elt->isNullValue())
428 return const_cast<Constant*>(Val);
429 // Otherwise break the aggregate zero into multiple zeros and do
430 // the insertion
431 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000432 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000433 std::vector<Constant*> Ops;
434 Ops.reserve(numOps);
435 for (unsigned i = 0; i < numOps; ++i) {
436 const Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000437 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
Robert Bocchinoca27f032006-01-17 20:07:22 +0000438 Ops.push_back(const_cast<Constant*>(Op));
439 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000440 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000441 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000442 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000443 // Insertion of scalar constant into vector constant
Robert Bocchinoca27f032006-01-17 20:07:22 +0000444 std::vector<Constant*> Ops;
445 Ops.reserve(CVal->getNumOperands());
446 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
447 const Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000448 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
Robert Bocchinoca27f032006-01-17 20:07:22 +0000449 Ops.push_back(const_cast<Constant*>(Op));
450 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000451 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000452 }
453 return 0;
454}
455
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000456Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
457 const Constant *V2,
458 const Constant *Mask) {
459 // TODO:
460 return 0;
461}
462
Dan Gohman06c60b62007-07-16 14:29:03 +0000463/// EvalVectorOp - Given two vector constants and a function pointer, apply the
Reid Spencerd84d35b2007-02-15 02:26:10 +0000464/// function pointer to each element pair, producing a new ConstantVector
Reid Spencer266e42b2006-12-23 06:05:41 +0000465/// constant.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000466static Constant *EvalVectorOp(const ConstantVector *V1,
467 const ConstantVector *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +0000468 Constant *(*FP)(Constant*, Constant*)) {
469 std::vector<Constant*> Res;
470 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
471 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
472 const_cast<Constant*>(V2->getOperand(i))));
Reid Spencerd84d35b2007-02-15 02:26:10 +0000473 return ConstantVector::get(Res);
Reid Spencer266e42b2006-12-23 06:05:41 +0000474}
475
476Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
477 const Constant *C1,
478 const Constant *C2) {
479 // Handle UndefValue up front
480 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
481 switch (Opcode) {
482 case Instruction::Add:
483 case Instruction::Sub:
484 case Instruction::Xor:
485 return UndefValue::get(C1->getType());
486 case Instruction::Mul:
487 case Instruction::And:
488 return Constant::getNullValue(C1->getType());
489 case Instruction::UDiv:
490 case Instruction::SDiv:
491 case Instruction::FDiv:
492 case Instruction::URem:
493 case Instruction::SRem:
494 case Instruction::FRem:
495 if (!isa<UndefValue>(C2)) // undef / X -> 0
496 return Constant::getNullValue(C1->getType());
497 return const_cast<Constant*>(C2); // X / undef -> undef
498 case Instruction::Or: // X | undef -> -1
Reid Spencerd84d35b2007-02-15 02:26:10 +0000499 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
500 return ConstantVector::getAllOnesValue(PTy);
Reid Spencer266e42b2006-12-23 06:05:41 +0000501 return ConstantInt::getAllOnesValue(C1->getType());
502 case Instruction::LShr:
503 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
504 return const_cast<Constant*>(C1); // undef lshr undef -> undef
505 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
506 // undef lshr X -> 0
507 case Instruction::AShr:
508 if (!isa<UndefValue>(C2))
509 return const_cast<Constant*>(C1); // undef ashr X --> undef
510 else if (isa<UndefValue>(C1))
511 return const_cast<Constant*>(C1); // undef ashr undef -> undef
512 else
513 return const_cast<Constant*>(C1); // X ashr undef --> X
514 case Instruction::Shl:
515 // undef << X -> 0 or X << undef -> 0
516 return Constant::getNullValue(C1->getType());
517 }
518 }
519
520 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
521 if (isa<ConstantExpr>(C2)) {
522 // There are many possible foldings we could do here. We should probably
523 // at least fold add of a pointer with an integer into the appropriate
524 // getelementptr. This will improve alias analysis a bit.
525 } else {
526 // Just implement a couple of simple identities.
527 switch (Opcode) {
528 case Instruction::Add:
529 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
530 break;
531 case Instruction::Sub:
532 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
533 break;
534 case Instruction::Mul:
535 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
536 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000537 if (CI->equalsInt(1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000538 return const_cast<Constant*>(C1); // X * 1 == X
539 break;
540 case Instruction::UDiv:
541 case Instruction::SDiv:
542 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000543 if (CI->equalsInt(1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000544 return const_cast<Constant*>(C1); // X / 1 == X
545 break;
546 case Instruction::URem:
547 case Instruction::SRem:
548 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000549 if (CI->equalsInt(1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000550 return Constant::getNullValue(CI->getType()); // X % 1 == 0
551 break;
552 case Instruction::And:
Chris Lattner6d94bb72007-03-25 05:47:04 +0000553 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2)) {
554 if (CI->isZero()) return const_cast<Constant*>(C2); // X & 0 == 0
Chris Lattner26f13eb2007-01-04 01:56:39 +0000555 if (CI->isAllOnesValue())
556 return const_cast<Constant*>(C1); // X & -1 == X
Chris Lattner6d94bb72007-03-25 05:47:04 +0000557
558 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
559 if (CE1->getOpcode() == Instruction::ZExt) {
560 APInt PossiblySetBits
561 = cast<IntegerType>(CE1->getOperand(0)->getType())->getMask();
562 PossiblySetBits.zext(C1->getType()->getPrimitiveSizeInBits());
563 if ((PossiblySetBits & CI->getValue()) == PossiblySetBits)
564 return const_cast<Constant*>(C1);
565 }
566 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000567 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
568 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
569
570 // Functions are at least 4-byte aligned. If and'ing the address of a
571 // function with a constant < 4, fold it to zero.
572 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000573 if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
574 isa<Function>(CPR))
Reid Spencer266e42b2006-12-23 06:05:41 +0000575 return Constant::getNullValue(CI->getType());
576 }
577 break;
578 case Instruction::Or:
579 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
Chris Lattner26f13eb2007-01-04 01:56:39 +0000580 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
581 if (CI->isAllOnesValue())
582 return const_cast<Constant*>(C2); // X | -1 == -1
Reid Spencer266e42b2006-12-23 06:05:41 +0000583 break;
584 case Instruction::Xor:
585 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
586 break;
Chris Lattner6d94bb72007-03-25 05:47:04 +0000587 case Instruction::AShr:
Reid Spencere20090b2007-03-26 20:09:02 +0000588 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
Chris Lattner6d94bb72007-03-25 05:47:04 +0000589 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
590 return ConstantExpr::getLShr(const_cast<Constant*>(C1),
591 const_cast<Constant*>(C2));
592 break;
Reid Spencer266e42b2006-12-23 06:05:41 +0000593 }
594 }
595 } else if (isa<ConstantExpr>(C2)) {
596 // If C2 is a constant expr and C1 isn't, flop them around and fold the
597 // other way if possible.
598 switch (Opcode) {
599 case Instruction::Add:
600 case Instruction::Mul:
601 case Instruction::And:
602 case Instruction::Or:
603 case Instruction::Xor:
604 // No change of opcode required.
605 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
606
607 case Instruction::Shl:
608 case Instruction::LShr:
609 case Instruction::AShr:
610 case Instruction::Sub:
611 case Instruction::SDiv:
612 case Instruction::UDiv:
613 case Instruction::FDiv:
614 case Instruction::URem:
615 case Instruction::SRem:
616 case Instruction::FRem:
617 default: // These instructions cannot be flopped around.
618 return 0;
619 }
620 }
621
622 // At this point we know neither constant is an UndefValue nor a ConstantExpr
Chris Lattner26f13eb2007-01-04 01:56:39 +0000623 // so look at directly computing the value.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000624 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
625 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000626 using namespace APIntOps;
627 APInt C1V = CI1->getValue();
628 APInt C2V = CI2->getValue();
Chris Lattner344da522007-01-12 18:42:52 +0000629 switch (Opcode) {
630 default:
631 break;
632 case Instruction::Add:
Reid Spencera1276332007-03-01 19:31:12 +0000633 return ConstantInt::get(C1V + C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000634 case Instruction::Sub:
Reid Spencera1276332007-03-01 19:31:12 +0000635 return ConstantInt::get(C1V - C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000636 case Instruction::Mul:
Reid Spencera1276332007-03-01 19:31:12 +0000637 return ConstantInt::get(C1V * C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000638 case Instruction::UDiv:
Reid Spencer81658a82007-02-27 06:23:51 +0000639 if (CI2->isNullValue())
640 return 0; // X / 0 -> can't fold
Reid Spencera1276332007-03-01 19:31:12 +0000641 return ConstantInt::get(C1V.udiv(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000642 case Instruction::SDiv:
Reid Spencer81658a82007-02-27 06:23:51 +0000643 if (CI2->isNullValue())
644 return 0; // X / 0 -> can't fold
Reid Spencer81658a82007-02-27 06:23:51 +0000645 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
646 return 0; // MIN_INT / -1 -> overflow
Reid Spencera1276332007-03-01 19:31:12 +0000647 return ConstantInt::get(C1V.sdiv(C2V));
Reid Spencer81658a82007-02-27 06:23:51 +0000648 case Instruction::URem:
649 if (C2->isNullValue())
650 return 0; // X / 0 -> can't fold
Reid Spencera1276332007-03-01 19:31:12 +0000651 return ConstantInt::get(C1V.urem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000652 case Instruction::SRem:
Reid Spencer81658a82007-02-27 06:23:51 +0000653 if (CI2->isNullValue())
654 return 0; // X % 0 -> can't fold
655 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
656 return 0; // MIN_INT % -1 -> overflow
Reid Spencera1276332007-03-01 19:31:12 +0000657 return ConstantInt::get(C1V.srem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000658 case Instruction::And:
Reid Spencera1276332007-03-01 19:31:12 +0000659 return ConstantInt::get(C1V & C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000660 case Instruction::Or:
Reid Spencera1276332007-03-01 19:31:12 +0000661 return ConstantInt::get(C1V | C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000662 case Instruction::Xor:
Reid Spencera1276332007-03-01 19:31:12 +0000663 return ConstantInt::get(C1V ^ C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000664 case Instruction::Shl:
Reid Spencer81658a82007-02-27 06:23:51 +0000665 if (uint32_t shiftAmt = C2V.getZExtValue())
Reid Spencerac419b52007-02-27 19:29:54 +0000666 if (shiftAmt < C1V.getBitWidth())
Reid Spencera1276332007-03-01 19:31:12 +0000667 return ConstantInt::get(C1V.shl(shiftAmt));
Reid Spencer81658a82007-02-27 06:23:51 +0000668 else
669 return UndefValue::get(C1->getType()); // too big shift is undef
670 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
Chris Lattner344da522007-01-12 18:42:52 +0000671 case Instruction::LShr:
Reid Spencer81658a82007-02-27 06:23:51 +0000672 if (uint32_t shiftAmt = C2V.getZExtValue())
Reid Spencerac419b52007-02-27 19:29:54 +0000673 if (shiftAmt < C1V.getBitWidth())
Reid Spencera1276332007-03-01 19:31:12 +0000674 return ConstantInt::get(C1V.lshr(shiftAmt));
Reid Spencer81658a82007-02-27 06:23:51 +0000675 else
676 return UndefValue::get(C1->getType()); // too big shift is undef
677 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
Chris Lattner344da522007-01-12 18:42:52 +0000678 case Instruction::AShr:
Reid Spencer81658a82007-02-27 06:23:51 +0000679 if (uint32_t shiftAmt = C2V.getZExtValue())
Reid Spencerac419b52007-02-27 19:29:54 +0000680 if (shiftAmt < C1V.getBitWidth())
Reid Spencera1276332007-03-01 19:31:12 +0000681 return ConstantInt::get(C1V.ashr(shiftAmt));
Reid Spencer81658a82007-02-27 06:23:51 +0000682 else
683 return UndefValue::get(C1->getType()); // too big shift is undef
684 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
Reid Spencer266e42b2006-12-23 06:05:41 +0000685 }
686 }
687 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
688 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000689 APFloat C1V = CFP1->getValueAPF();
690 APFloat C2V = CFP2->getValueAPF();
691 APFloat C3V = C1V; // copy for modification
692 bool isDouble = CFP1->getType()==Type::DoubleTy;
Reid Spencer266e42b2006-12-23 06:05:41 +0000693 switch (Opcode) {
694 default:
695 break;
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000696 case Instruction::Add:
697 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
698 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000699 case Instruction::Sub:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000700 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
701 return ConstantFP::get(CFP1->getType(), C3V);
702 case Instruction::Mul:
703 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
704 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000705 case Instruction::FDiv:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000706 // FIXME better to look at the return code
707 if (C2V.isZero())
708 if (C1V.isZero())
Reid Spencerd96dc902007-03-23 05:33:23 +0000709 // IEEE 754, Section 7.1, #4
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000710 return ConstantFP::get(CFP1->getType(), isDouble ?
711 APFloat(std::numeric_limits<double>::quiet_NaN()) :
712 APFloat(std::numeric_limits<float>::quiet_NaN()));
713 else if (C2V.isNegZero() || C1V.isNegative())
Reid Spencerd96dc902007-03-23 05:33:23 +0000714 // IEEE 754, Section 7.2, negative infinity case
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000715 return ConstantFP::get(CFP1->getType(), isDouble ?
716 APFloat(-std::numeric_limits<double>::infinity()) :
717 APFloat(-std::numeric_limits<float>::infinity()));
Reid Spencerd96dc902007-03-23 05:33:23 +0000718 else
719 // IEEE 754, Section 7.2, positive infinity case
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000720 return ConstantFP::get(CFP1->getType(), isDouble ?
721 APFloat(std::numeric_limits<double>::infinity()) :
722 APFloat(std::numeric_limits<float>::infinity()));
723 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
724 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000725 case Instruction::FRem:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000726 if (C2V.isZero())
Reid Spencerd96dc902007-03-23 05:33:23 +0000727 // IEEE 754, Section 7.1, #5
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000728 return ConstantFP::get(CFP1->getType(), isDouble ?
729 APFloat(std::numeric_limits<double>::quiet_NaN()) :
730 APFloat(std::numeric_limits<float>::quiet_NaN()));
731 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
732 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000733 }
734 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000735 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
736 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000737 switch (Opcode) {
738 default:
739 break;
740 case Instruction::Add:
741 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
742 case Instruction::Sub:
743 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
744 case Instruction::Mul:
745 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
746 case Instruction::UDiv:
747 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
748 case Instruction::SDiv:
749 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
750 case Instruction::FDiv:
751 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
752 case Instruction::URem:
753 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
754 case Instruction::SRem:
755 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
756 case Instruction::FRem:
757 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
758 case Instruction::And:
759 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
760 case Instruction::Or:
761 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
762 case Instruction::Xor:
763 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
764 }
765 }
766 }
767
768 // We don't know how to fold this
769 return 0;
770}
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000771
Chris Lattner60c47262005-01-28 19:09:51 +0000772/// isZeroSizedType - This type is zero sized if its an array or structure of
773/// zero sized types. The only leaf zero sized type is an empty structure.
774static bool isMaybeZeroSizedType(const Type *Ty) {
775 if (isa<OpaqueType>(Ty)) return true; // Can't say.
776 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
777
778 // If all of elements have zero size, this does too.
779 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +0000780 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +0000781 return true;
782
783 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
784 return isMaybeZeroSizedType(ATy->getElementType());
785 }
786 return false;
787}
Chris Lattner6ea4b522004-03-12 05:53:32 +0000788
Chris Lattner061da2f2004-01-13 05:51:55 +0000789/// IdxCompare - Compare the two constants as though they were getelementptr
790/// indices. This allows coersion of the types to be the same thing.
791///
792/// If the two constants are the "same" (after coersion), return 0. If the
793/// first is less than the second, return -1, if the second is less than the
794/// first, return 1. If the constants are not integral, return -2.
795///
Chris Lattner60c47262005-01-28 19:09:51 +0000796static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000797 if (C1 == C2) return 0;
798
Reid Spencerc90cf772006-12-31 21:43:30 +0000799 // Ok, we found a different index. If they are not ConstantInt, we can't do
800 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +0000801 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
802 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +0000803
Chris Lattner69193f92004-04-05 01:30:19 +0000804 // Ok, we have two differing integer indices. Sign extend them to be the same
805 // type. Long is always big enough, so we use it.
Reid Spencer8d9336d2006-12-31 05:26:44 +0000806 if (C1->getType() != Type::Int64Ty)
807 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000808
Reid Spencer8d9336d2006-12-31 05:26:44 +0000809 if (C2->getType() != Type::Int64Ty)
Reid Spencerc90cf772006-12-31 21:43:30 +0000810 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000811
812 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +0000813
Chris Lattner60c47262005-01-28 19:09:51 +0000814 // If the type being indexed over is really just a zero sized type, there is
815 // no pointer difference being made here.
816 if (isMaybeZeroSizedType(ElTy))
817 return -2; // dunno.
818
Chris Lattner061da2f2004-01-13 05:51:55 +0000819 // If they are really different, now that they are the same type, then we
820 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +0000821 if (cast<ConstantInt>(C1)->getSExtValue() <
822 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +0000823 return -1;
824 else
825 return 1;
826}
827
Chris Lattner858f4e92007-01-04 02:13:20 +0000828/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencer266e42b2006-12-23 06:05:41 +0000829/// decide about the two constants provided. This doesn't need to handle simple
830/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
831/// If we can determine that the two constants have a particular relation to
832/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +0000833/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
834/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000835///
836/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +0000837/// operand is always the most "complex" of the two. We consider ConstantFP
838/// to be the simplest, and ConstantExprs to be the most complex.
839static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
840 const Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000841 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +0000842 "Cannot compare values of different types!");
843 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +0000844 if (V1 == V2) return FCmpInst::FCMP_OEQ;
845
Reid Spencer9d36acf2006-12-24 18:52:08 +0000846 if (!isa<ConstantExpr>(V1)) {
847 if (!isa<ConstantExpr>(V2)) {
848 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng75b871f2007-01-11 12:24:14 +0000849 ConstantInt *R = 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000850 Constant *C1 = const_cast<Constant*>(V1);
851 Constant *C2 = const_cast<Constant*>(V2);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000852 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000853 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000854 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000855 return FCmpInst::FCMP_OEQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000856 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000857 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000858 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000859 return FCmpInst::FCMP_OLT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000860 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000861 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000862 if (R && !R->isZero())
Reid Spencer9d36acf2006-12-24 18:52:08 +0000863 return FCmpInst::FCMP_OGT;
864
865 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +0000866 return FCmpInst::BAD_FCMP_PREDICATE;
867 }
868
Reid Spencer9d36acf2006-12-24 18:52:08 +0000869 // If the first operand is simple and second is ConstantExpr, swap operands.
870 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
871 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
872 return FCmpInst::getSwappedPredicate(SwappedRelation);
873 } else {
874 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
875 // constantexpr or a simple constant.
876 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
877 switch (CE1->getOpcode()) {
878 case Instruction::FPTrunc:
879 case Instruction::FPExt:
880 case Instruction::UIToFP:
881 case Instruction::SIToFP:
882 // We might be able to do something with these but we don't right now.
883 break;
884 default:
885 break;
886 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000887 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000888 // There are MANY other foldings that we could perform here. They will
889 // probably be added on demand, as they seem needed.
890 return FCmpInst::BAD_FCMP_PREDICATE;
891}
892
893/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +0000894/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +0000895/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +0000896/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +0000897/// particular relation to each other, we should return the corresponding ICmp
898/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +0000899///
900/// To simplify this code we canonicalize the relation so that the first
901/// operand is always the most "complex" of the two. We consider simple
902/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +0000903/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +0000904///
Reid Spencer9d36acf2006-12-24 18:52:08 +0000905static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
906 const Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +0000907 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000908 assert(V1->getType() == V2->getType() &&
909 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +0000910 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +0000911
Reid Spenceraccd7c72004-07-17 23:47:01 +0000912 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000913 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
914 // We distilled this down to a simple case, use the standard constant
915 // folder.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000916 ConstantInt *R = 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000917 Constant *C1 = const_cast<Constant*>(V1);
918 Constant *C2 = const_cast<Constant*>(V2);
Reid Spencer266e42b2006-12-23 06:05:41 +0000919 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000920 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000921 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000922 return pred;
923 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000924 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000925 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000926 return pred;
927 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000928 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000929 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000930 return pred;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000931
932 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +0000933 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000934 }
935
Chris Lattner061da2f2004-01-13 05:51:55 +0000936 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +0000937 ICmpInst::Predicate SwappedRelation =
938 evaluateICmpRelation(V2, V1, isSigned);
939 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
940 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +0000941
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000942 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +0000943 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +0000944 ICmpInst::Predicate SwappedRelation =
945 evaluateICmpRelation(V2, V1, isSigned);
946 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
947 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000948 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000949 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +0000950 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000951
Reid Spenceraccd7c72004-07-17 23:47:01 +0000952 // Now we know that the RHS is a GlobalValue or simple constant,
Chris Lattner061da2f2004-01-13 05:51:55 +0000953 // which (since the types must match) means that it's a ConstantPointerNull.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000954 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner52fe8692007-09-10 23:42:42 +0000955 // Don't try to decide equality of aliases.
956 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
957 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
958 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000959 } else {
960 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Chris Lattner52fe8692007-09-10 23:42:42 +0000961 // GlobalVals can never be null. Don't try to evaluate aliases.
962 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000963 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000964 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000965 } else {
966 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
967 // constantexpr, a CPR, or a simple constant.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000968 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
969 const Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +0000970
971 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000972 case Instruction::Trunc:
973 case Instruction::FPTrunc:
974 case Instruction::FPExt:
975 case Instruction::FPToUI:
976 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +0000977 break; // We can't evaluate floating point casts or truncations.
978
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000979 case Instruction::UIToFP:
980 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000981 case Instruction::IntToPtr:
982 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +0000983 case Instruction::ZExt:
984 case Instruction::SExt:
985 case Instruction::PtrToInt:
Chris Lattner061da2f2004-01-13 05:51:55 +0000986 // If the cast is not actually changing bits, and the second operand is a
987 // null pointer, do the comparison with the pre-casted value.
988 if (V2->isNullValue() &&
Chris Lattner03c49532007-01-15 02:27:26 +0000989 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
Reid Spencerccf78ac2006-12-23 10:21:26 +0000990 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
Reid Spencer266e42b2006-12-23 06:05:41 +0000991 (CE1->getOpcode() == Instruction::SExt ? true :
992 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
993 return evaluateICmpRelation(
Reid Spencerccf78ac2006-12-23 10:21:26 +0000994 CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
Reid Spencer266e42b2006-12-23 06:05:41 +0000995 }
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000996
997 // If the dest type is a pointer type, and the RHS is a constantexpr cast
998 // from the same type as the src of the LHS, evaluate the inputs. This is
Reid Spencer266e42b2006-12-23 06:05:41 +0000999 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001000 // which happens a lot in compilers with tagged integers.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001001 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
Reid Spencer266e42b2006-12-23 06:05:41 +00001002 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001003 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
Chris Lattner03c49532007-01-15 02:27:26 +00001004 CE1->getOperand(0)->getType()->isInteger()) {
Reid Spencerccf78ac2006-12-23 10:21:26 +00001005 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
Reid Spencer266e42b2006-12-23 06:05:41 +00001006 (CE1->getOpcode() == Instruction::SExt ? true :
1007 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
1008 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
Reid Spencerccf78ac2006-12-23 10:21:26 +00001009 sgnd);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001010 }
Chris Lattner192e3262004-04-11 01:29:30 +00001011 break;
Chris Lattner061da2f2004-01-13 05:51:55 +00001012
1013 case Instruction::GetElementPtr:
1014 // Ok, since this is a getelementptr, we know that the constant has a
1015 // pointer type. Check the various cases.
1016 if (isa<ConstantPointerNull>(V2)) {
1017 // If we are comparing a GEP to a null pointer, check to see if the base
1018 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001019 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001020 if (GV->hasExternalWeakLinkage())
1021 // Weak linkage GVals could be zero or not. We're comparing that
1022 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001023 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +00001024 else
1025 // If its not weak linkage, the GVal must have a non-zero address
1026 // so the result is greater-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001027 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001028 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1029 // If we are indexing from a null pointer, check to see if we have any
1030 // non-zero indices.
1031 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1032 if (!CE1->getOperand(i)->isNullValue())
1033 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001034 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001035 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00001036 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001037 }
1038 // Otherwise, we can't really say if the first operand is null or not.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001039 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001040 if (isa<ConstantPointerNull>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001041 if (CPR2->hasExternalWeakLinkage())
1042 // Weak linkage GVals could be zero or not. We're comparing it to
1043 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001044 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +00001045 else
1046 // If its not weak linkage, the GVal must have a non-zero address
1047 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001048 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spenceraccd7c72004-07-17 23:47:01 +00001049 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001050 if (CPR1 == CPR2) {
1051 // If this is a getelementptr of the same global, then it must be
1052 // different. Because the types must match, the getelementptr could
1053 // only have at most one index, and because we fold getelementptr's
1054 // with a single zero index, it must be nonzero.
1055 assert(CE1->getNumOperands() == 2 &&
1056 !CE1->getOperand(1)->isNullValue() &&
1057 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001058 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001059 } else {
1060 // If they are different globals, we don't know what the value is,
1061 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001062 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001063 }
1064 }
1065 } else {
1066 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1067 const Constant *CE2Op0 = CE2->getOperand(0);
1068
1069 // There are MANY other foldings that we could perform here. They will
1070 // probably be added on demand, as they seem needed.
1071 switch (CE2->getOpcode()) {
1072 default: break;
1073 case Instruction::GetElementPtr:
1074 // By far the most common case to handle is when the base pointers are
1075 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001076 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001077 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001078 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001079 // Ok, we know that both getelementptr instructions are based on the
1080 // same global. From this, we can precisely determine the relative
1081 // ordering of the resultant pointers.
1082 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001083
Chris Lattner061da2f2004-01-13 05:51:55 +00001084 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +00001085 gep_type_iterator GTI = gep_type_begin(CE1);
1086 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1087 ++i, ++GTI)
1088 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1089 GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001090 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1091 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1092 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001093 }
1094
1095 // Ok, we ran out of things they have in common. If any leftovers
1096 // are non-zero then we have a difference, otherwise we are equal.
1097 for (; i < CE1->getNumOperands(); ++i)
1098 if (!CE1->getOperand(i)->isNullValue())
Zhou Sheng75b871f2007-01-11 12:24:14 +00001099 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001100 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +00001101 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001102 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001103
Chris Lattner061da2f2004-01-13 05:51:55 +00001104 for (; i < CE2->getNumOperands(); ++i)
1105 if (!CE2->getOperand(i)->isNullValue())
Zhou Sheng75b871f2007-01-11 12:24:14 +00001106 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001107 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001108 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001109 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1110 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001111 }
1112 }
1113 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001114 default:
1115 break;
1116 }
1117 }
1118
Reid Spencer266e42b2006-12-23 06:05:41 +00001119 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001120}
1121
Reid Spencer9d36acf2006-12-24 18:52:08 +00001122Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1123 const Constant *C1,
1124 const Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001125
1126 // Handle some degenerate cases first
1127 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
Reid Spencer542964f2007-01-11 18:21:29 +00001128 return UndefValue::get(Type::Int1Ty);
Reid Spencer266e42b2006-12-23 06:05:41 +00001129
1130 // icmp eq/ne(null,GV) -> false/true
1131 if (C1->isNullValue()) {
1132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1133 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
Reid Spencer9d36acf2006-12-24 18:52:08 +00001134 if (pred == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001135 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001136 else if (pred == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001137 return ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00001138 // icmp eq/ne(GV,null) -> false/true
1139 } else if (C2->isNullValue()) {
1140 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1141 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
Reid Spencer9d36acf2006-12-24 18:52:08 +00001142 if (pred == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001143 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001144 else if (pred == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001145 return ConstantInt::getTrue();
Chris Lattner1dd054c2004-01-12 22:07:24 +00001146 }
1147
Chris Lattner344da522007-01-12 18:42:52 +00001148 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001149 APInt V1 = cast<ConstantInt>(C1)->getValue();
1150 APInt V2 = cast<ConstantInt>(C2)->getValue();
1151 switch (pred) {
1152 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1153 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1154 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1155 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1156 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1157 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1158 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1159 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1160 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1161 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1162 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
Chris Lattner061da2f2004-01-13 05:51:55 +00001163 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001164 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001165 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1166 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1167 APFloat::cmpResult R = C1V.compare(C2V);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001168 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001169 default: assert(0 && "Invalid FCmp Predicate"); return 0;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001170 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1171 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00001172 case FCmpInst::FCMP_UNO:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001173 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
Reid Spencer74bd0362007-01-11 00:25:45 +00001174 case FCmpInst::FCMP_ORD:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001175 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
Reid Spencer266e42b2006-12-23 06:05:41 +00001176 case FCmpInst::FCMP_UEQ:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001177 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1178 R==APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001179 case FCmpInst::FCMP_OEQ:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001180 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
Reid Spencer74bd0362007-01-11 00:25:45 +00001181 case FCmpInst::FCMP_UNE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001182 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001183 case FCmpInst::FCMP_ONE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001184 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1185 R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001186 case FCmpInst::FCMP_ULT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001187 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1188 R==APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001189 case FCmpInst::FCMP_OLT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001190 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
Reid Spencer266e42b2006-12-23 06:05:41 +00001191 case FCmpInst::FCMP_UGT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001192 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1193 R==APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001194 case FCmpInst::FCMP_OGT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001195 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001196 case FCmpInst::FCMP_ULE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001197 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001198 case FCmpInst::FCMP_OLE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001199 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1200 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001201 case FCmpInst::FCMP_UGE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001202 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001203 case FCmpInst::FCMP_OGE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001204 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1205 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001206 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00001207 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1208 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001209 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001210 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1211 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1212 const_cast<Constant*>(CP1->getOperand(i)),
1213 const_cast<Constant*>(CP2->getOperand(i)));
Zhou Sheng75b871f2007-01-11 12:24:14 +00001214 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
Reid Spencer266e42b2006-12-23 06:05:41 +00001215 return CB;
1216 }
1217 // Otherwise, could not decide from any element pairs.
1218 return 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001219 } else if (pred == ICmpInst::ICMP_EQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001220 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1221 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1222 const_cast<Constant*>(CP1->getOperand(i)),
1223 const_cast<Constant*>(CP2->getOperand(i)));
Zhou Sheng75b871f2007-01-11 12:24:14 +00001224 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
Reid Spencer266e42b2006-12-23 06:05:41 +00001225 return CB;
1226 }
1227 // Otherwise, could not decide from any element pairs.
1228 return 0;
1229 }
1230 }
1231 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001232
Reid Spencer9d36acf2006-12-24 18:52:08 +00001233 if (C1->getType()->isFloatingPoint()) {
1234 switch (evaluateFCmpRelation(C1, C2)) {
1235 default: assert(0 && "Unknown relation!");
1236 case FCmpInst::FCMP_UNO:
1237 case FCmpInst::FCMP_ORD:
1238 case FCmpInst::FCMP_UEQ:
1239 case FCmpInst::FCMP_UNE:
1240 case FCmpInst::FCMP_ULT:
1241 case FCmpInst::FCMP_UGT:
1242 case FCmpInst::FCMP_ULE:
1243 case FCmpInst::FCMP_UGE:
1244 case FCmpInst::FCMP_TRUE:
1245 case FCmpInst::FCMP_FALSE:
1246 case FCmpInst::BAD_FCMP_PREDICATE:
1247 break; // Couldn't determine anything about these constants.
1248 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001249 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001250 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1251 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1252 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1253 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001254 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001255 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1256 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1257 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1258 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001259 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001260 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1261 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1262 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1263 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1264 // We can only partially decide this relation.
1265 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001266 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001267 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001268 return ConstantInt::getTrue();
Chris Lattner061da2f2004-01-13 05:51:55 +00001269 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001270 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1271 // We can only partially decide this relation.
1272 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001273 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001274 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001275 return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001276 break;
1277 case ICmpInst::ICMP_NE: // We know that C1 != C2
1278 // We can only partially decide this relation.
1279 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001280 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001281 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001282 return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001283 break;
1284 }
1285 } else {
1286 // Evaluate the relation between the two constants, per the predicate.
1287 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1288 default: assert(0 && "Unknown relational!");
1289 case ICmpInst::BAD_ICMP_PREDICATE:
1290 break; // Couldn't determine anything about these constants.
1291 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1292 // If we know the constants are equal, we can decide the result of this
1293 // computation precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001294 return ConstantInt::get(Type::Int1Ty,
1295 pred == ICmpInst::ICMP_EQ ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001296 pred == ICmpInst::ICMP_ULE ||
1297 pred == ICmpInst::ICMP_SLE ||
1298 pred == ICmpInst::ICMP_UGE ||
1299 pred == ICmpInst::ICMP_SGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001300 case ICmpInst::ICMP_ULT:
1301 // If we know that C1 < C2, we can decide the result of this computation
1302 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001303 return ConstantInt::get(Type::Int1Ty,
1304 pred == ICmpInst::ICMP_ULT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001305 pred == ICmpInst::ICMP_NE ||
1306 pred == ICmpInst::ICMP_ULE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001307 case ICmpInst::ICMP_SLT:
1308 // If we know that C1 < C2, we can decide the result of this computation
1309 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001310 return ConstantInt::get(Type::Int1Ty,
1311 pred == ICmpInst::ICMP_SLT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001312 pred == ICmpInst::ICMP_NE ||
1313 pred == ICmpInst::ICMP_SLE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001314 case ICmpInst::ICMP_UGT:
1315 // If we know that C1 > C2, we can decide the result of this computation
1316 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001317 return ConstantInt::get(Type::Int1Ty,
1318 pred == ICmpInst::ICMP_UGT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001319 pred == ICmpInst::ICMP_NE ||
1320 pred == ICmpInst::ICMP_UGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001321 case ICmpInst::ICMP_SGT:
1322 // If we know that C1 > C2, we can decide the result of this computation
1323 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001324 return ConstantInt::get(Type::Int1Ty,
1325 pred == ICmpInst::ICMP_SGT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001326 pred == ICmpInst::ICMP_NE ||
1327 pred == ICmpInst::ICMP_SGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001328 case ICmpInst::ICMP_ULE:
1329 // If we know that C1 <= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001330 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1331 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001332 break;
1333 case ICmpInst::ICMP_SLE:
1334 // If we know that C1 <= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001335 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1336 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001337 break;
1338
1339 case ICmpInst::ICMP_UGE:
1340 // If we know that C1 >= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001341 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1342 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001343 break;
1344 case ICmpInst::ICMP_SGE:
1345 // If we know that C1 >= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001346 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1347 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001348 break;
1349
1350 case ICmpInst::ICMP_NE:
1351 // If we know that C1 != C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001352 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1353 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001354 break;
1355 }
1356
1357 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1358 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1359 // other way if possible.
1360 switch (pred) {
1361 case ICmpInst::ICMP_EQ:
1362 case ICmpInst::ICMP_NE:
1363 // No change of predicate required.
1364 return ConstantFoldCompareInstruction(pred, C2, C1);
1365
1366 case ICmpInst::ICMP_ULT:
1367 case ICmpInst::ICMP_SLT:
1368 case ICmpInst::ICMP_UGT:
1369 case ICmpInst::ICMP_SGT:
1370 case ICmpInst::ICMP_ULE:
1371 case ICmpInst::ICMP_SLE:
1372 case ICmpInst::ICMP_UGE:
1373 case ICmpInst::ICMP_SGE:
1374 // Change the predicate as necessary to swap the operands.
1375 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1376 return ConstantFoldCompareInstruction(pred, C2, C1);
1377
1378 default: // These predicates cannot be flopped around.
1379 break;
1380 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001381 }
1382 }
1383 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001384}
1385
1386Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
David Greenec656cbb2007-09-04 15:46:09 +00001387 Constant* const *Idxs,
Chris Lattner302116a2007-01-31 04:40:28 +00001388 unsigned NumIdx) {
1389 if (NumIdx == 0 ||
1390 (NumIdx == 1 && Idxs[0]->isNullValue()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001391 return const_cast<Constant*>(C);
1392
Chris Lattnerf6013752004-10-17 21:54:55 +00001393 if (isa<UndefValue>(C)) {
Chris Lattner302116a2007-01-31 04:40:28 +00001394 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
David Greenec656cbb2007-09-04 15:46:09 +00001395 (Value **)Idxs,
1396 (Value **)Idxs+NumIdx,
Chris Lattnerf6013752004-10-17 21:54:55 +00001397 true);
1398 assert(Ty != 0 && "Invalid indices for GEP!");
1399 return UndefValue::get(PointerType::get(Ty));
1400 }
1401
Chris Lattner302116a2007-01-31 04:40:28 +00001402 Constant *Idx0 = Idxs[0];
Chris Lattner04b60fe2004-02-16 20:46:13 +00001403 if (C->isNullValue()) {
1404 bool isNull = true;
Chris Lattner302116a2007-01-31 04:40:28 +00001405 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1406 if (!Idxs[i]->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00001407 isNull = false;
1408 break;
1409 }
1410 if (isNull) {
Chris Lattner302116a2007-01-31 04:40:28 +00001411 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(),
David Greenec656cbb2007-09-04 15:46:09 +00001412 (Value**)Idxs,
1413 (Value**)Idxs+NumIdx,
Chris Lattner04b60fe2004-02-16 20:46:13 +00001414 true);
1415 assert(Ty != 0 && "Invalid indices for GEP!");
1416 return ConstantPointerNull::get(PointerType::get(Ty));
1417 }
1418 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001419
1420 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1421 // Combine Indices - If the source pointer to this getelementptr instruction
1422 // is a getelementptr instruction, combine the indices of the two
1423 // getelementptr instructions into a single instruction.
1424 //
1425 if (CE->getOpcode() == Instruction::GetElementPtr) {
1426 const Type *LastTy = 0;
1427 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1428 I != E; ++I)
1429 LastTy = *I;
1430
Chris Lattner13128ab2004-10-11 22:52:25 +00001431 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
Chris Lattner302116a2007-01-31 04:40:28 +00001432 SmallVector<Value*, 16> NewIndices;
1433 NewIndices.reserve(NumIdx + CE->getNumOperands());
Chris Lattner1dd054c2004-01-12 22:07:24 +00001434 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001435 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00001436
1437 // Add the last index of the source with the first index of the new GEP.
1438 // Make sure to handle the case when they are actually different types.
1439 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001440 // Otherwise it must be an array.
1441 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00001442 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00001443 if (IdxTy != Idx0->getType()) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001444 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
Reid Spencer27720a92006-12-05 03:30:09 +00001445 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
Reid Spencer8d9336d2006-12-31 05:26:44 +00001446 Type::Int64Ty);
Reid Spencer1a063892006-12-04 02:46:44 +00001447 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1448 } else {
1449 Combined =
1450 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1451 }
Chris Lattner71068a02004-07-07 04:45:13 +00001452 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001453
Chris Lattner1dd054c2004-01-12 22:07:24 +00001454 NewIndices.push_back(Combined);
Chris Lattner302116a2007-01-31 04:40:28 +00001455 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1456 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1457 NewIndices.size());
Chris Lattner1dd054c2004-01-12 22:07:24 +00001458 }
1459 }
1460
1461 // Implement folding of:
1462 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1463 // long 0, long 0)
1464 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1465 //
Chris Lattneraadc7782007-08-13 17:09:08 +00001466 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001467 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00001468 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1469 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1470 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00001471 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001472 if (CAT->getElementType() == SAT->getElementType())
1473 return ConstantExpr::getGetElementPtr(
Chris Lattner302116a2007-01-31 04:40:28 +00001474 (Constant*)CE->getOperand(0), Idxs, NumIdx);
Chris Lattneraadc7782007-08-13 17:09:08 +00001475 }
1476
1477 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1478 // Into: inttoptr (i64 0 to i8*)
1479 // This happens with pointers to member functions in C++.
1480 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1481 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1482 cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1483 Constant *Base = CE->getOperand(0);
1484 Constant *Offset = Idxs[0];
1485
1486 // Convert the smaller integer to the larger type.
1487 if (Offset->getType()->getPrimitiveSizeInBits() <
1488 Base->getType()->getPrimitiveSizeInBits())
1489 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1490 else if (Base->getType()->getPrimitiveSizeInBits() <
1491 Offset->getType()->getPrimitiveSizeInBits())
1492 Base = ConstantExpr::getZExt(Base, Base->getType());
1493
1494 Base = ConstantExpr::getAdd(Base, Offset);
1495 return ConstantExpr::getIntToPtr(Base, CE->getType());
1496 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001497 }
1498 return 0;
1499}
1500