blob: 521f6b84a2558fc4e3f0e3bd787e7c2dd78ca8eb [file] [log] [blame]
Chris Lattner5a945e32004-01-12 21:13:12 +00001//===- ConstantFolding.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
11// (internal) ConstantFolding.h interface, which is used by the
12// 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 Lattner5a945e32004-01-12 21:13:12 +000021#include "ConstantFolding.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 Lattner3d27be12006-08-27 12:54:02 +000026#include "llvm/Support/Compiler.h"
Chris Lattner057083f2006-10-13 17:22:21 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000030#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000031using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000032
Chris Lattner1dd054c2004-01-12 22:07:24 +000033//===----------------------------------------------------------------------===//
34// ConstantFold*Instruction Implementations
35//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000036
Chris Lattner6b3f4752006-04-02 01:38:28 +000037/// CastConstantPacked - Convert the specified ConstantPacked node to the
38/// specified packed type. At this point, we know that the elements of the
39/// input packed constant are all simple integer or FP values.
40static Constant *CastConstantPacked(ConstantPacked *CP,
41 const PackedType *DstTy) {
42 unsigned SrcNumElts = CP->getType()->getNumElements();
43 unsigned DstNumElts = DstTy->getNumElements();
44 const Type *SrcEltTy = CP->getType()->getElementType();
45 const Type *DstEltTy = DstTy->getElementType();
46
47 // If both vectors have the same number of elements (thus, the elements
48 // are the same size), perform the conversion now.
49 if (SrcNumElts == DstNumElts) {
50 std::vector<Constant*> Result;
51
Reid Spencer6c38f0b2006-11-27 01:05:10 +000052 // If the src and dest elements are both integers, or both floats, we can
53 // just BitCast each element because the elements are the same size.
Chris Lattner03c49532007-01-15 02:27:26 +000054 if ((SrcEltTy->isInteger() && DstEltTy->isInteger()) ||
Reid Spencer6c38f0b2006-11-27 01:05:10 +000055 (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
Chris Lattner6b3f4752006-04-02 01:38:28 +000056 for (unsigned i = 0; i != SrcNumElts; ++i)
Reid Spencer6c38f0b2006-11-27 01:05:10 +000057 Result.push_back(
Reid Spencerbb65ebf2006-12-12 23:36:14 +000058 ConstantExpr::getBitCast(CP->getOperand(i), DstEltTy));
Chris Lattner6b3f4752006-04-02 01:38:28 +000059 return ConstantPacked::get(Result);
60 }
61
Reid Spencer6c38f0b2006-11-27 01:05:10 +000062 // If this is an int-to-fp cast ..
Chris Lattner03c49532007-01-15 02:27:26 +000063 if (SrcEltTy->isInteger()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +000064 // Ensure that it is int-to-fp cast
Chris Lattner6b3f4752006-04-02 01:38:28 +000065 assert(DstEltTy->isFloatingPoint());
66 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
67 for (unsigned i = 0; i != SrcNumElts; ++i) {
68 double V =
Reid Spencere0fc4df2006-10-20 07:07:24 +000069 BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner6b3f4752006-04-02 01:38:28 +000070 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
71 }
72 return ConstantPacked::get(Result);
73 }
74 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
75 for (unsigned i = 0; i != SrcNumElts; ++i) {
76 float V =
Reid Spencere0fc4df2006-10-20 07:07:24 +000077 BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner6b3f4752006-04-02 01:38:28 +000078 Result.push_back(ConstantFP::get(Type::FloatTy, V));
79 }
80 return ConstantPacked::get(Result);
81 }
82
83 // Otherwise, this is an fp-to-int cast.
Chris Lattner03c49532007-01-15 02:27:26 +000084 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isInteger());
Chris Lattner6b3f4752006-04-02 01:38:28 +000085
86 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
87 for (unsigned i = 0; i != SrcNumElts; ++i) {
88 uint64_t V =
89 DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
Reid Spencer8d9336d2006-12-31 05:26:44 +000090 Constant *C = ConstantInt::get(Type::Int64Ty, V);
Reid Spencera16f9302006-12-05 07:18:07 +000091 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
Chris Lattner6b3f4752006-04-02 01:38:28 +000092 }
93 return ConstantPacked::get(Result);
94 }
95
96 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
97 for (unsigned i = 0; i != SrcNumElts; ++i) {
Reid Spencere0fc4df2006-10-20 07:07:24 +000098 uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
Reid Spencer8d9336d2006-12-31 05:26:44 +000099 Constant *C = ConstantInt::get(Type::Int32Ty, V);
Reid Spencera16f9302006-12-05 07:18:07 +0000100 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
Chris Lattner6b3f4752006-04-02 01:38:28 +0000101 }
102 return ConstantPacked::get(Result);
103 }
104
105 // Otherwise, this is a cast that changes element count and size. Handle
106 // casts which shrink the elements here.
107
108 // FIXME: We need to know endianness to do this!
109
110 return 0;
111}
112
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000113/// This function determines which opcode to use to fold two constant cast
114/// expressions together. It uses CastInst::isEliminableCastPair to determine
115/// the opcode. Consequently its just a wrapper around that function.
116/// @Determine if it is valid to fold a cast of a cast
117static unsigned
118foldConstantCastPair(
119 unsigned opc, ///< opcode of the second cast constant expression
120 const ConstantExpr*Op, ///< the first cast constant expression
121 const Type *DstTy ///< desintation type of the first cast
122) {
123 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
124 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
125 assert(CastInst::isCast(opc) && "Invalid cast opcode");
126
127 // The the types and opcodes for the two Cast constant expressions
128 const Type *SrcTy = Op->getOperand(0)->getType();
129 const Type *MidTy = Op->getType();
130 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
131 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000132
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000133 // Let CastInst::isEliminableCastPair do the heavy lifting.
134 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Reid Spencer8d9336d2006-12-31 05:26:44 +0000135 Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000136}
137
138Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
Chris Lattner1dd054c2004-01-12 22:07:24 +0000139 const Type *DestTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000140 const Type *SrcTy = V->getType();
Chris Lattner1dd054c2004-01-12 22:07:24 +0000141
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000142 if (isa<UndefValue>(V))
143 return UndefValue::get(DestTy);
144
145 // If the cast operand is a constant expression, there's a few things we can
146 // do to try to simplify it.
147 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
148 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000149 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000150 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
151 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000152 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
153 // If all of the indexes in the GEP are null values, there is no pointer
154 // adjustment going on. We might as well cast the source pointer.
155 bool isAllNull = true;
156 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
157 if (!CE->getOperand(i)->isNullValue()) {
158 isAllNull = false;
159 break;
160 }
161 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000162 // This is casting one pointer type to another, always BitCast
Reid Spencer27720a92006-12-05 03:30:09 +0000163 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000164 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000165 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000166
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000167 // We actually have to do a cast now. Perform the cast according to the
168 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000169 switch (opc) {
170 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000171 case Instruction::FPExt:
Reid Spencer8dabca42006-12-19 07:41:40 +0000172 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
173 return ConstantFP::get(DestTy, FPC->getValue());
174 return 0; // Can't fold.
175 case Instruction::FPToUI:
176 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
Zhou Sheng75b871f2007-01-11 12:24:14 +0000177 return ConstantInt::get(DestTy,(uint64_t) FPC->getValue());
Reid Spencer8dabca42006-12-19 07:41:40 +0000178 return 0; // Can't fold.
179 case Instruction::FPToSI:
180 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
Zhou Sheng75b871f2007-01-11 12:24:14 +0000181 return ConstantInt::get(DestTy,(int64_t) FPC->getValue());
Reid Spencer8dabca42006-12-19 07:41:40 +0000182 return 0; // Can't fold.
183 case Instruction::IntToPtr: //always treated as unsigned
184 if (V->isNullValue()) // Is it an integral null value?
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000185 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000186 return 0; // Other pointer types cannot be casted
187 case Instruction::PtrToInt: // always treated as unsigned
188 if (V->isNullValue()) // is it a null pointer value?
Zhou Sheng75b871f2007-01-11 12:24:14 +0000189 return ConstantInt::get(DestTy, 0);
Reid Spencer8dabca42006-12-19 07:41:40 +0000190 return 0; // Other pointer types cannot be casted
191 case Instruction::UIToFP:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000192 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
Reid Spencer8dabca42006-12-19 07:41:40 +0000193 return ConstantFP::get(DestTy, double(CI->getZExtValue()));
194 return 0;
195 case Instruction::SIToFP:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000196 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
Reid Spencer8dabca42006-12-19 07:41:40 +0000197 return ConstantFP::get(DestTy, double(CI->getSExtValue()));
198 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000199 case Instruction::ZExt:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000200 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
Reid Spencer8dabca42006-12-19 07:41:40 +0000201 return ConstantInt::get(DestTy, CI->getZExtValue());
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000202 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000203 case Instruction::SExt:
Zhou Sheng75b871f2007-01-11 12:24:14 +0000204 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
Reid Spencer8dabca42006-12-19 07:41:40 +0000205 return ConstantInt::get(DestTy, CI->getSExtValue());
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000206 return 0;
Chris Lattner710ebaf2006-12-01 19:22:41 +0000207 case Instruction::Trunc:
Reid Spencer8dabca42006-12-19 07:41:40 +0000208 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) // Can't trunc a bool
Zhou Sheng75b871f2007-01-11 12:24:14 +0000209 return ConstantInt::get(DestTy, CI->getZExtValue());
Chris Lattner710ebaf2006-12-01 19:22:41 +0000210 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000211 case Instruction::BitCast:
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000212 if (SrcTy == DestTy)
213 return (Constant*)V; // no-op cast
Chris Lattner4d1da162006-12-11 18:30:27 +0000214
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000215 // Check to see if we are casting a pointer to an aggregate to a pointer to
216 // the first element. If so, return the appropriate GEP instruction.
217 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
218 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
219 std::vector<Value*> IdxList;
Reid Spencer8d9336d2006-12-31 05:26:44 +0000220 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000221 const Type *ElTy = PTy->getElementType();
222 while (ElTy != DPTy->getElementType()) {
223 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
224 if (STy->getNumElements() == 0) break;
225 ElTy = STy->getElementType(0);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000226 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000227 } else if (const SequentialType *STy =
228 dyn_cast<SequentialType>(ElTy)) {
229 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
230 ElTy = STy->getElementType();
231 IdxList.push_back(IdxList[0]);
232 } else {
Chris Lattner6b3f4752006-04-02 01:38:28 +0000233 break;
234 }
235 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000236
237 if (ElTy == DPTy->getElementType())
238 return ConstantExpr::getGetElementPtr(
239 const_cast<Constant*>(V),IdxList);
240 }
241
242 // Handle casts from one packed constant to another. We know that the src
243 // and dest type have the same size (otherwise its an illegal cast).
244 if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
245 if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
246 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
247 "Not cast between same sized vectors!");
248 // First, check for null and undef
249 if (isa<ConstantAggregateZero>(V))
250 return Constant::getNullValue(DestTy);
251 if (isa<UndefValue>(V))
252 return UndefValue::get(DestTy);
253
254 if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
255 // This is a cast from a ConstantPacked of one type to a
256 // ConstantPacked of another type. Check to see if all elements of
257 // the input are simple.
258 bool AllSimpleConstants = true;
259 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
260 if (!isa<ConstantInt>(CP->getOperand(i)) &&
261 !isa<ConstantFP>(CP->getOperand(i))) {
262 AllSimpleConstants = false;
263 break;
264 }
265 }
266
267 // If all of the elements are simple constants, we can fold this.
268 if (AllSimpleConstants)
269 return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
270 }
Chris Lattner6b3f4752006-04-02 01:38:28 +0000271 }
272 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000273
Chris Lattner4d1da162006-12-11 18:30:27 +0000274 // Finally, implement bitcast folding now. The code below doesn't handle
275 // bitcast right.
276 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
277 return ConstantPointerNull::get(cast<PointerType>(DestTy));
278
279 // Handle integral constant input.
280 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
281 // Integral -> Integral, must be changing sign.
Chris Lattner03c49532007-01-15 02:27:26 +0000282 if (DestTy->isInteger())
Chris Lattner4d1da162006-12-11 18:30:27 +0000283 return ConstantInt::get(DestTy, CI->getZExtValue());
284
285 if (DestTy->isFloatingPoint()) {
286 if (DestTy == Type::FloatTy)
287 return ConstantFP::get(DestTy, BitsToFloat(CI->getZExtValue()));
288 assert(DestTy == Type::DoubleTy && "Unknown FP type!");
289 return ConstantFP::get(DestTy, BitsToDouble(CI->getZExtValue()));
290 }
291 // Otherwise, can't fold this (packed?)
292 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000293 }
Chris Lattner4d1da162006-12-11 18:30:27 +0000294
295 // Handle ConstantFP input.
296 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
297 // FP -> Integral.
Reid Spencera94d3942007-01-19 21:13:56 +0000298 if (DestTy->isInteger())
Chris Lattner4d1da162006-12-11 18:30:27 +0000299 return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
Chris Lattner4d1da162006-12-11 18:30:27 +0000300 }
301 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000302 default:
303 assert(!"Invalid CE CastInst opcode");
304 break;
Chris Lattner6b3f4752006-04-02 01:38:28 +0000305 }
Chris Lattnerb2b7f902004-10-11 03:57:30 +0000306
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000307 assert(0 && "Failed to cast constant expression");
308 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +0000309}
310
Chris Lattner6ea4b522004-03-12 05:53:32 +0000311Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
312 const Constant *V1,
313 const Constant *V2) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000314 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
Reid Spencercddc9df2007-01-12 04:24:46 +0000315 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000316
317 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
318 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
319 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000320 if (V1 == V2) return const_cast<Constant*>(V1);
Chris Lattner6ea4b522004-03-12 05:53:32 +0000321 return 0;
322}
323
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000324Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
325 const Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000326 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
327 return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000328 if (Val->isNullValue()) // ee(zero, x) -> zero
329 return Constant::getNullValue(
330 cast<PackedType>(Val->getType())->getElementType());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000331
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000332 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000333 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
334 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
Chris Lattnere52f29b2006-03-31 18:31:40 +0000335 } else if (isa<UndefValue>(Idx)) {
336 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
337 return const_cast<Constant*>(CVal->getOperand(0));
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000338 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000339 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000340 return 0;
341}
342
Robert Bocchinoca27f032006-01-17 20:07:22 +0000343Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
344 const Constant *Elt,
345 const Constant *Idx) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000346 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000347 if (!CIdx) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000348 uint64_t idxVal = CIdx->getZExtValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000349 if (isa<UndefValue>(Val)) {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000350 // Insertion of scalar constant into packed undef
351 // Optimize away insertion of undef
352 if (isa<UndefValue>(Elt))
353 return const_cast<Constant*>(Val);
354 // Otherwise break the aggregate undef into multiple undefs and do
355 // the insertion
356 unsigned numOps =
357 cast<PackedType>(Val->getType())->getNumElements();
358 std::vector<Constant*> Ops;
359 Ops.reserve(numOps);
360 for (unsigned i = 0; i < numOps; ++i) {
361 const Constant *Op =
362 (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
363 Ops.push_back(const_cast<Constant*>(Op));
364 }
365 return ConstantPacked::get(Ops);
366 }
Reid Spencer3054b142006-11-02 08:18:15 +0000367 if (isa<ConstantAggregateZero>(Val)) {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000368 // Insertion of scalar constant into packed aggregate zero
369 // Optimize away insertion of zero
370 if (Elt->isNullValue())
371 return const_cast<Constant*>(Val);
372 // Otherwise break the aggregate zero into multiple zeros and do
373 // the insertion
374 unsigned numOps =
375 cast<PackedType>(Val->getType())->getNumElements();
376 std::vector<Constant*> Ops;
377 Ops.reserve(numOps);
378 for (unsigned i = 0; i < numOps; ++i) {
379 const Constant *Op =
380 (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
381 Ops.push_back(const_cast<Constant*>(Op));
382 }
383 return ConstantPacked::get(Ops);
384 }
385 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
386 // Insertion of scalar constant into packed constant
387 std::vector<Constant*> Ops;
388 Ops.reserve(CVal->getNumOperands());
389 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
390 const Constant *Op =
391 (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
392 Ops.push_back(const_cast<Constant*>(Op));
393 }
394 return ConstantPacked::get(Ops);
395 }
396 return 0;
397}
398
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000399Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
400 const Constant *V2,
401 const Constant *Mask) {
402 // TODO:
403 return 0;
404}
405
Reid Spencer266e42b2006-12-23 06:05:41 +0000406/// EvalVectorOp - Given two packed constants and a function pointer, apply the
407/// function pointer to each element pair, producing a new ConstantPacked
408/// constant.
409static Constant *EvalVectorOp(const ConstantPacked *V1,
410 const ConstantPacked *V2,
411 Constant *(*FP)(Constant*, Constant*)) {
412 std::vector<Constant*> Res;
413 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
414 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
415 const_cast<Constant*>(V2->getOperand(i))));
416 return ConstantPacked::get(Res);
417}
418
419Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
420 const Constant *C1,
421 const Constant *C2) {
422 // Handle UndefValue up front
423 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
424 switch (Opcode) {
425 case Instruction::Add:
426 case Instruction::Sub:
427 case Instruction::Xor:
428 return UndefValue::get(C1->getType());
429 case Instruction::Mul:
430 case Instruction::And:
431 return Constant::getNullValue(C1->getType());
432 case Instruction::UDiv:
433 case Instruction::SDiv:
434 case Instruction::FDiv:
435 case Instruction::URem:
436 case Instruction::SRem:
437 case Instruction::FRem:
438 if (!isa<UndefValue>(C2)) // undef / X -> 0
439 return Constant::getNullValue(C1->getType());
440 return const_cast<Constant*>(C2); // X / undef -> undef
441 case Instruction::Or: // X | undef -> -1
Chris Lattner26f13eb2007-01-04 01:56:39 +0000442 if (const PackedType *PTy = dyn_cast<PackedType>(C1->getType()))
443 return ConstantPacked::getAllOnesValue(PTy);
Reid Spencer266e42b2006-12-23 06:05:41 +0000444 return ConstantInt::getAllOnesValue(C1->getType());
445 case Instruction::LShr:
446 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
447 return const_cast<Constant*>(C1); // undef lshr undef -> undef
448 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
449 // undef lshr X -> 0
450 case Instruction::AShr:
451 if (!isa<UndefValue>(C2))
452 return const_cast<Constant*>(C1); // undef ashr X --> undef
453 else if (isa<UndefValue>(C1))
454 return const_cast<Constant*>(C1); // undef ashr undef -> undef
455 else
456 return const_cast<Constant*>(C1); // X ashr undef --> X
457 case Instruction::Shl:
458 // undef << X -> 0 or X << undef -> 0
459 return Constant::getNullValue(C1->getType());
460 }
461 }
462
463 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
464 if (isa<ConstantExpr>(C2)) {
465 // There are many possible foldings we could do here. We should probably
466 // at least fold add of a pointer with an integer into the appropriate
467 // getelementptr. This will improve alias analysis a bit.
468 } else {
469 // Just implement a couple of simple identities.
470 switch (Opcode) {
471 case Instruction::Add:
472 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
473 break;
474 case Instruction::Sub:
475 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
476 break;
477 case Instruction::Mul:
478 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
479 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
480 if (CI->getZExtValue() == 1)
481 return const_cast<Constant*>(C1); // X * 1 == X
482 break;
483 case Instruction::UDiv:
484 case Instruction::SDiv:
485 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
486 if (CI->getZExtValue() == 1)
487 return const_cast<Constant*>(C1); // X / 1 == X
488 break;
489 case Instruction::URem:
490 case Instruction::SRem:
491 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
492 if (CI->getZExtValue() == 1)
493 return Constant::getNullValue(CI->getType()); // X % 1 == 0
494 break;
495 case Instruction::And:
Chris Lattner26f13eb2007-01-04 01:56:39 +0000496 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
497 if (CI->isAllOnesValue())
498 return const_cast<Constant*>(C1); // X & -1 == X
Reid Spencer266e42b2006-12-23 06:05:41 +0000499 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X & 0 == 0
500 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
501 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
502
503 // Functions are at least 4-byte aligned. If and'ing the address of a
504 // function with a constant < 4, fold it to zero.
505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
506 if (CI->getZExtValue() < 4 && isa<Function>(CPR))
507 return Constant::getNullValue(CI->getType());
508 }
509 break;
510 case Instruction::Or:
511 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
Chris Lattner26f13eb2007-01-04 01:56:39 +0000512 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
513 if (CI->isAllOnesValue())
514 return const_cast<Constant*>(C2); // X | -1 == -1
Reid Spencer266e42b2006-12-23 06:05:41 +0000515 break;
516 case Instruction::Xor:
517 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
518 break;
519 }
520 }
521 } else if (isa<ConstantExpr>(C2)) {
522 // If C2 is a constant expr and C1 isn't, flop them around and fold the
523 // other way if possible.
524 switch (Opcode) {
525 case Instruction::Add:
526 case Instruction::Mul:
527 case Instruction::And:
528 case Instruction::Or:
529 case Instruction::Xor:
530 // No change of opcode required.
531 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
532
533 case Instruction::Shl:
534 case Instruction::LShr:
535 case Instruction::AShr:
536 case Instruction::Sub:
537 case Instruction::SDiv:
538 case Instruction::UDiv:
539 case Instruction::FDiv:
540 case Instruction::URem:
541 case Instruction::SRem:
542 case Instruction::FRem:
543 default: // These instructions cannot be flopped around.
544 return 0;
545 }
546 }
547
548 // At this point we know neither constant is an UndefValue nor a ConstantExpr
Chris Lattner26f13eb2007-01-04 01:56:39 +0000549 // so look at directly computing the value.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000550 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
551 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Chris Lattner344da522007-01-12 18:42:52 +0000552 uint64_t C1Val = CI1->getZExtValue();
553 uint64_t C2Val = CI2->getZExtValue();
554 switch (Opcode) {
555 default:
556 break;
557 case Instruction::Add:
558 return ConstantInt::get(C1->getType(), C1Val + C2Val);
559 case Instruction::Sub:
560 return ConstantInt::get(C1->getType(), C1Val - C2Val);
561 case Instruction::Mul:
562 return ConstantInt::get(C1->getType(), C1Val * C2Val);
563 case Instruction::UDiv:
564 if (CI2->isNullValue()) // X / 0 -> can't fold
565 return 0;
566 return ConstantInt::get(C1->getType(), C1Val / C2Val);
567 case Instruction::SDiv:
568 if (CI2->isNullValue()) return 0; // X / 0 -> can't fold
569 if (CI2->isAllOnesValue() &&
570 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
571 (CI1->getSExtValue() == INT64_MIN)) ||
572 (CI1->getSExtValue() == -CI1->getSExtValue())))
573 return 0; // MIN_INT / -1 -> overflow
574 return ConstantInt::get(C1->getType(),
575 CI1->getSExtValue() / CI2->getSExtValue());
576 case Instruction::URem:
577 if (C2->isNullValue()) return 0; // X / 0 -> can't fold
578 return ConstantInt::get(C1->getType(), C1Val % C2Val);
579 case Instruction::SRem:
580 if (CI2->isNullValue()) return 0; // X % 0 -> can't fold
581 if (CI2->isAllOnesValue() &&
582 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
583 (CI1->getSExtValue() == INT64_MIN)) ||
584 (CI1->getSExtValue() == -CI1->getSExtValue())))
585 return 0; // MIN_INT % -1 -> overflow
586 return ConstantInt::get(C1->getType(),
587 CI1->getSExtValue() % CI2->getSExtValue());
588 case Instruction::And:
589 return ConstantInt::get(C1->getType(), C1Val & C2Val);
590 case Instruction::Or:
591 return ConstantInt::get(C1->getType(), C1Val | C2Val);
592 case Instruction::Xor:
593 return ConstantInt::get(C1->getType(), C1Val ^ C2Val);
594 case Instruction::Shl:
595 return ConstantInt::get(C1->getType(), C1Val << C2Val);
596 case Instruction::LShr:
597 return ConstantInt::get(C1->getType(), C1Val >> C2Val);
598 case Instruction::AShr:
599 return ConstantInt::get(C1->getType(),
600 CI1->getSExtValue() >> C2Val);
Reid Spencer266e42b2006-12-23 06:05:41 +0000601 }
602 }
603 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
604 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
605 double C1Val = CFP1->getValue();
606 double C2Val = CFP2->getValue();
607 switch (Opcode) {
608 default:
609 break;
610 case Instruction::Add:
611 return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
612 case Instruction::Sub:
613 return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
614 case Instruction::Mul:
615 return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
616 case Instruction::FDiv:
617 if (CFP2->isExactlyValue(0.0))
618 return ConstantFP::get(CFP1->getType(),
619 std::numeric_limits<double>::infinity());
620 if (CFP2->isExactlyValue(-0.0))
621 return ConstantFP::get(CFP1->getType(),
622 -std::numeric_limits<double>::infinity());
623 return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
624 case Instruction::FRem:
625 if (CFP2->isNullValue())
626 return 0;
627 return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
628 }
629 }
630 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
631 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
632 switch (Opcode) {
633 default:
634 break;
635 case Instruction::Add:
636 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
637 case Instruction::Sub:
638 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
639 case Instruction::Mul:
640 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
641 case Instruction::UDiv:
642 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
643 case Instruction::SDiv:
644 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
645 case Instruction::FDiv:
646 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
647 case Instruction::URem:
648 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
649 case Instruction::SRem:
650 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
651 case Instruction::FRem:
652 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
653 case Instruction::And:
654 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
655 case Instruction::Or:
656 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
657 case Instruction::Xor:
658 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
659 }
660 }
661 }
662
663 // We don't know how to fold this
664 return 0;
665}
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000666
Chris Lattner60c47262005-01-28 19:09:51 +0000667/// isZeroSizedType - This type is zero sized if its an array or structure of
668/// zero sized types. The only leaf zero sized type is an empty structure.
669static bool isMaybeZeroSizedType(const Type *Ty) {
670 if (isa<OpaqueType>(Ty)) return true; // Can't say.
671 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
672
673 // If all of elements have zero size, this does too.
674 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +0000675 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +0000676 return true;
677
678 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
679 return isMaybeZeroSizedType(ATy->getElementType());
680 }
681 return false;
682}
Chris Lattner6ea4b522004-03-12 05:53:32 +0000683
Chris Lattner061da2f2004-01-13 05:51:55 +0000684/// IdxCompare - Compare the two constants as though they were getelementptr
685/// indices. This allows coersion of the types to be the same thing.
686///
687/// If the two constants are the "same" (after coersion), return 0. If the
688/// first is less than the second, return -1, if the second is less than the
689/// first, return 1. If the constants are not integral, return -2.
690///
Chris Lattner60c47262005-01-28 19:09:51 +0000691static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000692 if (C1 == C2) return 0;
693
Reid Spencerc90cf772006-12-31 21:43:30 +0000694 // Ok, we found a different index. If they are not ConstantInt, we can't do
695 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +0000696 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
697 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +0000698
Chris Lattner69193f92004-04-05 01:30:19 +0000699 // Ok, we have two differing integer indices. Sign extend them to be the same
700 // type. Long is always big enough, so we use it.
Reid Spencer8d9336d2006-12-31 05:26:44 +0000701 if (C1->getType() != Type::Int64Ty)
702 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000703
Reid Spencer8d9336d2006-12-31 05:26:44 +0000704 if (C2->getType() != Type::Int64Ty)
Reid Spencerc90cf772006-12-31 21:43:30 +0000705 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000706
707 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +0000708
Chris Lattner60c47262005-01-28 19:09:51 +0000709 // If the type being indexed over is really just a zero sized type, there is
710 // no pointer difference being made here.
711 if (isMaybeZeroSizedType(ElTy))
712 return -2; // dunno.
713
Chris Lattner061da2f2004-01-13 05:51:55 +0000714 // If they are really different, now that they are the same type, then we
715 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +0000716 if (cast<ConstantInt>(C1)->getSExtValue() <
717 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +0000718 return -1;
719 else
720 return 1;
721}
722
Chris Lattner858f4e92007-01-04 02:13:20 +0000723/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencer266e42b2006-12-23 06:05:41 +0000724/// decide about the two constants provided. This doesn't need to handle simple
725/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
726/// If we can determine that the two constants have a particular relation to
727/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +0000728/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
729/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000730///
731/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +0000732/// operand is always the most "complex" of the two. We consider ConstantFP
733/// to be the simplest, and ConstantExprs to be the most complex.
734static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
735 const Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000736 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +0000737 "Cannot compare values of different types!");
738 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +0000739 if (V1 == V2) return FCmpInst::FCMP_OEQ;
740
Reid Spencer9d36acf2006-12-24 18:52:08 +0000741 if (!isa<ConstantExpr>(V1)) {
742 if (!isa<ConstantExpr>(V2)) {
743 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng75b871f2007-01-11 12:24:14 +0000744 ConstantInt *R = 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000745 Constant *C1 = const_cast<Constant*>(V1);
746 Constant *C2 = const_cast<Constant*>(V2);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000747 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000748 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
Reid Spencercddc9df2007-01-12 04:24:46 +0000749 if (R && R->getZExtValue())
Reid Spencer266e42b2006-12-23 06:05:41 +0000750 return FCmpInst::FCMP_OEQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000751 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000752 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
Reid Spencercddc9df2007-01-12 04:24:46 +0000753 if (R && R->getZExtValue())
Reid Spencer266e42b2006-12-23 06:05:41 +0000754 return FCmpInst::FCMP_OLT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000755 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000756 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
Reid Spencercddc9df2007-01-12 04:24:46 +0000757 if (R && R->getZExtValue())
Reid Spencer9d36acf2006-12-24 18:52:08 +0000758 return FCmpInst::FCMP_OGT;
759
760 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +0000761 return FCmpInst::BAD_FCMP_PREDICATE;
762 }
763
Reid Spencer9d36acf2006-12-24 18:52:08 +0000764 // If the first operand is simple and second is ConstantExpr, swap operands.
765 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
766 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
767 return FCmpInst::getSwappedPredicate(SwappedRelation);
768 } else {
769 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
770 // constantexpr or a simple constant.
771 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
772 switch (CE1->getOpcode()) {
773 case Instruction::FPTrunc:
774 case Instruction::FPExt:
775 case Instruction::UIToFP:
776 case Instruction::SIToFP:
777 // We might be able to do something with these but we don't right now.
778 break;
779 default:
780 break;
781 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000782 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000783 // There are MANY other foldings that we could perform here. They will
784 // probably be added on demand, as they seem needed.
785 return FCmpInst::BAD_FCMP_PREDICATE;
786}
787
788/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +0000789/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +0000790/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +0000791/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +0000792/// particular relation to each other, we should return the corresponding ICmp
793/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +0000794///
795/// To simplify this code we canonicalize the relation so that the first
796/// operand is always the most "complex" of the two. We consider simple
797/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +0000798/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +0000799///
Reid Spencer9d36acf2006-12-24 18:52:08 +0000800static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
801 const Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +0000802 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000803 assert(V1->getType() == V2->getType() &&
804 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +0000805 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +0000806
Reid Spenceraccd7c72004-07-17 23:47:01 +0000807 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000808 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
809 // We distilled this down to a simple case, use the standard constant
810 // folder.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000811 ConstantInt *R = 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000812 Constant *C1 = const_cast<Constant*>(V1);
813 Constant *C2 = const_cast<Constant*>(V2);
Reid Spencer266e42b2006-12-23 06:05:41 +0000814 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000815 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencercddc9df2007-01-12 04:24:46 +0000816 if (R && R->getZExtValue())
Reid Spencer266e42b2006-12-23 06:05:41 +0000817 return pred;
818 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000819 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencercddc9df2007-01-12 04:24:46 +0000820 if (R && R->getZExtValue())
Reid Spencer266e42b2006-12-23 06:05:41 +0000821 return pred;
822 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000823 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencercddc9df2007-01-12 04:24:46 +0000824 if (R && R->getZExtValue())
Reid Spencer266e42b2006-12-23 06:05:41 +0000825 return pred;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000826
827 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +0000828 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000829 }
830
Chris Lattner061da2f2004-01-13 05:51:55 +0000831 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +0000832 ICmpInst::Predicate SwappedRelation =
833 evaluateICmpRelation(V2, V1, isSigned);
834 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
835 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +0000836
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000837 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +0000838 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +0000839 ICmpInst::Predicate SwappedRelation =
840 evaluateICmpRelation(V2, V1, isSigned);
841 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
842 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000843 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000844 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +0000845 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000846
Reid Spenceraccd7c72004-07-17 23:47:01 +0000847 // Now we know that the RHS is a GlobalValue or simple constant,
Chris Lattner061da2f2004-01-13 05:51:55 +0000848 // which (since the types must match) means that it's a ConstantPointerNull.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000849 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Reid Spencer876f7222006-12-06 00:25:09 +0000850 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
Reid Spencer266e42b2006-12-23 06:05:41 +0000851 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000852 } else {
Reid Spencer876f7222006-12-06 00:25:09 +0000853 // GlobalVals can never be null.
Chris Lattner061da2f2004-01-13 05:51:55 +0000854 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Reid Spencer876f7222006-12-06 00:25:09 +0000855 if (!CPR1->hasExternalWeakLinkage())
Reid Spencer266e42b2006-12-23 06:05:41 +0000856 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000857 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000858 } else {
859 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
860 // constantexpr, a CPR, or a simple constant.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000861 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
862 const Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +0000863
864 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000865 case Instruction::Trunc:
866 case Instruction::FPTrunc:
867 case Instruction::FPExt:
868 case Instruction::FPToUI:
869 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +0000870 break; // We can't evaluate floating point casts or truncations.
871
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000872 case Instruction::UIToFP:
873 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000874 case Instruction::IntToPtr:
875 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +0000876 case Instruction::ZExt:
877 case Instruction::SExt:
878 case Instruction::PtrToInt:
Chris Lattner061da2f2004-01-13 05:51:55 +0000879 // If the cast is not actually changing bits, and the second operand is a
880 // null pointer, do the comparison with the pre-casted value.
881 if (V2->isNullValue() &&
Chris Lattner03c49532007-01-15 02:27:26 +0000882 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
Reid Spencerccf78ac2006-12-23 10:21:26 +0000883 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
Reid Spencer266e42b2006-12-23 06:05:41 +0000884 (CE1->getOpcode() == Instruction::SExt ? true :
885 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
886 return evaluateICmpRelation(
Reid Spencerccf78ac2006-12-23 10:21:26 +0000887 CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
Reid Spencer266e42b2006-12-23 06:05:41 +0000888 }
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000889
890 // If the dest type is a pointer type, and the RHS is a constantexpr cast
891 // from the same type as the src of the LHS, evaluate the inputs. This is
Reid Spencer266e42b2006-12-23 06:05:41 +0000892 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000893 // which happens a lot in compilers with tagged integers.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000894 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
Reid Spencer266e42b2006-12-23 06:05:41 +0000895 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000896 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
Chris Lattner03c49532007-01-15 02:27:26 +0000897 CE1->getOperand(0)->getType()->isInteger()) {
Reid Spencerccf78ac2006-12-23 10:21:26 +0000898 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
Reid Spencer266e42b2006-12-23 06:05:41 +0000899 (CE1->getOpcode() == Instruction::SExt ? true :
900 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
901 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
Reid Spencerccf78ac2006-12-23 10:21:26 +0000902 sgnd);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000903 }
Chris Lattner192e3262004-04-11 01:29:30 +0000904 break;
Chris Lattner061da2f2004-01-13 05:51:55 +0000905
906 case Instruction::GetElementPtr:
907 // Ok, since this is a getelementptr, we know that the constant has a
908 // pointer type. Check the various cases.
909 if (isa<ConstantPointerNull>(V2)) {
910 // If we are comparing a GEP to a null pointer, check to see if the base
911 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000912 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +0000913 if (GV->hasExternalWeakLinkage())
914 // Weak linkage GVals could be zero or not. We're comparing that
915 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +0000916 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +0000917 else
918 // If its not weak linkage, the GVal must have a non-zero address
919 // so the result is greater-than
Reid Spencer266e42b2006-12-23 06:05:41 +0000920 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +0000921 } else if (isa<ConstantPointerNull>(CE1Op0)) {
922 // If we are indexing from a null pointer, check to see if we have any
923 // non-zero indices.
924 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
925 if (!CE1->getOperand(i)->isNullValue())
926 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +0000927 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +0000928 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +0000929 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +0000930 }
931 // Otherwise, we can't really say if the first operand is null or not.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000932 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000933 if (isa<ConstantPointerNull>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +0000934 if (CPR2->hasExternalWeakLinkage())
935 // Weak linkage GVals could be zero or not. We're comparing it to
936 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +0000937 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +0000938 else
939 // If its not weak linkage, the GVal must have a non-zero address
940 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +0000941 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spenceraccd7c72004-07-17 23:47:01 +0000942 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000943 if (CPR1 == CPR2) {
944 // If this is a getelementptr of the same global, then it must be
945 // different. Because the types must match, the getelementptr could
946 // only have at most one index, and because we fold getelementptr's
947 // with a single zero index, it must be nonzero.
948 assert(CE1->getNumOperands() == 2 &&
949 !CE1->getOperand(1)->isNullValue() &&
950 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +0000951 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +0000952 } else {
953 // If they are different globals, we don't know what the value is,
954 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +0000955 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000956 }
957 }
958 } else {
959 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
960 const Constant *CE2Op0 = CE2->getOperand(0);
961
962 // There are MANY other foldings that we could perform here. They will
963 // probably be added on demand, as they seem needed.
964 switch (CE2->getOpcode()) {
965 default: break;
966 case Instruction::GetElementPtr:
967 // By far the most common case to handle is when the base pointers are
968 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000969 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000970 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +0000971 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000972 // Ok, we know that both getelementptr instructions are based on the
973 // same global. From this, we can precisely determine the relative
974 // ordering of the resultant pointers.
975 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000976
Chris Lattner061da2f2004-01-13 05:51:55 +0000977 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +0000978 gep_type_iterator GTI = gep_type_begin(CE1);
979 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
980 ++i, ++GTI)
981 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
982 GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000983 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
984 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
985 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000986 }
987
988 // Ok, we ran out of things they have in common. If any leftovers
989 // are non-zero then we have a difference, otherwise we are equal.
990 for (; i < CE1->getNumOperands(); ++i)
991 if (!CE1->getOperand(i)->isNullValue())
Zhou Sheng75b871f2007-01-11 12:24:14 +0000992 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000993 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +0000994 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000995 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000996
Chris Lattner061da2f2004-01-13 05:51:55 +0000997 for (; i < CE2->getNumOperands(); ++i)
998 if (!CE2->getOperand(i)->isNullValue())
Zhou Sheng75b871f2007-01-11 12:24:14 +0000999 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001000 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001001 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001002 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1003 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001004 }
1005 }
1006 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001007 default:
1008 break;
1009 }
1010 }
1011
Reid Spencer266e42b2006-12-23 06:05:41 +00001012 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001013}
1014
Reid Spencer9d36acf2006-12-24 18:52:08 +00001015Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1016 const Constant *C1,
1017 const Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001018
1019 // Handle some degenerate cases first
1020 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
Reid Spencer542964f2007-01-11 18:21:29 +00001021 return UndefValue::get(Type::Int1Ty);
Reid Spencer266e42b2006-12-23 06:05:41 +00001022
1023 // icmp eq/ne(null,GV) -> false/true
1024 if (C1->isNullValue()) {
1025 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1026 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
Reid Spencer9d36acf2006-12-24 18:52:08 +00001027 if (pred == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001028 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001029 else if (pred == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001030 return ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00001031 // icmp eq/ne(GV,null) -> false/true
1032 } else if (C2->isNullValue()) {
1033 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1034 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
Reid Spencer9d36acf2006-12-24 18:52:08 +00001035 if (pred == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001036 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001037 else if (pred == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001038 return ConstantInt::getTrue();
Chris Lattner1dd054c2004-01-12 22:07:24 +00001039 }
1040
Chris Lattner344da522007-01-12 18:42:52 +00001041 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001042 if (ICmpInst::isSignedPredicate(ICmpInst::Predicate(pred))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001043 int64_t V1 = cast<ConstantInt>(C1)->getSExtValue();
1044 int64_t V2 = cast<ConstantInt>(C2)->getSExtValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001045 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001046 default: assert(0 && "Invalid ICmp Predicate"); return 0;
Reid Spencercddc9df2007-01-12 04:24:46 +00001047 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1 < V2);
1048 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1 > V2);
1049 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1050 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
Reid Spencer266e42b2006-12-23 06:05:41 +00001051 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001052 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00001053 uint64_t V1 = cast<ConstantInt>(C1)->getZExtValue();
1054 uint64_t V2 = cast<ConstantInt>(C2)->getZExtValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001055 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001056 default: assert(0 && "Invalid ICmp Predicate"); return 0;
Reid Spencercddc9df2007-01-12 04:24:46 +00001057 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1058 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1059 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1 < V2);
1060 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1 > V2);
1061 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1 <= V2);
1062 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1 >= V2);
Chris Lattner061da2f2004-01-13 05:51:55 +00001063 }
1064 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001065 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1066 double C1Val = cast<ConstantFP>(C1)->getValue();
1067 double C2Val = cast<ConstantFP>(C2)->getValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001068 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001069 default: assert(0 && "Invalid FCmp Predicate"); return 0;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001070 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1071 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00001072 case FCmpInst::FCMP_UNO:
Reid Spencercddc9df2007-01-12 04:24:46 +00001073 return ConstantInt::get(Type::Int1Ty, C1Val != C1Val || C2Val != C2Val);
Reid Spencer74bd0362007-01-11 00:25:45 +00001074 case FCmpInst::FCMP_ORD:
Reid Spencercddc9df2007-01-12 04:24:46 +00001075 return ConstantInt::get(Type::Int1Ty, C1Val == C1Val && C2Val == C2Val);
Reid Spencer266e42b2006-12-23 06:05:41 +00001076 case FCmpInst::FCMP_UEQ:
Reid Spencer74bd0362007-01-11 00:25:45 +00001077 if (C1Val != C1Val || C2Val != C2Val)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001078 return ConstantInt::getTrue();
Reid Spencer74bd0362007-01-11 00:25:45 +00001079 /* FALL THROUGH */
Reid Spencercddc9df2007-01-12 04:24:46 +00001080 case FCmpInst::FCMP_OEQ:
1081 return ConstantInt::get(Type::Int1Ty, C1Val == C2Val);
Reid Spencer74bd0362007-01-11 00:25:45 +00001082 case FCmpInst::FCMP_UNE:
1083 if (C1Val != C1Val || C2Val != C2Val)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001084 return ConstantInt::getTrue();
Reid Spencer74bd0362007-01-11 00:25:45 +00001085 /* FALL THROUGH */
Reid Spencercddc9df2007-01-12 04:24:46 +00001086 case FCmpInst::FCMP_ONE:
1087 return ConstantInt::get(Type::Int1Ty, C1Val != C2Val);
Reid Spencer74bd0362007-01-11 00:25:45 +00001088 case FCmpInst::FCMP_ULT:
1089 if (C1Val != C1Val || C2Val != C2Val)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001090 return ConstantInt::getTrue();
Reid Spencer74bd0362007-01-11 00:25:45 +00001091 /* FALL THROUGH */
Reid Spencercddc9df2007-01-12 04:24:46 +00001092 case FCmpInst::FCMP_OLT:
1093 return ConstantInt::get(Type::Int1Ty, C1Val < C2Val);
Reid Spencer266e42b2006-12-23 06:05:41 +00001094 case FCmpInst::FCMP_UGT:
Reid Spencer74bd0362007-01-11 00:25:45 +00001095 if (C1Val != C1Val || C2Val != C2Val)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001096 return ConstantInt::getTrue();
Reid Spencer74bd0362007-01-11 00:25:45 +00001097 /* FALL THROUGH */
Reid Spencercddc9df2007-01-12 04:24:46 +00001098 case FCmpInst::FCMP_OGT:
1099 return ConstantInt::get(Type::Int1Ty, C1Val > C2Val);
Reid Spencer74bd0362007-01-11 00:25:45 +00001100 case FCmpInst::FCMP_ULE:
1101 if (C1Val != C1Val || C2Val != C2Val)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001102 return ConstantInt::getTrue();
Reid Spencer74bd0362007-01-11 00:25:45 +00001103 /* FALL THROUGH */
Reid Spencercddc9df2007-01-12 04:24:46 +00001104 case FCmpInst::FCMP_OLE:
1105 return ConstantInt::get(Type::Int1Ty, C1Val <= C2Val);
Reid Spencer266e42b2006-12-23 06:05:41 +00001106 case FCmpInst::FCMP_UGE:
Reid Spencer74bd0362007-01-11 00:25:45 +00001107 if (C1Val != C1Val || C2Val != C2Val)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001108 return ConstantInt::getTrue();
Reid Spencer74bd0362007-01-11 00:25:45 +00001109 /* FALL THROUGH */
Reid Spencercddc9df2007-01-12 04:24:46 +00001110 case FCmpInst::FCMP_OGE:
1111 return ConstantInt::get(Type::Int1Ty, C1Val >= C2Val);
Reid Spencer266e42b2006-12-23 06:05:41 +00001112 }
Reid Spencer9d36acf2006-12-24 18:52:08 +00001113 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
1114 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
1115 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001116 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1117 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1118 const_cast<Constant*>(CP1->getOperand(i)),
1119 const_cast<Constant*>(CP2->getOperand(i)));
Zhou Sheng75b871f2007-01-11 12:24:14 +00001120 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
Reid Spencer266e42b2006-12-23 06:05:41 +00001121 return CB;
1122 }
1123 // Otherwise, could not decide from any element pairs.
1124 return 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001125 } else if (pred == ICmpInst::ICMP_EQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001126 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1127 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1128 const_cast<Constant*>(CP1->getOperand(i)),
1129 const_cast<Constant*>(CP2->getOperand(i)));
Zhou Sheng75b871f2007-01-11 12:24:14 +00001130 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
Reid Spencer266e42b2006-12-23 06:05:41 +00001131 return CB;
1132 }
1133 // Otherwise, could not decide from any element pairs.
1134 return 0;
1135 }
1136 }
1137 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001138
Reid Spencer9d36acf2006-12-24 18:52:08 +00001139 if (C1->getType()->isFloatingPoint()) {
1140 switch (evaluateFCmpRelation(C1, C2)) {
1141 default: assert(0 && "Unknown relation!");
1142 case FCmpInst::FCMP_UNO:
1143 case FCmpInst::FCMP_ORD:
1144 case FCmpInst::FCMP_UEQ:
1145 case FCmpInst::FCMP_UNE:
1146 case FCmpInst::FCMP_ULT:
1147 case FCmpInst::FCMP_UGT:
1148 case FCmpInst::FCMP_ULE:
1149 case FCmpInst::FCMP_UGE:
1150 case FCmpInst::FCMP_TRUE:
1151 case FCmpInst::FCMP_FALSE:
1152 case FCmpInst::BAD_FCMP_PREDICATE:
1153 break; // Couldn't determine anything about these constants.
1154 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001155 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001156 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1157 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1158 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1159 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001160 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001161 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1162 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1163 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1164 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001165 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001166 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1167 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1168 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1169 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1170 // We can only partially decide this relation.
1171 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001172 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001173 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001174 return ConstantInt::getTrue();
Chris Lattner061da2f2004-01-13 05:51:55 +00001175 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001176 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1177 // We can only partially decide this relation.
1178 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001179 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001180 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001181 return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001182 break;
1183 case ICmpInst::ICMP_NE: // We know that C1 != C2
1184 // We can only partially decide this relation.
1185 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001186 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001187 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001188 return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001189 break;
1190 }
1191 } else {
1192 // Evaluate the relation between the two constants, per the predicate.
1193 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1194 default: assert(0 && "Unknown relational!");
1195 case ICmpInst::BAD_ICMP_PREDICATE:
1196 break; // Couldn't determine anything about these constants.
1197 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1198 // If we know the constants are equal, we can decide the result of this
1199 // computation precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001200 return ConstantInt::get(Type::Int1Ty,
1201 pred == ICmpInst::ICMP_EQ ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001202 pred == ICmpInst::ICMP_ULE ||
1203 pred == ICmpInst::ICMP_SLE ||
1204 pred == ICmpInst::ICMP_UGE ||
1205 pred == ICmpInst::ICMP_SGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001206 case ICmpInst::ICMP_ULT:
1207 // If we know that C1 < C2, we can decide the result of this computation
1208 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001209 return ConstantInt::get(Type::Int1Ty,
1210 pred == ICmpInst::ICMP_ULT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001211 pred == ICmpInst::ICMP_NE ||
1212 pred == ICmpInst::ICMP_ULE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001213 case ICmpInst::ICMP_SLT:
1214 // If we know that C1 < C2, we can decide the result of this computation
1215 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001216 return ConstantInt::get(Type::Int1Ty,
1217 pred == ICmpInst::ICMP_SLT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001218 pred == ICmpInst::ICMP_NE ||
1219 pred == ICmpInst::ICMP_SLE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001220 case ICmpInst::ICMP_UGT:
1221 // If we know that C1 > C2, we can decide the result of this computation
1222 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001223 return ConstantInt::get(Type::Int1Ty,
1224 pred == ICmpInst::ICMP_UGT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001225 pred == ICmpInst::ICMP_NE ||
1226 pred == ICmpInst::ICMP_UGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001227 case ICmpInst::ICMP_SGT:
1228 // If we know that C1 > C2, we can decide the result of this computation
1229 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001230 return ConstantInt::get(Type::Int1Ty,
1231 pred == ICmpInst::ICMP_SGT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001232 pred == ICmpInst::ICMP_NE ||
1233 pred == ICmpInst::ICMP_SGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001234 case ICmpInst::ICMP_ULE:
1235 // If we know that C1 <= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001236 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1237 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001238 break;
1239 case ICmpInst::ICMP_SLE:
1240 // If we know that C1 <= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001241 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1242 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001243 break;
1244
1245 case ICmpInst::ICMP_UGE:
1246 // If we know that C1 >= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001247 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1248 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001249 break;
1250 case ICmpInst::ICMP_SGE:
1251 // If we know that C1 >= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001252 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1253 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001254 break;
1255
1256 case ICmpInst::ICMP_NE:
1257 // If we know that C1 != C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001258 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1259 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001260 break;
1261 }
1262
1263 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1264 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1265 // other way if possible.
1266 switch (pred) {
1267 case ICmpInst::ICMP_EQ:
1268 case ICmpInst::ICMP_NE:
1269 // No change of predicate required.
1270 return ConstantFoldCompareInstruction(pred, C2, C1);
1271
1272 case ICmpInst::ICMP_ULT:
1273 case ICmpInst::ICMP_SLT:
1274 case ICmpInst::ICMP_UGT:
1275 case ICmpInst::ICMP_SGT:
1276 case ICmpInst::ICMP_ULE:
1277 case ICmpInst::ICMP_SLE:
1278 case ICmpInst::ICMP_UGE:
1279 case ICmpInst::ICMP_SGE:
1280 // Change the predicate as necessary to swap the operands.
1281 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1282 return ConstantFoldCompareInstruction(pred, C2, C1);
1283
1284 default: // These predicates cannot be flopped around.
1285 break;
1286 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001287 }
1288 }
1289 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001290}
1291
1292Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001293 const std::vector<Value*> &IdxList) {
Chris Lattner1dd054c2004-01-12 22:07:24 +00001294 if (IdxList.size() == 0 ||
Chris Lattner13128ab2004-10-11 22:52:25 +00001295 (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001296 return const_cast<Constant*>(C);
1297
Chris Lattnerf6013752004-10-17 21:54:55 +00001298 if (isa<UndefValue>(C)) {
1299 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1300 true);
1301 assert(Ty != 0 && "Invalid indices for GEP!");
1302 return UndefValue::get(PointerType::get(Ty));
1303 }
1304
1305 Constant *Idx0 = cast<Constant>(IdxList[0]);
Chris Lattner04b60fe2004-02-16 20:46:13 +00001306 if (C->isNullValue()) {
1307 bool isNull = true;
1308 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001309 if (!cast<Constant>(IdxList[i])->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00001310 isNull = false;
1311 break;
1312 }
1313 if (isNull) {
Chris Lattner13128ab2004-10-11 22:52:25 +00001314 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
Chris Lattner04b60fe2004-02-16 20:46:13 +00001315 true);
1316 assert(Ty != 0 && "Invalid indices for GEP!");
1317 return ConstantPointerNull::get(PointerType::get(Ty));
1318 }
1319 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001320
1321 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1322 // Combine Indices - If the source pointer to this getelementptr instruction
1323 // is a getelementptr instruction, combine the indices of the two
1324 // getelementptr instructions into a single instruction.
1325 //
1326 if (CE->getOpcode() == Instruction::GetElementPtr) {
1327 const Type *LastTy = 0;
1328 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1329 I != E; ++I)
1330 LastTy = *I;
1331
Chris Lattner13128ab2004-10-11 22:52:25 +00001332 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1333 std::vector<Value*> NewIndices;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001334 NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1335 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001336 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00001337
1338 // Add the last index of the source with the first index of the new GEP.
1339 // Make sure to handle the case when they are actually different types.
1340 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001341 // Otherwise it must be an array.
1342 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00001343 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00001344 if (IdxTy != Idx0->getType()) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001345 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
Reid Spencer27720a92006-12-05 03:30:09 +00001346 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
Reid Spencer8d9336d2006-12-31 05:26:44 +00001347 Type::Int64Ty);
Reid Spencer1a063892006-12-04 02:46:44 +00001348 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1349 } else {
1350 Combined =
1351 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1352 }
Chris Lattner71068a02004-07-07 04:45:13 +00001353 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001354
Chris Lattner1dd054c2004-01-12 22:07:24 +00001355 NewIndices.push_back(Combined);
1356 NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1357 return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1358 }
1359 }
1360
1361 // Implement folding of:
1362 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1363 // long 0, long 0)
1364 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1365 //
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001366 if (CE->isCast() && IdxList.size() > 1 && Idx0->isNullValue())
Misha Brukmanb1c93172005-04-21 23:48:37 +00001367 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00001368 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1369 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1370 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00001371 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001372 if (CAT->getElementType() == SAT->getElementType())
1373 return ConstantExpr::getGetElementPtr(
1374 (Constant*)CE->getOperand(0), IdxList);
1375 }
1376 return 0;
1377}
1378