blob: d537b273761c9e998c0b96f18faf55c8ba70077b [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Dan Gohman21c62162009-09-11 00:04:14 +000015// pieces that don't need TargetData, and the pieces that do. This is to avoid
16// a dependence in VMCore on Target.
Chris Lattner1dd054c2004-01-12 22:07:24 +000017//
Chris Lattner2f7c9632001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
Chris Lattner33e93b82007-02-27 03:05:06 +000020#include "ConstantFold.h"
Chris Lattner6ff6cea2004-01-12 21:02:29 +000021#include "llvm/Constants.h"
Chris Lattnera9eddae2004-02-22 06:25:38 +000022#include "llvm/Instructions.h"
Chris Lattner1f0049c2003-04-17 19:24:18 +000023#include "llvm/DerivedTypes.h"
Chris Lattnerea0789c2004-03-08 06:17:35 +000024#include "llvm/Function.h"
Chris Lattner52fe8692007-09-10 23:42:42 +000025#include "llvm/GlobalAlias.h"
Dan Gohman21c62162009-09-11 00:04:14 +000026#include "llvm/GlobalVariable.h"
Owen Anderson53a52212009-07-13 04:09:18 +000027#include "llvm/LLVMContext.h"
Chris Lattner302116a2007-01-31 04:40:28 +000028#include "llvm/ADT/SmallVector.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000029#include "llvm/Support/Compiler.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner057083f2006-10-13 17:22:21 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/ManagedStatic.h"
33#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000034#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000035using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000036
Chris Lattner1dd054c2004-01-12 22:07:24 +000037//===----------------------------------------------------------------------===//
38// ConstantFold*Instruction Implementations
39//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000040
Chris Lattner5c6399e2007-12-11 06:07:39 +000041/// BitCastConstantVector - Convert the specified ConstantVector node to the
Reid Spencer09575ba2007-02-15 03:39:18 +000042/// specified vector type. At this point, we know that the elements of the
Dan Gohman06c60b62007-07-16 14:29:03 +000043/// input vector constant are all simple integer or FP values.
Owen Anderson53a52212009-07-13 04:09:18 +000044static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
Owen Anderson0d2de8c2009-06-20 00:24:58 +000045 const VectorType *DstTy) {
Chris Lattner5c6399e2007-12-11 06:07:39 +000046 // If this cast changes element count then we can't handle it here:
47 // doing so requires endianness information. This should be handled by
48 // Analysis/ConstantFolding.cpp
49 unsigned NumElts = DstTy->getNumElements();
50 if (NumElts != CV->getNumOperands())
51 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +000052
Chris Lattner5c6399e2007-12-11 06:07:39 +000053 // Check to verify that all elements of the input are simple.
54 for (unsigned i = 0; i != NumElts; ++i) {
55 if (!isa<ConstantInt>(CV->getOperand(i)) &&
56 !isa<ConstantFP>(CV->getOperand(i)))
57 return 0;
Chris Lattner6b3f4752006-04-02 01:38:28 +000058 }
Chris Lattner5c6399e2007-12-11 06:07:39 +000059
60 // Bitcast each element now.
61 std::vector<Constant*> Result;
62 const Type *DstEltTy = DstTy->getElementType();
63 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson487375e2009-07-29 18:55:55 +000064 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
Owen Anderson53a52212009-07-13 04:09:18 +000065 DstEltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +000066 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000067}
68
Reid Spencer6c38f0b2006-11-27 01:05:10 +000069/// This function determines which opcode to use to fold two constant cast
70/// expressions together. It uses CastInst::isEliminableCastPair to determine
71/// the opcode. Consequently its just a wrapper around that function.
Reid Spencer05d55b32007-08-05 19:27:01 +000072/// @brief Determine if it is valid to fold a cast of a cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +000073static unsigned
74foldConstantCastPair(
75 unsigned opc, ///< opcode of the second cast constant expression
Nick Lewyckye0332982009-09-20 01:35:59 +000076 ConstantExpr *Op, ///< the first cast constant expression
Reid Spencer6c38f0b2006-11-27 01:05:10 +000077 const Type *DstTy ///< desintation type of the first cast
78) {
79 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
80 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
81 assert(CastInst::isCast(opc) && "Invalid cast opcode");
Dan Gohman062d3782009-08-29 23:35:16 +000082
Reid Spencer6c38f0b2006-11-27 01:05:10 +000083 // The the types and opcodes for the two Cast constant expressions
84 const Type *SrcTy = Op->getOperand(0)->getType();
85 const Type *MidTy = Op->getType();
86 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
87 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +000088
Reid Spencer6c38f0b2006-11-27 01:05:10 +000089 // Let CastInst::isEliminableCastPair do the heavy lifting.
90 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Owen Anderson55f1c092009-08-13 21:58:54 +000091 Type::getInt64Ty(DstTy->getContext()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +000092}
93
Owen Anderson53a52212009-07-13 04:09:18 +000094static Constant *FoldBitCast(LLVMContext &Context,
95 Constant *V, const Type *DestTy) {
Chris Lattnere8ea0372007-12-11 05:55:02 +000096 const Type *SrcTy = V->getType();
97 if (SrcTy == DestTy)
98 return V; // no-op cast
Dan Gohman062d3782009-08-29 23:35:16 +000099
Chris Lattnere8ea0372007-12-11 05:55:02 +0000100 // Check to see if we are casting a pointer to an aggregate to a pointer to
101 // the first element. If so, return the appropriate GEP instruction.
102 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000103 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
104 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
105 SmallVector<Value*, 8> IdxList;
Owen Anderson55f1c092009-08-13 21:58:54 +0000106 Value *Zero = Constant::getNullValue(Type::getInt32Ty(Context));
Dan Gohman76733742009-08-12 00:32:55 +0000107 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000108 const Type *ElTy = PTy->getElementType();
109 while (ElTy != DPTy->getElementType()) {
110 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
111 if (STy->getNumElements() == 0) break;
112 ElTy = STy->getElementType(0);
Dan Gohman76733742009-08-12 00:32:55 +0000113 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000114 } else if (const SequentialType *STy =
115 dyn_cast<SequentialType>(ElTy)) {
116 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
117 ElTy = STy->getElementType();
Dan Gohman76733742009-08-12 00:32:55 +0000118 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000119 } else {
120 break;
121 }
Chris Lattnere8ea0372007-12-11 05:55:02 +0000122 }
Dan Gohman062d3782009-08-29 23:35:16 +0000123
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000124 if (ElTy == DPTy->getElementType())
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000125 // This GEP is inbounds because all indices are zero.
126 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
127 IdxList.size());
Chris Lattnere8ea0372007-12-11 05:55:02 +0000128 }
Dan Gohman062d3782009-08-29 23:35:16 +0000129
Chris Lattnere8ea0372007-12-11 05:55:02 +0000130 // Handle casts from one vector constant to another. We know that the src
131 // and dest type have the same size (otherwise its an illegal cast).
132 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
133 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
134 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
135 "Not cast between same sized vectors!");
Devang Pateld26344d2008-11-03 23:20:04 +0000136 SrcTy = NULL;
Chris Lattnere8ea0372007-12-11 05:55:02 +0000137 // First, check for null. Undef is already handled.
138 if (isa<ConstantAggregateZero>(V))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000139 return Constant::getNullValue(DestTy);
Dan Gohman062d3782009-08-29 23:35:16 +0000140
Chris Lattner5c6399e2007-12-11 06:07:39 +0000141 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
Owen Anderson53a52212009-07-13 04:09:18 +0000142 return BitCastConstantVector(Context, CV, DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000143 }
Chris Lattner1baace02008-10-16 05:26:51 +0000144
145 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
146 // This allows for other simplifications (although some of them
147 // can only be handled by Analysis/ConstantFolding.cpp).
148 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000149 return ConstantExpr::getBitCast(
Owen Anderson4aa32952009-07-28 21:19:26 +0000150 ConstantVector::get(&V, 1), DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000151 }
Dan Gohman062d3782009-08-29 23:35:16 +0000152
Chris Lattnere8ea0372007-12-11 05:55:02 +0000153 // Finally, implement bitcast folding now. The code below doesn't handle
154 // bitcast right.
155 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000156 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Dan Gohman062d3782009-08-29 23:35:16 +0000157
Chris Lattnere8ea0372007-12-11 05:55:02 +0000158 // Handle integral constant input.
Nick Lewyckye0332982009-09-20 01:35:59 +0000159 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattnere8ea0372007-12-11 05:55:02 +0000160 if (DestTy->isInteger())
161 // Integral -> Integral. This is a no-op because the bit widths must
162 // be the same. Consequently, we just fold to V.
163 return V;
Duncan Sands1ea11732009-02-04 10:17:14 +0000164
165 if (DestTy->isFloatingPoint())
Owen Anderson69c464d2009-07-27 20:59:43 +0000166 return ConstantFP::get(Context, APFloat(CI->getValue(),
Owen Anderson55f1c092009-08-13 21:58:54 +0000167 DestTy != Type::getPPC_FP128Ty(Context)));
Duncan Sands1ea11732009-02-04 10:17:14 +0000168
Chris Lattnere8ea0372007-12-11 05:55:02 +0000169 // Otherwise, can't fold this (vector?)
170 return 0;
171 }
Duncan Sandse7d54792009-02-04 11:17:06 +0000172
Chris Lattnere8ea0372007-12-11 05:55:02 +0000173 // Handle ConstantFP input.
Nick Lewyckye0332982009-09-20 01:35:59 +0000174 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
Chris Lattnere8ea0372007-12-11 05:55:02 +0000175 // FP -> Integral.
Owen Andersonedb4a702009-07-24 23:12:02 +0000176 return ConstantInt::get(Context, FP->getValueAPF().bitcastToAPInt());
Duncan Sandse7d54792009-02-04 11:17:06 +0000177
Chris Lattnere8ea0372007-12-11 05:55:02 +0000178 return 0;
179}
180
181
Chris Lattnerf67d2972009-10-17 21:53:27 +0000182/// ExtractConstantBytes - V is an integer constant which only has a subset of
183/// its bytes used. The bytes used are indicated by ByteStart (which is the
184/// first byte used, counting from the least significant byte) and ByteSize,
185/// which is the number of bytes used.
186///
187/// This function analyzes the specified constant to see if the specified byte
188/// range can be returned as a simplified constant. If so, the constant is
189/// returned, otherwise null is returned.
190///
191static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
192 unsigned ByteSize) {
193 assert(isa<IntegerType>(C->getType()) &&
194 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
195 "Non-byte sized integer input");
196 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
197 assert(ByteSize && "Must be accessing some piece");
198 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
199 assert(ByteSize != CSize && "Should not extract everything");
200
201 // Constant Integers are simple.
202 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
203 APInt V = CI->getValue();
204 if (ByteStart)
205 V = V.lshr(ByteStart*8);
206 V.trunc(ByteSize*8);
207 return ConstantInt::get(CI->getContext(), V);
208 }
209
210 // In the input is a constant expr, we might be able to recursively simplify.
211 // If not, we definitely can't do anything.
212 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
213 if (CE == 0) return 0;
214
215 switch (CE->getOpcode()) {
216 default: return 0;
217 case Instruction::Or: {
Chris Lattnera91a5632009-10-28 05:14:34 +0000218 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000219 if (RHS == 0)
220 return 0;
221
222 // X | -1 -> -1.
223 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
224 if (RHSC->isAllOnesValue())
225 return RHSC;
226
Chris Lattnera91a5632009-10-28 05:14:34 +0000227 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000228 if (LHS == 0)
229 return 0;
230 return ConstantExpr::getOr(LHS, RHS);
231 }
232 case Instruction::And: {
Chris Lattnera91a5632009-10-28 05:14:34 +0000233 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000234 if (RHS == 0)
235 return 0;
236
237 // X & 0 -> 0.
238 if (RHS->isNullValue())
239 return RHS;
240
Chris Lattnera91a5632009-10-28 05:14:34 +0000241 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000242 if (LHS == 0)
243 return 0;
244 return ConstantExpr::getAnd(LHS, RHS);
245 }
246 case Instruction::LShr: {
247 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
248 if (Amt == 0)
249 return 0;
250 unsigned ShAmt = Amt->getZExtValue();
251 // Cannot analyze non-byte shifts.
252 if ((ShAmt & 7) != 0)
253 return 0;
254 ShAmt >>= 3;
255
256 // If the extract is known to be all zeros, return zero.
257 if (ByteStart >= CSize-ShAmt)
258 return Constant::getNullValue(IntegerType::get(CE->getContext(),
259 ByteSize*8));
260 // If the extract is known to be fully in the input, extract it.
261 if (ByteStart+ByteSize+ShAmt <= CSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000262 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000263
264 // TODO: Handle the 'partially zero' case.
265 return 0;
266 }
267
268 case Instruction::Shl: {
269 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
270 if (Amt == 0)
271 return 0;
272 unsigned ShAmt = Amt->getZExtValue();
273 // Cannot analyze non-byte shifts.
274 if ((ShAmt & 7) != 0)
275 return 0;
276 ShAmt >>= 3;
277
278 // If the extract is known to be all zeros, return zero.
279 if (ByteStart+ByteSize <= ShAmt)
280 return Constant::getNullValue(IntegerType::get(CE->getContext(),
281 ByteSize*8));
282 // If the extract is known to be fully in the input, extract it.
283 if (ByteStart >= ShAmt)
Chris Lattnera91a5632009-10-28 05:14:34 +0000284 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000285
286 // TODO: Handle the 'partially zero' case.
287 return 0;
288 }
289
290 case Instruction::ZExt: {
291 unsigned SrcBitSize =
Chris Lattnera91a5632009-10-28 05:14:34 +0000292 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
Chris Lattnerf67d2972009-10-17 21:53:27 +0000293
294 // If extracting something that is completely zero, return 0.
295 if (ByteStart*8 >= SrcBitSize)
296 return Constant::getNullValue(IntegerType::get(CE->getContext(),
297 ByteSize*8));
298
299 // If exactly extracting the input, return it.
300 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000301 return CE->getOperand(0);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000302
303 // If extracting something completely in the input, if if the input is a
304 // multiple of 8 bits, recurse.
305 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000306 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000307
308 // Otherwise, if extracting a subset of the input, which is not multiple of
309 // 8 bits, do a shift and trunc to get the bits.
310 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
311 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
Chris Lattnera91a5632009-10-28 05:14:34 +0000312 Constant *Res = CE->getOperand(0);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000313 if (ByteStart)
314 Res = ConstantExpr::getLShr(Res,
315 ConstantInt::get(Res->getType(), ByteStart*8));
316 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
317 ByteSize*8));
318 }
319
320 // TODO: Handle the 'partially zero' case.
321 return 0;
322 }
323 }
324}
325
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000326/// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
327/// on Ty, with any known factors factored out. If Folded is false,
328/// return null if no factoring was possible, to avoid endlessly
329/// bouncing an unfoldable expression back into the top-level folder.
330///
331static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
332 bool Folded) {
333 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
334 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
335 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
336 return ConstantExpr::getNUWMul(E, N);
337 }
338 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
339 Constant *N = ConstantInt::get(DestTy, VTy->getNumElements());
340 Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
341 return ConstantExpr::getNUWMul(E, N);
342 }
343 if (const StructType *STy = dyn_cast<StructType>(Ty))
344 if (!STy->isPacked()) {
345 unsigned NumElems = STy->getNumElements();
346 // An empty struct has size zero.
347 if (NumElems == 0)
348 return ConstantExpr::getNullValue(DestTy);
349 // Check for a struct with all members having the same type.
350 const Type *MemberTy = STy->getElementType(0);
351 bool AllSame = true;
352 for (unsigned i = 1; i != NumElems; ++i)
353 if (MemberTy != STy->getElementType(i)) {
354 AllSame = false;
355 break;
356 }
357 if (AllSame) {
358 Constant *N = ConstantInt::get(DestTy, NumElems);
359 Constant *E = getFoldedSizeOf(MemberTy, DestTy, true);
360 return ConstantExpr::getNUWMul(E, N);
361 }
362 }
363
364 // If there's no interesting folding happening, bail so that we don't create
365 // a constant that looks like it needs folding but really doesn't.
366 if (!Folded)
367 return 0;
368
369 // Base case: Get a regular sizeof expression.
370 Constant *C = ConstantExpr::getSizeOf(Ty);
371 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
372 DestTy, false),
373 C, DestTy);
374 return C;
375}
376
377/// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
378/// on Ty and FieldNo, with any known factors factored out. If Folded is false,
379/// return null if no factoring was possible, to avoid endlessly
380/// bouncing an unfoldable expression back into the top-level folder.
381///
382static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
383 const Type *DestTy,
384 bool Folded) {
385 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
386 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
387 DestTy, false),
388 FieldNo, DestTy);
389 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
390 return ConstantExpr::getNUWMul(E, N);
391 }
392 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
393 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
394 DestTy, false),
395 FieldNo, DestTy);
396 Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
397 return ConstantExpr::getNUWMul(E, N);
398 }
399 if (const StructType *STy = dyn_cast<StructType>(Ty))
400 if (!STy->isPacked()) {
401 unsigned NumElems = STy->getNumElements();
402 // An empty struct has no members.
403 if (NumElems == 0)
404 return 0;
405 // Check for a struct with all members having the same type.
406 const Type *MemberTy = STy->getElementType(0);
407 bool AllSame = true;
408 for (unsigned i = 1; i != NumElems; ++i)
409 if (MemberTy != STy->getElementType(i)) {
410 AllSame = false;
411 break;
412 }
413 if (AllSame) {
414 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
415 false,
416 DestTy,
417 false),
418 FieldNo, DestTy);
419 Constant *E = getFoldedSizeOf(MemberTy, DestTy, true);
420 return ConstantExpr::getNUWMul(E, N);
421 }
422 }
423
424 // If there's no interesting folding happening, bail so that we don't create
425 // a constant that looks like it needs folding but really doesn't.
426 if (!Folded)
427 return 0;
428
429 // Base case: Get a regular offsetof expression.
430 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
431 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
432 DestTy, false),
433 C, DestTy);
434 return C;
435}
Chris Lattnerf67d2972009-10-17 21:53:27 +0000436
Owen Anderson53a52212009-07-13 04:09:18 +0000437Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000438 unsigned opc, Constant *V,
Owen Anderson0d2de8c2009-06-20 00:24:58 +0000439 const Type *DestTy) {
Chris Lattner363485d2007-07-20 22:09:02 +0000440 if (isa<UndefValue>(V)) {
441 // zext(undef) = 0, because the top bits will be zero.
442 // sext(undef) = 0, because the top bits will all be the same.
Chris Lattnerb4c6cc92008-02-19 06:22:12 +0000443 // [us]itofp(undef) = 0, because the result value is bounded.
444 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
445 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
Owen Anderson5a1acd92009-07-31 20:28:14 +0000446 return Constant::getNullValue(DestTy);
Owen Andersonb292b8c2009-07-30 23:03:37 +0000447 return UndefValue::get(DestTy);
Chris Lattner363485d2007-07-20 22:09:02 +0000448 }
Dale Johannesen19db0932007-10-14 01:56:47 +0000449 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +0000450 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +0000451 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000452
453 // If the cast operand is a constant expression, there's a few things we can
454 // do to try to simplify it.
Nick Lewyckye0332982009-09-20 01:35:59 +0000455 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000456 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000457 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000458 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
Owen Anderson487375e2009-07-29 18:55:55 +0000459 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000460 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
461 // If all of the indexes in the GEP are null values, there is no pointer
462 // adjustment going on. We might as well cast the source pointer.
463 bool isAllNull = true;
464 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
465 if (!CE->getOperand(i)->isNullValue()) {
466 isAllNull = false;
467 break;
468 }
469 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000470 // This is casting one pointer type to another, always BitCast
Owen Anderson487375e2009-07-29 18:55:55 +0000471 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000472 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000473 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000474
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000475 // If the cast operand is a constant vector, perform the cast by
476 // operating on each element. In the cast of bitcasts, the element
477 // count may be mismatched; don't attempt to handle that here.
Nick Lewyckye0332982009-09-20 01:35:59 +0000478 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000479 if (isa<VectorType>(DestTy) &&
480 cast<VectorType>(DestTy)->getNumElements() ==
481 CV->getType()->getNumElements()) {
482 std::vector<Constant*> res;
483 const VectorType *DestVecTy = cast<VectorType>(DestTy);
484 const Type *DstEltTy = DestVecTy->getElementType();
485 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Owen Anderson487375e2009-07-29 18:55:55 +0000486 res.push_back(ConstantExpr::getCast(opc,
Owen Anderson0d2de8c2009-06-20 00:24:58 +0000487 CV->getOperand(i), DstEltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +0000488 return ConstantVector::get(DestVecTy, res);
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000489 }
490
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000491 // We actually have to do a cast now. Perform the cast according to the
492 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000493 switch (opc) {
Chris Lattnerf67d2972009-10-17 21:53:27 +0000494 default:
495 llvm_unreachable("Failed to cast constant expression");
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000496 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000497 case Instruction::FPExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000498 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000499 bool ignored;
Dale Johannesenf4bad972007-09-19 14:22:58 +0000500 APFloat Val = FPC->getValueAPF();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000501 Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
502 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
503 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
504 DestTy->isFP128Ty() ? APFloat::IEEEquad :
Dale Johannesenf4bad972007-09-19 14:22:58 +0000505 APFloat::Bogus,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000506 APFloat::rmNearestTiesToEven, &ignored);
Owen Anderson69c464d2009-07-27 20:59:43 +0000507 return ConstantFP::get(Context, Val);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000508 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000509 return 0; // Can't fold.
510 case Instruction::FPToUI:
Reid Spencer8dabca42006-12-19 07:41:40 +0000511 case Instruction::FPToSI:
Nick Lewyckye0332982009-09-20 01:35:59 +0000512 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Chris Lattner2b827fd2007-10-15 05:34:10 +0000513 const APFloat &V = FPC->getValueAPF();
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000514 bool ignored;
Dale Johannesenf4bad972007-09-19 14:22:58 +0000515 uint64_t x[2];
Reid Spencer81658a82007-02-27 06:23:51 +0000516 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesen17663f42007-09-25 23:32:20 +0000517 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000518 APFloat::rmTowardZero, &ignored);
Dale Johannesenf4bad972007-09-19 14:22:58 +0000519 APInt Val(DestBitWidth, 2, x);
Owen Andersonedb4a702009-07-24 23:12:02 +0000520 return ConstantInt::get(Context, Val);
Reid Spencer81658a82007-02-27 06:23:51 +0000521 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000522 return 0; // Can't fold.
523 case Instruction::IntToPtr: //always treated as unsigned
524 if (V->isNullValue()) // Is it an integral null value?
Owen Andersonb292b8c2009-07-30 23:03:37 +0000525 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000526 return 0; // Other pointer types cannot be casted
527 case Instruction::PtrToInt: // always treated as unsigned
Dan Gohmancf913832010-01-28 02:15:55 +0000528 // Is it a null pointer value?
529 if (V->isNullValue())
Owen Andersonedb4a702009-07-24 23:12:02 +0000530 return ConstantInt::get(DestTy, 0);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000531 // If this is a sizeof-like expression, pull out multiplications by
532 // known factors to expose them to subsequent folding. If it's an
533 // alignof-like expression, factor out known factors.
Dan Gohmancf913832010-01-28 02:15:55 +0000534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
535 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000536 CE->getOperand(0)->isNullValue()) {
537 const Type *Ty =
538 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
539 if (CE->getNumOperands() == 2) {
540 // Handle a sizeof-like expression.
541 Constant *Idx = CE->getOperand(1);
542 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
543 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
544 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
Dan Gohmancf913832010-01-28 02:15:55 +0000545 DestTy, false),
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000546 Idx, DestTy);
547 return ConstantExpr::getMul(C, Idx);
Dan Gohmancf913832010-01-28 02:15:55 +0000548 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000549 } else if (CE->getNumOperands() == 3 &&
550 CE->getOperand(1)->isNullValue()) {
551 // Handle an alignof-like expression.
552 if (const StructType *STy = dyn_cast<StructType>(Ty))
553 if (!STy->isPacked()) {
554 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
555 if (CI->isOne() &&
556 STy->getNumElements() == 2 &&
557 STy->getElementType(0)->isInteger(1)) {
558 // The alignment of an array is equal to the alignment of the
559 // array element. Note that this is not always true for vectors.
560 if (const ArrayType *ATy =
561 dyn_cast<ArrayType>(STy->getElementType(1))) {
562 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
563 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
564 DestTy,
565 false),
566 C, DestTy);
567 return C;
568 }
569 // Packed structs always have an alignment of 1.
570 if (const StructType *InnerSTy =
571 dyn_cast<StructType>(STy->getElementType(1)))
572 if (InnerSTy->isPacked())
573 return ConstantInt::get(DestTy, 1);
574 }
575 }
576 // Handle an offsetof-like expression.
577 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)){
578 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
579 DestTy, false))
580 return C;
581 }
582 }
583 }
Dan Gohmancf913832010-01-28 02:15:55 +0000584 // Other pointer types cannot be casted
585 return 0;
Reid Spencer8dabca42006-12-19 07:41:40 +0000586 case Instruction::UIToFP:
Reid Spencer8dabca42006-12-19 07:41:40 +0000587 case Instruction::SIToFP:
Nick Lewyckye0332982009-09-20 01:35:59 +0000588 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Dale Johannesen91506522007-09-30 18:19:03 +0000589 APInt api = CI->getValue();
590 const uint64_t zero[] = {0, 0};
Dale Johannesen91506522007-09-30 18:19:03 +0000591 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
592 2, zero));
Dan Gohman06c45d52008-02-29 01:42:52 +0000593 (void)apf.convertFromAPInt(api,
594 opc==Instruction::SIToFP,
595 APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +0000596 return ConstantFP::get(Context, apf);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000597 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000598 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000599 case Instruction::ZExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000600 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000601 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
602 APInt Result(CI->getValue());
603 Result.zext(BitWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +0000604 return ConstantInt::get(Context, Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000605 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000606 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000607 case Instruction::SExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000608 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000609 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
610 APInt Result(CI->getValue());
611 Result.sext(BitWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +0000612 return ConstantInt::get(Context, Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000613 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000614 return 0;
Chris Lattnerf67d2972009-10-17 21:53:27 +0000615 case Instruction::Trunc: {
616 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Nick Lewyckye0332982009-09-20 01:35:59 +0000617 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000618 APInt Result(CI->getValue());
Chris Lattnerf67d2972009-10-17 21:53:27 +0000619 Result.trunc(DestBitWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +0000620 return ConstantInt::get(Context, Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000621 }
Chris Lattnerf67d2972009-10-17 21:53:27 +0000622
623 // The input must be a constantexpr. See if we can simplify this based on
624 // the bytes we are demanding. Only do this if the source and dest are an
625 // even multiple of a byte.
626 if ((DestBitWidth & 7) == 0 &&
627 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
628 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
629 return Res;
630
Chris Lattner710ebaf2006-12-01 19:22:41 +0000631 return 0;
Chris Lattnerf67d2972009-10-17 21:53:27 +0000632 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000633 case Instruction::BitCast:
Nick Lewyckye0332982009-09-20 01:35:59 +0000634 return FoldBitCast(Context, V, DestTy);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000635 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000636}
637
Owen Anderson53a52212009-07-13 04:09:18 +0000638Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
Nick Lewyckye0332982009-09-20 01:35:59 +0000639 Constant *Cond,
640 Constant *V1, Constant *V2) {
641 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
642 return CB->getZExtValue() ? V1 : V2;
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000643
Nick Lewyckye0332982009-09-20 01:35:59 +0000644 if (isa<UndefValue>(V1)) return V2;
645 if (isa<UndefValue>(V2)) return V1;
646 if (isa<UndefValue>(Cond)) return V1;
647 if (V1 == V2) return V1;
Chris Lattner6ea4b522004-03-12 05:53:32 +0000648 return 0;
649}
650
Owen Anderson53a52212009-07-13 04:09:18 +0000651Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000652 Constant *Val,
653 Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000654 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
Owen Andersonb292b8c2009-07-30 23:03:37 +0000655 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000656 if (Val->isNullValue()) // ee(zero, x) -> zero
Owen Anderson5a1acd92009-07-31 20:28:14 +0000657 return Constant::getNullValue(
Reid Spencerd84d35b2007-02-15 02:26:10 +0000658 cast<VectorType>(Val->getType())->getElementType());
Dan Gohman062d3782009-08-29 23:35:16 +0000659
Nick Lewyckye0332982009-09-20 01:35:59 +0000660 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
661 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
Gabor Greiff6caff662008-05-10 08:32:32 +0000662 return CVal->getOperand(CIdx->getZExtValue());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000663 } else if (isa<UndefValue>(Idx)) {
664 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
Gabor Greiff6caff662008-05-10 08:32:32 +0000665 return CVal->getOperand(0);
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000666 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000667 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000668 return 0;
669}
670
Owen Anderson53a52212009-07-13 04:09:18 +0000671Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000672 Constant *Val,
673 Constant *Elt,
674 Constant *Idx) {
675 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000676 if (!CIdx) return 0;
Reid Spencer81658a82007-02-27 06:23:51 +0000677 APInt idxVal = CIdx->getValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000678 if (isa<UndefValue>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000679 // Insertion of scalar constant into vector undef
Robert Bocchinoca27f032006-01-17 20:07:22 +0000680 // Optimize away insertion of undef
681 if (isa<UndefValue>(Elt))
Nick Lewyckye0332982009-09-20 01:35:59 +0000682 return Val;
Robert Bocchinoca27f032006-01-17 20:07:22 +0000683 // Otherwise break the aggregate undef into multiple undefs and do
684 // the insertion
685 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000686 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000687 std::vector<Constant*> Ops;
688 Ops.reserve(numOps);
689 for (unsigned i = 0; i < numOps; ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000690 Constant *Op =
Owen Andersonb292b8c2009-07-30 23:03:37 +0000691 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000692 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000693 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000694 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000695 }
Reid Spencer3054b142006-11-02 08:18:15 +0000696 if (isa<ConstantAggregateZero>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000697 // Insertion of scalar constant into vector aggregate zero
Robert Bocchinoca27f032006-01-17 20:07:22 +0000698 // Optimize away insertion of zero
699 if (Elt->isNullValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000700 return Val;
Robert Bocchinoca27f032006-01-17 20:07:22 +0000701 // Otherwise break the aggregate zero into multiple zeros and do
702 // the insertion
703 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000704 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000705 std::vector<Constant*> Ops;
706 Ops.reserve(numOps);
707 for (unsigned i = 0; i < numOps; ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000708 Constant *Op =
Owen Anderson5a1acd92009-07-31 20:28:14 +0000709 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000710 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000711 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000712 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000713 }
Nick Lewyckye0332982009-09-20 01:35:59 +0000714 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000715 // Insertion of scalar constant into vector constant
Robert Bocchinoca27f032006-01-17 20:07:22 +0000716 std::vector<Constant*> Ops;
717 Ops.reserve(CVal->getNumOperands());
718 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000719 Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000720 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
Nick Lewyckye0332982009-09-20 01:35:59 +0000721 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000722 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000723 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000724 }
Dan Gohman3db11c22008-06-03 00:15:20 +0000725
Robert Bocchinoca27f032006-01-17 20:07:22 +0000726 return 0;
727}
728
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000729/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
730/// return the specified element value. Otherwise return null.
Nick Lewyckye0332982009-09-20 01:35:59 +0000731static Constant *GetVectorElement(LLVMContext &Context, Constant *C,
Owen Anderson53a52212009-07-13 04:09:18 +0000732 unsigned EltNo) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000733 if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
Gabor Greiff6caff662008-05-10 08:32:32 +0000734 return CV->getOperand(EltNo);
Dan Gohman062d3782009-08-29 23:35:16 +0000735
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000736 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
737 if (isa<ConstantAggregateZero>(C))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000738 return Constant::getNullValue(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000739 if (isa<UndefValue>(C))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000740 return UndefValue::get(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000741 return 0;
742}
743
Owen Anderson53a52212009-07-13 04:09:18 +0000744Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000745 Constant *V1,
746 Constant *V2,
747 Constant *Mask) {
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000748 // Undefined shuffle mask -> undefined value.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000749 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
Mon P Wang25f01062008-11-10 04:46:22 +0000750
751 unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
752 unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000753 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
Mon P Wang25f01062008-11-10 04:46:22 +0000754
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000755 // Loop over the shuffle mask, evaluating each element.
756 SmallVector<Constant*, 32> Result;
Mon P Wang25f01062008-11-10 04:46:22 +0000757 for (unsigned i = 0; i != MaskNumElts; ++i) {
Owen Anderson53a52212009-07-13 04:09:18 +0000758 Constant *InElt = GetVectorElement(Context, Mask, i);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000759 if (InElt == 0) return 0;
Mon P Wang25f01062008-11-10 04:46:22 +0000760
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000761 if (isa<UndefValue>(InElt))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000762 InElt = UndefValue::get(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000763 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
764 unsigned Elt = CI->getZExtValue();
Mon P Wang25f01062008-11-10 04:46:22 +0000765 if (Elt >= SrcNumElts*2)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000766 InElt = UndefValue::get(EltTy);
Mon P Wang25f01062008-11-10 04:46:22 +0000767 else if (Elt >= SrcNumElts)
Owen Anderson53a52212009-07-13 04:09:18 +0000768 InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000769 else
Owen Anderson53a52212009-07-13 04:09:18 +0000770 InElt = GetVectorElement(Context, V1, Elt);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000771 if (InElt == 0) return 0;
772 } else {
773 // Unknown value.
774 return 0;
775 }
776 Result.push_back(InElt);
777 }
Mon P Wang25f01062008-11-10 04:46:22 +0000778
Owen Anderson4aa32952009-07-28 21:19:26 +0000779 return ConstantVector::get(&Result[0], Result.size());
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000780}
781
Owen Anderson53a52212009-07-13 04:09:18 +0000782Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000783 Constant *Agg,
Dan Gohman3db11c22008-06-03 00:15:20 +0000784 const unsigned *Idxs,
785 unsigned NumIdx) {
786 // Base case: no indices, so return the entire value.
787 if (NumIdx == 0)
Nick Lewyckye0332982009-09-20 01:35:59 +0000788 return Agg;
Dan Gohman3db11c22008-06-03 00:15:20 +0000789
790 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
Owen Andersonb292b8c2009-07-30 23:03:37 +0000791 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
Dan Gohman3db11c22008-06-03 00:15:20 +0000792 Idxs,
793 Idxs + NumIdx));
794
795 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
796 return
Owen Anderson5a1acd92009-07-31 20:28:14 +0000797 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
Dan Gohman3db11c22008-06-03 00:15:20 +0000798 Idxs,
799 Idxs + NumIdx));
800
801 // Otherwise recurse.
Chris Lattnera91a5632009-10-28 05:14:34 +0000802 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
803 return ConstantFoldExtractValueInstruction(Context, CS->getOperand(*Idxs),
804 Idxs+1, NumIdx-1);
805
806 if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
807 return ConstantFoldExtractValueInstruction(Context, CA->getOperand(*Idxs),
808 Idxs+1, NumIdx-1);
809 ConstantVector *CV = cast<ConstantVector>(Agg);
810 return ConstantFoldExtractValueInstruction(Context, CV->getOperand(*Idxs),
Dan Gohman3db11c22008-06-03 00:15:20 +0000811 Idxs+1, NumIdx-1);
Dan Gohman12fce772008-05-15 19:50:34 +0000812}
813
Owen Anderson53a52212009-07-13 04:09:18 +0000814Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000815 Constant *Agg,
816 Constant *Val,
Dan Gohman3db11c22008-06-03 00:15:20 +0000817 const unsigned *Idxs,
818 unsigned NumIdx) {
819 // Base case: no indices, so replace the entire value.
820 if (NumIdx == 0)
Nick Lewyckye0332982009-09-20 01:35:59 +0000821 return Val;
Dan Gohman3db11c22008-06-03 00:15:20 +0000822
823 if (isa<UndefValue>(Agg)) {
824 // Insertion of constant into aggregate undef
Chris Lattneree8f74f2009-09-15 06:28:12 +0000825 // Optimize away insertion of undef.
Dan Gohman3db11c22008-06-03 00:15:20 +0000826 if (isa<UndefValue>(Val))
Nick Lewyckye0332982009-09-20 01:35:59 +0000827 return Agg;
Chris Lattneree8f74f2009-09-15 06:28:12 +0000828
Dan Gohman3db11c22008-06-03 00:15:20 +0000829 // Otherwise break the aggregate undef into multiple undefs and do
Chris Lattneree8f74f2009-09-15 06:28:12 +0000830 // the insertion.
Dan Gohman3db11c22008-06-03 00:15:20 +0000831 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
832 unsigned numOps;
833 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
834 numOps = AR->getNumElements();
835 else
836 numOps = cast<StructType>(AggTy)->getNumElements();
Chris Lattneree8f74f2009-09-15 06:28:12 +0000837
Dan Gohman3db11c22008-06-03 00:15:20 +0000838 std::vector<Constant*> Ops(numOps);
839 for (unsigned i = 0; i < numOps; ++i) {
840 const Type *MemberTy = AggTy->getTypeAtIndex(i);
Nick Lewyckye0332982009-09-20 01:35:59 +0000841 Constant *Op =
Dan Gohman3db11c22008-06-03 00:15:20 +0000842 (*Idxs == i) ?
Owen Andersonb292b8c2009-07-30 23:03:37 +0000843 ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
Dan Gohman3db11c22008-06-03 00:15:20 +0000844 Val, Idxs+1, NumIdx-1) :
Owen Andersonb292b8c2009-07-30 23:03:37 +0000845 UndefValue::get(MemberTy);
Nick Lewyckye0332982009-09-20 01:35:59 +0000846 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000847 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000848
849 if (const StructType* ST = dyn_cast<StructType>(AggTy))
850 return ConstantStruct::get(Context, Ops, ST->isPacked());
851 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000852 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000853
Dan Gohman3db11c22008-06-03 00:15:20 +0000854 if (isa<ConstantAggregateZero>(Agg)) {
855 // Insertion of constant into aggregate zero
Chris Lattneree8f74f2009-09-15 06:28:12 +0000856 // Optimize away insertion of zero.
Dan Gohman3db11c22008-06-03 00:15:20 +0000857 if (Val->isNullValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000858 return Agg;
Chris Lattneree8f74f2009-09-15 06:28:12 +0000859
Dan Gohman3db11c22008-06-03 00:15:20 +0000860 // Otherwise break the aggregate zero into multiple zeros and do
Chris Lattneree8f74f2009-09-15 06:28:12 +0000861 // the insertion.
Dan Gohman3db11c22008-06-03 00:15:20 +0000862 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
863 unsigned numOps;
864 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
865 numOps = AR->getNumElements();
866 else
867 numOps = cast<StructType>(AggTy)->getNumElements();
Chris Lattneree8f74f2009-09-15 06:28:12 +0000868
Dan Gohman3db11c22008-06-03 00:15:20 +0000869 std::vector<Constant*> Ops(numOps);
870 for (unsigned i = 0; i < numOps; ++i) {
871 const Type *MemberTy = AggTy->getTypeAtIndex(i);
Nick Lewyckye0332982009-09-20 01:35:59 +0000872 Constant *Op =
Dan Gohman3db11c22008-06-03 00:15:20 +0000873 (*Idxs == i) ?
Owen Anderson53a52212009-07-13 04:09:18 +0000874 ConstantFoldInsertValueInstruction(Context,
Owen Anderson5a1acd92009-07-31 20:28:14 +0000875 Constant::getNullValue(MemberTy),
Dan Gohman3db11c22008-06-03 00:15:20 +0000876 Val, Idxs+1, NumIdx-1) :
Owen Anderson5a1acd92009-07-31 20:28:14 +0000877 Constant::getNullValue(MemberTy);
Nick Lewyckye0332982009-09-20 01:35:59 +0000878 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000879 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000880
881 if (const StructType* ST = dyn_cast<StructType>(AggTy))
882 return ConstantStruct::get(Context, Ops, ST->isPacked());
883 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000884 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000885
Dan Gohman3db11c22008-06-03 00:15:20 +0000886 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
Chris Lattneree8f74f2009-09-15 06:28:12 +0000887 // Insertion of constant into aggregate constant.
Dan Gohman3db11c22008-06-03 00:15:20 +0000888 std::vector<Constant*> Ops(Agg->getNumOperands());
889 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
Chris Lattnera91a5632009-10-28 05:14:34 +0000890 Constant *Op = cast<Constant>(Agg->getOperand(i));
891 if (*Idxs == i)
892 Op = ConstantFoldInsertValueInstruction(Context, Op,
893 Val, Idxs+1, NumIdx-1);
Nick Lewyckye0332982009-09-20 01:35:59 +0000894 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000895 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000896
897 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
898 return ConstantStruct::get(Context, Ops, ST->isPacked());
899 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000900 }
901
Dan Gohman12fce772008-05-15 19:50:34 +0000902 return 0;
903}
904
Reid Spencer266e42b2006-12-23 06:05:41 +0000905
Owen Anderson53a52212009-07-13 04:09:18 +0000906Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
907 unsigned Opcode,
Nick Lewyckye0332982009-09-20 01:35:59 +0000908 Constant *C1, Constant *C2) {
Dale Johannesene5facd52007-10-16 23:38:29 +0000909 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +0000910 if (C1->getType()->isPPC_FP128Ty())
Dale Johannesene5facd52007-10-16 23:38:29 +0000911 return 0;
912
Chris Lattneree8f74f2009-09-15 06:28:12 +0000913 // Handle UndefValue up front.
Reid Spencer266e42b2006-12-23 06:05:41 +0000914 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
915 switch (Opcode) {
Evan Chengdf1690d2008-03-25 20:08:07 +0000916 case Instruction::Xor:
917 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
918 // Handle undef ^ undef -> 0 special case. This is a common
919 // idiom (misuse).
Owen Anderson5a1acd92009-07-31 20:28:14 +0000920 return Constant::getNullValue(C1->getType());
Evan Chengdf1690d2008-03-25 20:08:07 +0000921 // Fallthrough
Reid Spencer266e42b2006-12-23 06:05:41 +0000922 case Instruction::Add:
923 case Instruction::Sub:
Owen Andersonb292b8c2009-07-30 23:03:37 +0000924 return UndefValue::get(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000925 case Instruction::Mul:
926 case Instruction::And:
Owen Anderson5a1acd92009-07-31 20:28:14 +0000927 return Constant::getNullValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000928 case Instruction::UDiv:
929 case Instruction::SDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +0000930 case Instruction::URem:
931 case Instruction::SRem:
Reid Spencer266e42b2006-12-23 06:05:41 +0000932 if (!isa<UndefValue>(C2)) // undef / X -> 0
Owen Anderson5a1acd92009-07-31 20:28:14 +0000933 return Constant::getNullValue(C1->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000934 return C2; // X / undef -> undef
Reid Spencer266e42b2006-12-23 06:05:41 +0000935 case Instruction::Or: // X | undef -> -1
Reid Spencerd84d35b2007-02-15 02:26:10 +0000936 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000937 return Constant::getAllOnesValue(PTy);
938 return Constant::getAllOnesValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000939 case Instruction::LShr:
940 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000941 return C1; // undef lshr undef -> undef
Owen Anderson5a1acd92009-07-31 20:28:14 +0000942 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +0000943 // undef lshr X -> 0
944 case Instruction::AShr:
945 if (!isa<UndefValue>(C2))
Nick Lewyckye0332982009-09-20 01:35:59 +0000946 return C1; // undef ashr X --> undef
Reid Spencer266e42b2006-12-23 06:05:41 +0000947 else if (isa<UndefValue>(C1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000948 return C1; // undef ashr undef -> undef
Reid Spencer266e42b2006-12-23 06:05:41 +0000949 else
Nick Lewyckye0332982009-09-20 01:35:59 +0000950 return C1; // X ashr undef --> X
Reid Spencer266e42b2006-12-23 06:05:41 +0000951 case Instruction::Shl:
952 // undef << X -> 0 or X << undef -> 0
Owen Anderson5a1acd92009-07-31 20:28:14 +0000953 return Constant::getNullValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000954 }
955 }
956
Nick Lewycky6b8320f2009-06-21 01:56:41 +0000957 // Handle simplifications when the RHS is a constant int.
Nick Lewyckye0332982009-09-20 01:35:59 +0000958 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Chris Lattner334d33c2008-04-19 21:58:19 +0000959 switch (Opcode) {
960 case Instruction::Add:
Nick Lewyckye0332982009-09-20 01:35:59 +0000961 if (CI2->equalsInt(0)) return C1; // X + 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000962 break;
963 case Instruction::Sub:
Nick Lewyckye0332982009-09-20 01:35:59 +0000964 if (CI2->equalsInt(0)) return C1; // X - 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000965 break;
966 case Instruction::Mul:
Nick Lewyckye0332982009-09-20 01:35:59 +0000967 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
Chris Lattner334d33c2008-04-19 21:58:19 +0000968 if (CI2->equalsInt(1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000969 return C1; // X * 1 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000970 break;
971 case Instruction::UDiv:
972 case Instruction::SDiv:
973 if (CI2->equalsInt(1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000974 return C1; // X / 1 == X
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000975 if (CI2->equalsInt(0))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000976 return UndefValue::get(CI2->getType()); // X / 0 == undef
Chris Lattner334d33c2008-04-19 21:58:19 +0000977 break;
978 case Instruction::URem:
979 case Instruction::SRem:
980 if (CI2->equalsInt(1))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000981 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000982 if (CI2->equalsInt(0))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000983 return UndefValue::get(CI2->getType()); // X % 0 == undef
Chris Lattner334d33c2008-04-19 21:58:19 +0000984 break;
985 case Instruction::And:
Nick Lewyckye0332982009-09-20 01:35:59 +0000986 if (CI2->isZero()) return C2; // X & 0 == 0
Chris Lattner334d33c2008-04-19 21:58:19 +0000987 if (CI2->isAllOnesValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000988 return C1; // X & -1 == X
Dan Gohman062d3782009-08-29 23:35:16 +0000989
Nick Lewyckye0332982009-09-20 01:35:59 +0000990 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000991 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
Chris Lattner334d33c2008-04-19 21:58:19 +0000992 if (CE1->getOpcode() == Instruction::ZExt) {
993 unsigned DstWidth = CI2->getType()->getBitWidth();
994 unsigned SrcWidth =
995 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
996 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
997 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
Nick Lewyckye0332982009-09-20 01:35:59 +0000998 return C1;
Chris Lattner6d94bb72007-03-25 05:47:04 +0000999 }
Dan Gohman062d3782009-08-29 23:35:16 +00001000
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001001 // If and'ing the address of a global with a constant, fold it.
Chris Lattner334d33c2008-04-19 21:58:19 +00001002 if (CE1->getOpcode() == Instruction::PtrToInt &&
1003 isa<GlobalValue>(CE1->getOperand(0))) {
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001004 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
Dan Gohman062d3782009-08-29 23:35:16 +00001005
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001006 // Functions are at least 4-byte aligned.
1007 unsigned GVAlign = GV->getAlignment();
1008 if (isa<Function>(GV))
1009 GVAlign = std::max(GVAlign, 4U);
Dan Gohman062d3782009-08-29 23:35:16 +00001010
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001011 if (GVAlign > 1) {
1012 unsigned DstWidth = CI2->getType()->getBitWidth();
Chris Lattner912bec72008-04-20 19:59:12 +00001013 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001014 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1015
1016 // If checking bits we know are clear, return zero.
1017 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
Owen Anderson5a1acd92009-07-31 20:28:14 +00001018 return Constant::getNullValue(CI2->getType());
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001019 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001020 }
Chris Lattner334d33c2008-04-19 21:58:19 +00001021 }
1022 break;
1023 case Instruction::Or:
Nick Lewyckye0332982009-09-20 01:35:59 +00001024 if (CI2->equalsInt(0)) return C1; // X | 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +00001025 if (CI2->isAllOnesValue())
Nick Lewyckye0332982009-09-20 01:35:59 +00001026 return C2; // X | -1 == -1
Chris Lattner334d33c2008-04-19 21:58:19 +00001027 break;
1028 case Instruction::Xor:
Nick Lewyckye0332982009-09-20 01:35:59 +00001029 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
Nick Lewycky28260402009-09-20 06:24:51 +00001030
1031 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1032 switch (CE1->getOpcode()) {
1033 default: break;
1034 case Instruction::ICmp:
1035 case Instruction::FCmp:
Nick Lewyckyff550aa2009-09-20 06:27:35 +00001036 // cmp pred ^ true -> cmp !pred
Nick Lewycky28260402009-09-20 06:24:51 +00001037 assert(CI2->equalsInt(1));
Nick Lewycky0f8348e2009-09-20 06:26:34 +00001038 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
Nick Lewycky28260402009-09-20 06:24:51 +00001039 pred = CmpInst::getInversePredicate(pred);
1040 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1041 CE1->getOperand(1));
1042 }
1043 }
Chris Lattner334d33c2008-04-19 21:58:19 +00001044 break;
1045 case Instruction::AShr:
1046 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
Nick Lewyckye0332982009-09-20 01:35:59 +00001047 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
Chris Lattner6d94bb72007-03-25 05:47:04 +00001048 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
Nick Lewyckye0332982009-09-20 01:35:59 +00001049 return ConstantExpr::getLShr(C1, C2);
Chris Lattner334d33c2008-04-19 21:58:19 +00001050 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00001051 }
Chris Lattner334d33c2008-04-19 21:58:19 +00001052 }
Dan Gohman062d3782009-08-29 23:35:16 +00001053
Chris Lattner6b056052008-04-20 18:24:14 +00001054 // At this point we know neither constant is an UndefValue.
Nick Lewyckye0332982009-09-20 01:35:59 +00001055 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1056 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001057 using namespace APIntOps;
Chris Lattner6b056052008-04-20 18:24:14 +00001058 const APInt &C1V = CI1->getValue();
1059 const APInt &C2V = CI2->getValue();
Chris Lattner344da522007-01-12 18:42:52 +00001060 switch (Opcode) {
1061 default:
1062 break;
1063 case Instruction::Add:
Owen Andersonedb4a702009-07-24 23:12:02 +00001064 return ConstantInt::get(Context, C1V + C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001065 case Instruction::Sub:
Owen Andersonedb4a702009-07-24 23:12:02 +00001066 return ConstantInt::get(Context, C1V - C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001067 case Instruction::Mul:
Owen Andersonedb4a702009-07-24 23:12:02 +00001068 return ConstantInt::get(Context, C1V * C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001069 case Instruction::UDiv:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001070 assert(!CI2->isNullValue() && "Div by zero handled above");
Owen Andersonedb4a702009-07-24 23:12:02 +00001071 return ConstantInt::get(Context, C1V.udiv(C2V));
Chris Lattner344da522007-01-12 18:42:52 +00001072 case Instruction::SDiv:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001073 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer81658a82007-02-27 06:23:51 +00001074 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001075 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
Owen Andersonedb4a702009-07-24 23:12:02 +00001076 return ConstantInt::get(Context, C1V.sdiv(C2V));
Reid Spencer81658a82007-02-27 06:23:51 +00001077 case Instruction::URem:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001078 assert(!CI2->isNullValue() && "Div by zero handled above");
Owen Andersonedb4a702009-07-24 23:12:02 +00001079 return ConstantInt::get(Context, C1V.urem(C2V));
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001080 case Instruction::SRem:
1081 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer81658a82007-02-27 06:23:51 +00001082 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001083 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
Owen Andersonedb4a702009-07-24 23:12:02 +00001084 return ConstantInt::get(Context, C1V.srem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +00001085 case Instruction::And:
Owen Andersonedb4a702009-07-24 23:12:02 +00001086 return ConstantInt::get(Context, C1V & C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001087 case Instruction::Or:
Owen Andersonedb4a702009-07-24 23:12:02 +00001088 return ConstantInt::get(Context, C1V | C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001089 case Instruction::Xor:
Owen Andersonedb4a702009-07-24 23:12:02 +00001090 return ConstantInt::get(Context, C1V ^ C2V);
Chris Lattner6b056052008-04-20 18:24:14 +00001091 case Instruction::Shl: {
1092 uint32_t shiftAmt = C2V.getZExtValue();
1093 if (shiftAmt < C1V.getBitWidth())
Owen Andersonedb4a702009-07-24 23:12:02 +00001094 return ConstantInt::get(Context, C1V.shl(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +00001095 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001096 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +00001097 }
1098 case Instruction::LShr: {
1099 uint32_t shiftAmt = C2V.getZExtValue();
1100 if (shiftAmt < C1V.getBitWidth())
Owen Andersonedb4a702009-07-24 23:12:02 +00001101 return ConstantInt::get(Context, C1V.lshr(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +00001102 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001103 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +00001104 }
1105 case Instruction::AShr: {
1106 uint32_t shiftAmt = C2V.getZExtValue();
1107 if (shiftAmt < C1V.getBitWidth())
Owen Andersonedb4a702009-07-24 23:12:02 +00001108 return ConstantInt::get(Context, C1V.ashr(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +00001109 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001110 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +00001111 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001112 }
1113 }
Nick Lewycky6b8320f2009-06-21 01:56:41 +00001114
1115 switch (Opcode) {
1116 case Instruction::SDiv:
1117 case Instruction::UDiv:
1118 case Instruction::URem:
1119 case Instruction::SRem:
1120 case Instruction::LShr:
1121 case Instruction::AShr:
1122 case Instruction::Shl:
Nick Lewyckye0332982009-09-20 01:35:59 +00001123 if (CI1->equalsInt(0)) return C1;
Nick Lewycky6b8320f2009-06-21 01:56:41 +00001124 break;
1125 default:
1126 break;
1127 }
Nick Lewyckye0332982009-09-20 01:35:59 +00001128 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1129 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001130 APFloat C1V = CFP1->getValueAPF();
1131 APFloat C2V = CFP2->getValueAPF();
1132 APFloat C3V = C1V; // copy for modification
Reid Spencer266e42b2006-12-23 06:05:41 +00001133 switch (Opcode) {
1134 default:
1135 break;
Dan Gohmana5b96452009-06-04 22:49:04 +00001136 case Instruction::FAdd:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001137 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001138 return ConstantFP::get(Context, C3V);
Dan Gohmana5b96452009-06-04 22:49:04 +00001139 case Instruction::FSub:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001140 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001141 return ConstantFP::get(Context, C3V);
Dan Gohmana5b96452009-06-04 22:49:04 +00001142 case Instruction::FMul:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001143 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001144 return ConstantFP::get(Context, C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001145 case Instruction::FDiv:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001146 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001147 return ConstantFP::get(Context, C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001148 case Instruction::FRem:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001149 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001150 return ConstantFP::get(Context, C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001151 }
1152 }
Dan Gohman9f396602007-10-30 19:00:49 +00001153 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
Nick Lewyckye0332982009-09-20 01:35:59 +00001154 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1155 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
Dan Gohmanb43e0202007-10-31 21:36:31 +00001156 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1157 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
Owen Anderson85f86dc2009-07-13 22:41:06 +00001158 std::vector<Constant*> Res;
1159 const Type* EltTy = VTy->getElementType();
Nick Lewyckye0332982009-09-20 01:35:59 +00001160 Constant *C1 = 0;
1161 Constant *C2 = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00001162 switch (Opcode) {
Chris Lattner6072ead2008-04-19 21:13:00 +00001163 default:
1164 break;
Dan Gohmana5b96452009-06-04 22:49:04 +00001165 case Instruction::Add:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001166 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001167 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1168 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001169 Res.push_back(ConstantExpr::getAdd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001170 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001171 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001172 case Instruction::FAdd:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001173 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001174 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1175 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001176 Res.push_back(ConstantExpr::getFAdd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001177 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001178 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001179 case Instruction::Sub:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001180 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001181 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1182 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001183 Res.push_back(ConstantExpr::getSub(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001184 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001185 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001186 case Instruction::FSub:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001187 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001188 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1189 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001190 Res.push_back(ConstantExpr::getFSub(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001191 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001192 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001193 case Instruction::Mul:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001194 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001195 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1196 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001197 Res.push_back(ConstantExpr::getMul(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001198 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001199 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001200 case Instruction::FMul:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001201 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001202 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1203 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001204 Res.push_back(ConstantExpr::getFMul(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001205 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001206 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001207 case Instruction::UDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001208 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001209 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1210 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001211 Res.push_back(ConstantExpr::getUDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001212 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001213 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001214 case Instruction::SDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001215 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001216 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1217 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001218 Res.push_back(ConstantExpr::getSDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001219 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001220 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001221 case Instruction::FDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001222 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001223 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1224 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001225 Res.push_back(ConstantExpr::getFDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001226 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001227 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001228 case Instruction::URem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001229 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001230 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1231 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001232 Res.push_back(ConstantExpr::getURem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001233 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001234 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001235 case Instruction::SRem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001236 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001237 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1238 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001239 Res.push_back(ConstantExpr::getSRem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001240 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001241 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001242 case Instruction::FRem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001243 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001244 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1245 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001246 Res.push_back(ConstantExpr::getFRem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001247 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001248 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001249 case Instruction::And:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001250 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001251 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1252 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001253 Res.push_back(ConstantExpr::getAnd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001254 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001255 return ConstantVector::get(Res);
Owen Anderson85f86dc2009-07-13 22:41:06 +00001256 case Instruction::Or:
1257 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001258 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1259 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001260 Res.push_back(ConstantExpr::getOr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001261 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001262 return ConstantVector::get(Res);
Owen Anderson85f86dc2009-07-13 22:41:06 +00001263 case Instruction::Xor:
1264 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001265 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1266 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001267 Res.push_back(ConstantExpr::getXor(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001268 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001269 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001270 case Instruction::LShr:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001271 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001272 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1273 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001274 Res.push_back(ConstantExpr::getLShr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001275 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001276 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001277 case Instruction::AShr:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001278 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001279 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1280 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001281 Res.push_back(ConstantExpr::getAShr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001282 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001283 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001284 case Instruction::Shl:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001285 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001286 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1287 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001288 Res.push_back(ConstantExpr::getShl(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001289 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001290 return ConstantVector::get(Res);
Dan Gohmanb43e0202007-10-31 21:36:31 +00001291 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001292 }
1293 }
1294
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001295 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattner6b056052008-04-20 18:24:14 +00001296 // There are many possible foldings we could do here. We should probably
1297 // at least fold add of a pointer with an integer into the appropriate
1298 // getelementptr. This will improve alias analysis a bit.
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001299
1300 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1301 // (a + (b + c)).
1302 if (Instruction::isAssociative(Opcode, C1->getType()) &&
1303 CE1->getOpcode() == Opcode) {
1304 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1305 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1306 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1307 }
Chris Lattner6b056052008-04-20 18:24:14 +00001308 } else if (isa<ConstantExpr>(C2)) {
1309 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1310 // other way if possible.
1311 switch (Opcode) {
1312 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +00001313 case Instruction::FAdd:
Chris Lattner6b056052008-04-20 18:24:14 +00001314 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00001315 case Instruction::FMul:
Chris Lattner6b056052008-04-20 18:24:14 +00001316 case Instruction::And:
1317 case Instruction::Or:
1318 case Instruction::Xor:
1319 // No change of opcode required.
Owen Anderson53a52212009-07-13 04:09:18 +00001320 return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
Dan Gohman062d3782009-08-29 23:35:16 +00001321
Chris Lattner6b056052008-04-20 18:24:14 +00001322 case Instruction::Shl:
1323 case Instruction::LShr:
1324 case Instruction::AShr:
1325 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001326 case Instruction::FSub:
Chris Lattner6b056052008-04-20 18:24:14 +00001327 case Instruction::SDiv:
1328 case Instruction::UDiv:
1329 case Instruction::FDiv:
1330 case Instruction::URem:
1331 case Instruction::SRem:
1332 case Instruction::FRem:
1333 default: // These instructions cannot be flopped around.
1334 break;
1335 }
1336 }
Dan Gohman062d3782009-08-29 23:35:16 +00001337
Nick Lewycky605109d2009-09-20 00:04:02 +00001338 // i1 can be simplified in many cases.
Benjamin Kramera81a6df2010-01-05 20:07:06 +00001339 if (C1->getType()->isInteger(1)) {
Nick Lewycky605109d2009-09-20 00:04:02 +00001340 switch (Opcode) {
1341 case Instruction::Add:
1342 case Instruction::Sub:
Nick Lewyckye0332982009-09-20 01:35:59 +00001343 return ConstantExpr::getXor(C1, C2);
Nick Lewycky605109d2009-09-20 00:04:02 +00001344 case Instruction::Mul:
Nick Lewyckye0332982009-09-20 01:35:59 +00001345 return ConstantExpr::getAnd(C1, C2);
Nick Lewycky605109d2009-09-20 00:04:02 +00001346 case Instruction::Shl:
1347 case Instruction::LShr:
1348 case Instruction::AShr:
1349 // We can assume that C2 == 0. If it were one the result would be
1350 // undefined because the shift value is as large as the bitwidth.
Nick Lewyckye0332982009-09-20 01:35:59 +00001351 return C1;
Nick Lewycky605109d2009-09-20 00:04:02 +00001352 case Instruction::SDiv:
1353 case Instruction::UDiv:
1354 // We can assume that C2 == 1. If it were zero the result would be
1355 // undefined through division by zero.
Nick Lewyckye0332982009-09-20 01:35:59 +00001356 return C1;
Nick Lewycky605109d2009-09-20 00:04:02 +00001357 case Instruction::URem:
1358 case Instruction::SRem:
1359 // We can assume that C2 == 1. If it were zero the result would be
1360 // undefined through division by zero.
1361 return ConstantInt::getFalse(Context);
1362 default:
1363 break;
1364 }
1365 }
1366
Chris Lattner6b056052008-04-20 18:24:14 +00001367 // We don't know how to fold this.
Reid Spencer266e42b2006-12-23 06:05:41 +00001368 return 0;
1369}
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001370
Chris Lattner60c47262005-01-28 19:09:51 +00001371/// isZeroSizedType - This type is zero sized if its an array or structure of
1372/// zero sized types. The only leaf zero sized type is an empty structure.
1373static bool isMaybeZeroSizedType(const Type *Ty) {
1374 if (isa<OpaqueType>(Ty)) return true; // Can't say.
1375 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1376
1377 // If all of elements have zero size, this does too.
1378 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +00001379 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +00001380 return true;
1381
1382 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1383 return isMaybeZeroSizedType(ATy->getElementType());
1384 }
1385 return false;
1386}
Chris Lattner6ea4b522004-03-12 05:53:32 +00001387
Chris Lattner061da2f2004-01-13 05:51:55 +00001388/// IdxCompare - Compare the two constants as though they were getelementptr
1389/// indices. This allows coersion of the types to be the same thing.
1390///
1391/// If the two constants are the "same" (after coersion), return 0. If the
1392/// first is less than the second, return -1, if the second is less than the
1393/// first, return 1. If the constants are not integral, return -2.
1394///
Owen Anderson53a52212009-07-13 04:09:18 +00001395static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2,
1396 const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001397 if (C1 == C2) return 0;
1398
Reid Spencerc90cf772006-12-31 21:43:30 +00001399 // Ok, we found a different index. If they are not ConstantInt, we can't do
1400 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +00001401 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1402 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001403
Chris Lattner69193f92004-04-05 01:30:19 +00001404 // Ok, we have two differing integer indices. Sign extend them to be the same
1405 // type. Long is always big enough, so we use it.
Benjamin Kramerd2564e32010-01-05 21:05:54 +00001406 if (!C1->getType()->isInteger(64))
Owen Anderson55f1c092009-08-13 21:58:54 +00001407 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001408
Benjamin Kramerd2564e32010-01-05 21:05:54 +00001409 if (!C2->getType()->isInteger(64))
Owen Anderson55f1c092009-08-13 21:58:54 +00001410 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
Reid Spencer8d9336d2006-12-31 05:26:44 +00001411
1412 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +00001413
Chris Lattner60c47262005-01-28 19:09:51 +00001414 // If the type being indexed over is really just a zero sized type, there is
1415 // no pointer difference being made here.
1416 if (isMaybeZeroSizedType(ElTy))
1417 return -2; // dunno.
1418
Chris Lattner061da2f2004-01-13 05:51:55 +00001419 // If they are really different, now that they are the same type, then we
1420 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +00001421 if (cast<ConstantInt>(C1)->getSExtValue() <
1422 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +00001423 return -1;
1424 else
1425 return 1;
1426}
1427
Chris Lattner858f4e92007-01-04 02:13:20 +00001428/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencer266e42b2006-12-23 06:05:41 +00001429/// decide about the two constants provided. This doesn't need to handle simple
1430/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1431/// If we can determine that the two constants have a particular relation to
1432/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001433/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1434/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001435///
1436/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +00001437/// operand is always the most "complex" of the two. We consider ConstantFP
1438/// to be the simplest, and ConstantExprs to be the most complex.
Owen Anderson53a52212009-07-13 04:09:18 +00001439static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +00001440 Constant *V1, Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001441 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +00001442 "Cannot compare values of different types!");
Dale Johannesen19db0932007-10-14 01:56:47 +00001443
1444 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001445 if (V1->getType()->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +00001446 return FCmpInst::BAD_FCMP_PREDICATE;
1447
Reid Spencer9d36acf2006-12-24 18:52:08 +00001448 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +00001449 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1450
Reid Spencer9d36acf2006-12-24 18:52:08 +00001451 if (!isa<ConstantExpr>(V1)) {
1452 if (!isa<ConstantExpr>(V2)) {
1453 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng75b871f2007-01-11 12:24:14 +00001454 ConstantInt *R = 0;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001455 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001456 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001457 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001458 return FCmpInst::FCMP_OEQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001459 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001460 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001461 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001462 return FCmpInst::FCMP_OLT;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001463 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001464 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001465 if (R && !R->isZero())
Reid Spencer9d36acf2006-12-24 18:52:08 +00001466 return FCmpInst::FCMP_OGT;
1467
1468 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +00001469 return FCmpInst::BAD_FCMP_PREDICATE;
1470 }
Dan Gohman062d3782009-08-29 23:35:16 +00001471
Reid Spencer9d36acf2006-12-24 18:52:08 +00001472 // If the first operand is simple and second is ConstantExpr, swap operands.
Owen Anderson53a52212009-07-13 04:09:18 +00001473 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001474 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1475 return FCmpInst::getSwappedPredicate(SwappedRelation);
1476 } else {
1477 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1478 // constantexpr or a simple constant.
Nick Lewyckye0332982009-09-20 01:35:59 +00001479 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001480 switch (CE1->getOpcode()) {
1481 case Instruction::FPTrunc:
1482 case Instruction::FPExt:
1483 case Instruction::UIToFP:
1484 case Instruction::SIToFP:
1485 // We might be able to do something with these but we don't right now.
1486 break;
1487 default:
1488 break;
1489 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001490 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001491 // There are MANY other foldings that we could perform here. They will
1492 // probably be added on demand, as they seem needed.
1493 return FCmpInst::BAD_FCMP_PREDICATE;
1494}
1495
1496/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +00001497/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +00001498/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +00001499/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +00001500/// particular relation to each other, we should return the corresponding ICmp
1501/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +00001502///
1503/// To simplify this code we canonicalize the relation so that the first
1504/// operand is always the most "complex" of the two. We consider simple
1505/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +00001506/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +00001507///
Owen Anderson53a52212009-07-13 04:09:18 +00001508static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
Chris Lattner3c46e142010-02-01 19:35:08 +00001509 Constant *V1, Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +00001510 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001511 assert(V1->getType() == V2->getType() &&
1512 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001513 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001514
Chris Lattner3c46e142010-02-01 19:35:08 +00001515 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1516 !isa<BlockAddress>(V1)) {
1517 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1518 !isa<BlockAddress>(V2)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001519 // We distilled this down to a simple case, use the standard constant
1520 // folder.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001521 ConstantInt *R = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00001522 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Nick Lewyckye0332982009-09-20 01:35:59 +00001523 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001524 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001525 return pred;
1526 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Nick Lewyckye0332982009-09-20 01:35:59 +00001527 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001528 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001529 return pred;
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001530 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Nick Lewyckye0332982009-09-20 01:35:59 +00001531 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001532 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001533 return pred;
Dan Gohman062d3782009-08-29 23:35:16 +00001534
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001535 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +00001536 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001537 }
Dan Gohman062d3782009-08-29 23:35:16 +00001538
Chris Lattner061da2f2004-01-13 05:51:55 +00001539 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +00001540 ICmpInst::Predicate SwappedRelation =
Owen Anderson53a52212009-07-13 04:09:18 +00001541 evaluateICmpRelation(Context, V2, V1, isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001542 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1543 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +00001544
Chris Lattner3c46e142010-02-01 19:35:08 +00001545 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +00001546 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +00001547 ICmpInst::Predicate SwappedRelation =
Owen Anderson53a52212009-07-13 04:09:18 +00001548 evaluateICmpRelation(Context, V2, V1, isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001549 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1550 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner3c46e142010-02-01 19:35:08 +00001551 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +00001552 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001553
Chris Lattner3c46e142010-02-01 19:35:08 +00001554 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1555 // constant (which, since the types must match, means that it's a
1556 // ConstantPointerNull).
1557 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner52fe8692007-09-10 23:42:42 +00001558 // Don't try to decide equality of aliases.
Chris Lattner3c46e142010-02-01 19:35:08 +00001559 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1560 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
Chris Lattner52fe8692007-09-10 23:42:42 +00001561 return ICmpInst::ICMP_NE;
Chris Lattner3c46e142010-02-01 19:35:08 +00001562 } else if (isa<BlockAddress>(V2)) {
1563 return ICmpInst::ICMP_NE; // Globals never equal labels.
Chris Lattner061da2f2004-01-13 05:51:55 +00001564 } else {
1565 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Chris Lattner3c46e142010-02-01 19:35:08 +00001566 // GlobalVals can never be null unless they have external weak linkage.
1567 // We don't try to evaluate aliases here.
1568 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
Reid Spencer266e42b2006-12-23 06:05:41 +00001569 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001570 }
Chris Lattner3c46e142010-02-01 19:35:08 +00001571 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1572 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1573 ICmpInst::Predicate SwappedRelation =
1574 evaluateICmpRelation(Context, V2, V1, isSigned);
1575 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1576 return ICmpInst::getSwappedPredicate(SwappedRelation);
1577 return ICmpInst::BAD_ICMP_PREDICATE;
1578 }
1579
1580 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1581 // constant (which, since the types must match, means that it is a
1582 // ConstantPointerNull).
1583 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1584 // Block address in another function can't equal this one, but block
1585 // addresses in the current function might be the same if blocks are
1586 // empty.
1587 if (BA2->getFunction() != BA->getFunction())
1588 return ICmpInst::ICMP_NE;
1589 } else {
1590 // Block addresses aren't null, don't equal the address of globals.
1591 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1592 "Canonicalization guarantee!");
1593 return ICmpInst::ICMP_NE;
1594 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001595 } else {
1596 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
Chris Lattner3c46e142010-02-01 19:35:08 +00001597 // constantexpr, a global, block address, or a simple constant.
Nick Lewyckye0332982009-09-20 01:35:59 +00001598 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1599 Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +00001600
1601 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001602 case Instruction::Trunc:
1603 case Instruction::FPTrunc:
1604 case Instruction::FPExt:
1605 case Instruction::FPToUI:
1606 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +00001607 break; // We can't evaluate floating point casts or truncations.
1608
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001609 case Instruction::UIToFP:
1610 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001611 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +00001612 case Instruction::ZExt:
1613 case Instruction::SExt:
Chris Lattner061da2f2004-01-13 05:51:55 +00001614 // If the cast is not actually changing bits, and the second operand is a
1615 // null pointer, do the comparison with the pre-casted value.
1616 if (V2->isNullValue() &&
Chris Lattner03c49532007-01-15 02:27:26 +00001617 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001618 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1619 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
Owen Anderson53a52212009-07-13 04:09:18 +00001620 return evaluateICmpRelation(Context, CE1Op0,
Owen Anderson5a1acd92009-07-31 20:28:14 +00001621 Constant::getNullValue(CE1Op0->getType()),
Nick Lewycky2949a232009-09-20 03:48:46 +00001622 isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001623 }
Chris Lattner192e3262004-04-11 01:29:30 +00001624 break;
Chris Lattner061da2f2004-01-13 05:51:55 +00001625
1626 case Instruction::GetElementPtr:
1627 // Ok, since this is a getelementptr, we know that the constant has a
1628 // pointer type. Check the various cases.
1629 if (isa<ConstantPointerNull>(V2)) {
1630 // If we are comparing a GEP to a null pointer, check to see if the base
1631 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001632 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001633 if (GV->hasExternalWeakLinkage())
1634 // Weak linkage GVals could be zero or not. We're comparing that
1635 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001636 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +00001637 else
1638 // If its not weak linkage, the GVal must have a non-zero address
1639 // so the result is greater-than
Nick Lewycky9e085542009-09-20 04:27:06 +00001640 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001641 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1642 // If we are indexing from a null pointer, check to see if we have any
1643 // non-zero indices.
1644 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1645 if (!CE1->getOperand(i)->isNullValue())
1646 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001647 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001648 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00001649 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001650 }
1651 // Otherwise, we can't really say if the first operand is null or not.
Chris Lattner3c46e142010-02-01 19:35:08 +00001652 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001653 if (isa<ConstantPointerNull>(CE1Op0)) {
Chris Lattner3c46e142010-02-01 19:35:08 +00001654 if (GV2->hasExternalWeakLinkage())
Reid Spencer876f7222006-12-06 00:25:09 +00001655 // Weak linkage GVals could be zero or not. We're comparing it to
1656 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001657 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +00001658 else
1659 // If its not weak linkage, the GVal must have a non-zero address
1660 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001661 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner3c46e142010-02-01 19:35:08 +00001662 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1663 if (GV == GV2) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001664 // If this is a getelementptr of the same global, then it must be
1665 // different. Because the types must match, the getelementptr could
1666 // only have at most one index, and because we fold getelementptr's
1667 // with a single zero index, it must be nonzero.
1668 assert(CE1->getNumOperands() == 2 &&
1669 !CE1->getOperand(1)->isNullValue() &&
1670 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001671 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001672 } else {
1673 // If they are different globals, we don't know what the value is,
1674 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001675 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001676 }
1677 }
1678 } else {
Nick Lewyckye0332982009-09-20 01:35:59 +00001679 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1680 Constant *CE2Op0 = CE2->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +00001681
1682 // There are MANY other foldings that we could perform here. They will
1683 // probably be added on demand, as they seem needed.
1684 switch (CE2->getOpcode()) {
1685 default: break;
1686 case Instruction::GetElementPtr:
1687 // By far the most common case to handle is when the base pointers are
1688 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001689 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001690 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001691 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001692 // Ok, we know that both getelementptr instructions are based on the
1693 // same global. From this, we can precisely determine the relative
1694 // ordering of the resultant pointers.
1695 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001696
Dan Gohman7190d482009-09-10 23:37:55 +00001697 // The logic below assumes that the result of the comparison
1698 // can be determined by finding the first index that differs.
1699 // This doesn't work if there is over-indexing in any
1700 // subsequent indices, so check for that case first.
1701 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1702 !CE2->isGEPWithNoNotionalOverIndexing())
1703 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1704
Chris Lattner061da2f2004-01-13 05:51:55 +00001705 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +00001706 gep_type_iterator GTI = gep_type_begin(CE1);
1707 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1708 ++i, ++GTI)
Owen Anderson53a52212009-07-13 04:09:18 +00001709 switch (IdxCompare(Context, CE1->getOperand(i),
1710 CE2->getOperand(i), GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001711 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1712 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1713 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001714 }
1715
1716 // Ok, we ran out of things they have in common. If any leftovers
1717 // are non-zero then we have a difference, otherwise we are equal.
1718 for (; i < CE1->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001719 if (!CE1->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001720 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001721 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +00001722 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001723 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001724 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001725
Chris Lattner061da2f2004-01-13 05:51:55 +00001726 for (; i < CE2->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001727 if (!CE2->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001728 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001729 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001730 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001731 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001732 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001733 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001734 }
1735 }
1736 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001737 default:
1738 break;
1739 }
1740 }
1741
Reid Spencer266e42b2006-12-23 06:05:41 +00001742 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001743}
1744
Owen Anderson53a52212009-07-13 04:09:18 +00001745Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1746 unsigned short pred,
Nick Lewyckye0332982009-09-20 01:35:59 +00001747 Constant *C1, Constant *C2) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001748 const Type *ResultTy;
1749 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
Owen Anderson55f1c092009-08-13 21:58:54 +00001750 ResultTy = VectorType::get(Type::getInt1Ty(Context), VT->getNumElements());
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001751 else
Owen Anderson55f1c092009-08-13 21:58:54 +00001752 ResultTy = Type::getInt1Ty(Context);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001753
Chris Lattnerd137a082008-07-08 05:46:34 +00001754 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001755 if (pred == FCmpInst::FCMP_FALSE)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001756 return Constant::getNullValue(ResultTy);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001757
1758 if (pred == FCmpInst::FCMP_TRUE)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001759 return Constant::getAllOnesValue(ResultTy);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001760
Reid Spencer266e42b2006-12-23 06:05:41 +00001761 // Handle some degenerate cases first
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001762 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
Owen Andersonb292b8c2009-07-30 23:03:37 +00001763 return UndefValue::get(ResultTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00001764
Dale Johannesen19db0932007-10-14 01:56:47 +00001765 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001766 if (C1->getType()->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +00001767 return 0;
1768
Reid Spencer266e42b2006-12-23 06:05:41 +00001769 // icmp eq/ne(null,GV) -> false/true
1770 if (C1->isNullValue()) {
1771 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001772 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001773 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001774 if (pred == ICmpInst::ICMP_EQ)
Owen Anderson23a204d2009-07-31 17:39:07 +00001775 return ConstantInt::getFalse(Context);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001776 else if (pred == ICmpInst::ICMP_NE)
Owen Anderson23a204d2009-07-31 17:39:07 +00001777 return ConstantInt::getTrue(Context);
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001778 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001779 // icmp eq/ne(GV,null) -> false/true
1780 } else if (C2->isNullValue()) {
1781 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001782 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001783 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001784 if (pred == ICmpInst::ICMP_EQ)
Owen Anderson23a204d2009-07-31 17:39:07 +00001785 return ConstantInt::getFalse(Context);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001786 else if (pred == ICmpInst::ICMP_NE)
Owen Anderson23a204d2009-07-31 17:39:07 +00001787 return ConstantInt::getTrue(Context);
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001788 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001789 }
1790
Nick Lewyckyb0225ba2009-09-20 07:21:39 +00001791 // If the comparison is a comparison between two i1's, simplify it.
Benjamin Kramera81a6df2010-01-05 20:07:06 +00001792 if (C1->getType()->isInteger(1)) {
Nick Lewyckyb0225ba2009-09-20 07:21:39 +00001793 switch(pred) {
1794 case ICmpInst::ICMP_EQ:
1795 if (isa<ConstantInt>(C2))
1796 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1797 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1798 case ICmpInst::ICMP_NE:
1799 return ConstantExpr::getXor(C1, C2);
1800 default:
1801 break;
1802 }
1803 }
1804
Chris Lattner344da522007-01-12 18:42:52 +00001805 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001806 APInt V1 = cast<ConstantInt>(C1)->getValue();
1807 APInt V2 = cast<ConstantInt>(C2)->getValue();
1808 switch (pred) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001809 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
Owen Anderson53a52212009-07-13 04:09:18 +00001810 case ICmpInst::ICMP_EQ:
Owen Anderson55f1c092009-08-13 21:58:54 +00001811 return ConstantInt::get(Type::getInt1Ty(Context), V1 == V2);
Owen Anderson53a52212009-07-13 04:09:18 +00001812 case ICmpInst::ICMP_NE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001813 return ConstantInt::get(Type::getInt1Ty(Context), V1 != V2);
Owen Anderson53a52212009-07-13 04:09:18 +00001814 case ICmpInst::ICMP_SLT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001815 return ConstantInt::get(Type::getInt1Ty(Context), V1.slt(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001816 case ICmpInst::ICMP_SGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001817 return ConstantInt::get(Type::getInt1Ty(Context), V1.sgt(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001818 case ICmpInst::ICMP_SLE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001819 return ConstantInt::get(Type::getInt1Ty(Context), V1.sle(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001820 case ICmpInst::ICMP_SGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001821 return ConstantInt::get(Type::getInt1Ty(Context), V1.sge(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001822 case ICmpInst::ICMP_ULT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001823 return ConstantInt::get(Type::getInt1Ty(Context), V1.ult(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001824 case ICmpInst::ICMP_UGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001825 return ConstantInt::get(Type::getInt1Ty(Context), V1.ugt(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001826 case ICmpInst::ICMP_ULE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001827 return ConstantInt::get(Type::getInt1Ty(Context), V1.ule(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001828 case ICmpInst::ICMP_UGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001829 return ConstantInt::get(Type::getInt1Ty(Context), V1.uge(V2));
Chris Lattner061da2f2004-01-13 05:51:55 +00001830 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001831 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001832 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1833 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1834 APFloat::cmpResult R = C1V.compare(C2V);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001835 switch (pred) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001836 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
Owen Anderson23a204d2009-07-31 17:39:07 +00001837 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse(Context);
1838 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue(Context);
Reid Spencer266e42b2006-12-23 06:05:41 +00001839 case FCmpInst::FCMP_UNO:
Owen Anderson55f1c092009-08-13 21:58:54 +00001840 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered);
Reid Spencer74bd0362007-01-11 00:25:45 +00001841 case FCmpInst::FCMP_ORD:
Owen Anderson55f1c092009-08-13 21:58:54 +00001842 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpUnordered);
Reid Spencer266e42b2006-12-23 06:05:41 +00001843 case FCmpInst::FCMP_UEQ:
Owen Anderson55f1c092009-08-13 21:58:54 +00001844 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001845 R==APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001846 case FCmpInst::FCMP_OEQ:
Owen Anderson55f1c092009-08-13 21:58:54 +00001847 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpEqual);
Reid Spencer74bd0362007-01-11 00:25:45 +00001848 case FCmpInst::FCMP_UNE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001849 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001850 case FCmpInst::FCMP_ONE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001851 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001852 R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001853 case FCmpInst::FCMP_ULT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001854 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001855 R==APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001856 case FCmpInst::FCMP_OLT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001857 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan);
Reid Spencer266e42b2006-12-23 06:05:41 +00001858 case FCmpInst::FCMP_UGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001859 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001860 R==APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001861 case FCmpInst::FCMP_OGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001862 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001863 case FCmpInst::FCMP_ULE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001864 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001865 case FCmpInst::FCMP_OLE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001866 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001867 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001868 case FCmpInst::FCMP_UGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001869 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001870 case FCmpInst::FCMP_OGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001871 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001872 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001873 }
Chris Lattner67136cf2008-07-10 00:29:28 +00001874 } else if (isa<VectorType>(C1->getType())) {
1875 SmallVector<Constant*, 16> C1Elts, C2Elts;
Owen Anderson53a52212009-07-13 04:09:18 +00001876 C1->getVectorElements(Context, C1Elts);
1877 C2->getVectorElements(Context, C2Elts);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001878 if (C1Elts.empty() || C2Elts.empty())
1879 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +00001880
Chris Lattner67136cf2008-07-10 00:29:28 +00001881 // If we can constant fold the comparison of each element, constant fold
1882 // the whole vector comparison.
1883 SmallVector<Constant*, 4> ResElts;
Chris Lattner67136cf2008-07-10 00:29:28 +00001884 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1885 // Compare the elements, producing an i1 result or constant expr.
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001886 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
Reid Spencer266e42b2006-12-23 06:05:41 +00001887 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001888 return ConstantVector::get(&ResElts[0], ResElts.size());
Reid Spencer266e42b2006-12-23 06:05:41 +00001889 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001890
Reid Spencer9d36acf2006-12-24 18:52:08 +00001891 if (C1->getType()->isFloatingPoint()) {
Chris Lattner350e4172008-07-08 18:47:38 +00001892 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Owen Anderson53a52212009-07-13 04:09:18 +00001893 switch (evaluateFCmpRelation(Context, C1, C2)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001894 default: llvm_unreachable("Unknown relation!");
Reid Spencer9d36acf2006-12-24 18:52:08 +00001895 case FCmpInst::FCMP_UNO:
1896 case FCmpInst::FCMP_ORD:
1897 case FCmpInst::FCMP_UEQ:
1898 case FCmpInst::FCMP_UNE:
1899 case FCmpInst::FCMP_ULT:
1900 case FCmpInst::FCMP_UGT:
1901 case FCmpInst::FCMP_ULE:
1902 case FCmpInst::FCMP_UGE:
1903 case FCmpInst::FCMP_TRUE:
1904 case FCmpInst::FCMP_FALSE:
1905 case FCmpInst::BAD_FCMP_PREDICATE:
1906 break; // Couldn't determine anything about these constants.
1907 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001908 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1909 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1910 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1911 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001912 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001913 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1914 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1915 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1916 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001917 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001918 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1919 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1920 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1921 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001922 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1923 // We can only partially decide this relation.
1924 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Chris Lattnerd137a082008-07-08 05:46:34 +00001925 Result = 0;
1926 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1927 Result = 1;
Chris Lattner061da2f2004-01-13 05:51:55 +00001928 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001929 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1930 // We can only partially decide this relation.
1931 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Chris Lattnerd137a082008-07-08 05:46:34 +00001932 Result = 0;
1933 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1934 Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001935 break;
1936 case ICmpInst::ICMP_NE: // We know that C1 != C2
1937 // We can only partially decide this relation.
1938 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Chris Lattnerd137a082008-07-08 05:46:34 +00001939 Result = 0;
1940 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1941 Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001942 break;
1943 }
Dan Gohman062d3782009-08-29 23:35:16 +00001944
Chris Lattnerd137a082008-07-08 05:46:34 +00001945 // If we evaluated the result, return it now.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001946 if (Result != -1)
Owen Anderson55f1c092009-08-13 21:58:54 +00001947 return ConstantInt::get(Type::getInt1Ty(Context), Result);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001948
Reid Spencer9d36acf2006-12-24 18:52:08 +00001949 } else {
1950 // Evaluate the relation between the two constants, per the predicate.
Chris Lattnerd137a082008-07-08 05:46:34 +00001951 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Owen Anderson53a52212009-07-13 04:09:18 +00001952 switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001953 default: llvm_unreachable("Unknown relational!");
Reid Spencer9d36acf2006-12-24 18:52:08 +00001954 case ICmpInst::BAD_ICMP_PREDICATE:
1955 break; // Couldn't determine anything about these constants.
1956 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1957 // If we know the constants are equal, we can decide the result of this
1958 // computation precisely.
Nick Lewycky9e085542009-09-20 04:27:06 +00001959 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
Chris Lattnerd137a082008-07-08 05:46:34 +00001960 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001961 case ICmpInst::ICMP_ULT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001962 switch (pred) {
1963 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001964 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001965 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001966 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001967 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001968 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001969 case ICmpInst::ICMP_SLT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001970 switch (pred) {
1971 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001972 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001973 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001974 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001975 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001976 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001977 case ICmpInst::ICMP_UGT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001978 switch (pred) {
1979 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001980 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001981 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001982 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001983 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001984 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001985 case ICmpInst::ICMP_SGT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001986 switch (pred) {
1987 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001988 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001989 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001990 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001991 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001992 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001993 case ICmpInst::ICMP_ULE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001994 if (pred == ICmpInst::ICMP_UGT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00001995 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001996 break;
1997 case ICmpInst::ICMP_SLE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001998 if (pred == ICmpInst::ICMP_SGT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00001999 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002000 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002001 case ICmpInst::ICMP_UGE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002002 if (pred == ICmpInst::ICMP_ULT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00002003 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002004 break;
2005 case ICmpInst::ICMP_SGE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002006 if (pred == ICmpInst::ICMP_SLT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00002007 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002008 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002009 case ICmpInst::ICMP_NE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002010 if (pred == ICmpInst::ICMP_EQ) Result = 0;
2011 if (pred == ICmpInst::ICMP_NE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002012 break;
2013 }
Dan Gohman062d3782009-08-29 23:35:16 +00002014
Chris Lattnerd137a082008-07-08 05:46:34 +00002015 // If we evaluated the result, return it now.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002016 if (Result != -1)
Owen Anderson55f1c092009-08-13 21:58:54 +00002017 return ConstantInt::get(Type::getInt1Ty(Context), Result);
Dan Gohman062d3782009-08-29 23:35:16 +00002018
Nick Lewycky4a034522009-09-20 05:48:50 +00002019 // If the right hand side is a bitcast, try using its inverse to simplify
Chris Lattner94eb4b22010-02-01 20:04:40 +00002020 // it by moving it to the left hand side. We can't do this if it would turn
2021 // a vector compare into scalar compare of visa versa.
Nick Lewycky4a034522009-09-20 05:48:50 +00002022 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
Chris Lattner94eb4b22010-02-01 20:04:40 +00002023 Constant *CE2Op0 = CE2->getOperand(0);
2024 if (CE2->getOpcode() == Instruction::BitCast &&
2025 isa<VectorType>(CE2->getType()) ==isa<VectorType>(CE2Op0->getType())){
Nick Lewycky4a034522009-09-20 05:48:50 +00002026 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2027 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2028 }
2029 }
2030
Nick Lewycky9b3ed872009-09-20 07:31:25 +00002031 // If the left hand side is an extension, try eliminating it.
2032 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2033 if (CE1->getOpcode() == Instruction::SExt ||
2034 CE1->getOpcode() == Instruction::ZExt) {
2035 Constant *CE1Op0 = CE1->getOperand(0);
2036 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2037 if (CE1Inverse == CE1Op0) {
2038 // Check whether we can safely truncate the right hand side.
2039 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2040 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2041 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2042 }
2043 }
2044 }
2045 }
2046
Eli Friedmane67cae32009-12-17 06:07:04 +00002047 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2048 (C1->isNullValue() && !C2->isNullValue())) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002049 // If C2 is a constant expr and C1 isn't, flip them around and fold the
Reid Spencer9d36acf2006-12-24 18:52:08 +00002050 // other way if possible.
Eli Friedmane67cae32009-12-17 06:07:04 +00002051 // Also, if C1 is null and C2 isn't, flip them around.
Reid Spencer9d36acf2006-12-24 18:52:08 +00002052 switch (pred) {
2053 case ICmpInst::ICMP_EQ:
2054 case ICmpInst::ICMP_NE:
2055 // No change of predicate required.
Eli Friedmane67cae32009-12-17 06:07:04 +00002056 return ConstantExpr::getICmp(pred, C2, C1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00002057
2058 case ICmpInst::ICMP_ULT:
2059 case ICmpInst::ICMP_SLT:
2060 case ICmpInst::ICMP_UGT:
2061 case ICmpInst::ICMP_SGT:
2062 case ICmpInst::ICMP_ULE:
2063 case ICmpInst::ICMP_SLE:
2064 case ICmpInst::ICMP_UGE:
2065 case ICmpInst::ICMP_SGE:
2066 // Change the predicate as necessary to swap the operands.
2067 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
Eli Friedmane67cae32009-12-17 06:07:04 +00002068 return ConstantExpr::getICmp(pred, C2, C1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00002069
2070 default: // These predicates cannot be flopped around.
2071 break;
2072 }
Chris Lattner061da2f2004-01-13 05:51:55 +00002073 }
2074 }
2075 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +00002076}
Chris Lattner1dd054c2004-01-12 22:07:24 +00002077
Dan Gohman21c62162009-09-11 00:04:14 +00002078/// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2079/// is "inbounds".
2080static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
2081 // No indices means nothing that could be out of bounds.
2082 if (NumIdx == 0) return true;
2083
2084 // If the first index is zero, it's in bounds.
2085 if (Idxs[0]->isNullValue()) return true;
2086
2087 // If the first index is one and all the rest are zero, it's in bounds,
2088 // by the one-past-the-end rule.
2089 if (!cast<ConstantInt>(Idxs[0])->isOne())
2090 return false;
2091 for (unsigned i = 1, e = NumIdx; i != e; ++i)
2092 if (!Idxs[i]->isNullValue())
2093 return false;
2094 return true;
2095}
2096
Owen Anderson53a52212009-07-13 04:09:18 +00002097Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +00002098 Constant *C,
Dan Gohman21c62162009-09-11 00:04:14 +00002099 bool inBounds,
David Greenec656cbb2007-09-04 15:46:09 +00002100 Constant* const *Idxs,
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002101 unsigned NumIdx) {
Chris Lattner302116a2007-01-31 04:40:28 +00002102 if (NumIdx == 0 ||
2103 (NumIdx == 1 && Idxs[0]->isNullValue()))
Nick Lewyckye0332982009-09-20 01:35:59 +00002104 return C;
Chris Lattner1dd054c2004-01-12 22:07:24 +00002105
Chris Lattnerf6013752004-10-17 21:54:55 +00002106 if (isa<UndefValue>(C)) {
Christopher Lambedf07882007-12-17 01:12:55 +00002107 const PointerType *Ptr = cast<PointerType>(C->getType());
2108 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00002109 (Value **)Idxs,
Dan Gohman12fce772008-05-15 19:50:34 +00002110 (Value **)Idxs+NumIdx);
Chris Lattnerf6013752004-10-17 21:54:55 +00002111 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002112 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
Chris Lattnerf6013752004-10-17 21:54:55 +00002113 }
2114
Chris Lattner302116a2007-01-31 04:40:28 +00002115 Constant *Idx0 = Idxs[0];
Chris Lattner04b60fe2004-02-16 20:46:13 +00002116 if (C->isNullValue()) {
2117 bool isNull = true;
Chris Lattner302116a2007-01-31 04:40:28 +00002118 for (unsigned i = 0, e = NumIdx; i != e; ++i)
2119 if (!Idxs[i]->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00002120 isNull = false;
2121 break;
2122 }
2123 if (isNull) {
Christopher Lambedf07882007-12-17 01:12:55 +00002124 const PointerType *Ptr = cast<PointerType>(C->getType());
2125 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00002126 (Value**)Idxs,
Dan Gohman12fce772008-05-15 19:50:34 +00002127 (Value**)Idxs+NumIdx);
Chris Lattner04b60fe2004-02-16 20:46:13 +00002128 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002129 return ConstantPointerNull::get(
Owen Anderson4056ca92009-07-29 22:17:13 +00002130 PointerType::get(Ty,Ptr->getAddressSpace()));
Chris Lattner04b60fe2004-02-16 20:46:13 +00002131 }
2132 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00002133
Nick Lewyckye0332982009-09-20 01:35:59 +00002134 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1dd054c2004-01-12 22:07:24 +00002135 // Combine Indices - If the source pointer to this getelementptr instruction
2136 // is a getelementptr instruction, combine the indices of the two
2137 // getelementptr instructions into a single instruction.
2138 //
2139 if (CE->getOpcode() == Instruction::GetElementPtr) {
2140 const Type *LastTy = 0;
2141 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2142 I != E; ++I)
2143 LastTy = *I;
2144
Chris Lattner13128ab2004-10-11 22:52:25 +00002145 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
Chris Lattner302116a2007-01-31 04:40:28 +00002146 SmallVector<Value*, 16> NewIndices;
2147 NewIndices.reserve(NumIdx + CE->getNumOperands());
Chris Lattner1dd054c2004-01-12 22:07:24 +00002148 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00002149 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00002150
2151 // Add the last index of the source with the first index of the new GEP.
2152 // Make sure to handle the case when they are actually different types.
2153 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002154 // Otherwise it must be an array.
2155 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00002156 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00002157 if (IdxTy != Idx0->getType()) {
Owen Anderson53a52212009-07-13 04:09:18 +00002158 Constant *C1 =
Owen Anderson55f1c092009-08-13 21:58:54 +00002159 ConstantExpr::getSExtOrBitCast(Idx0, Type::getInt64Ty(Context));
Owen Anderson487375e2009-07-29 18:55:55 +00002160 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
Owen Anderson55f1c092009-08-13 21:58:54 +00002161 Type::getInt64Ty(Context));
Owen Anderson487375e2009-07-29 18:55:55 +00002162 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
Reid Spencer1a063892006-12-04 02:46:44 +00002163 } else {
2164 Combined =
Owen Anderson487375e2009-07-29 18:55:55 +00002165 ConstantExpr::get(Instruction::Add, Idx0, Combined);
Reid Spencer1a063892006-12-04 02:46:44 +00002166 }
Chris Lattner71068a02004-07-07 04:45:13 +00002167 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002168
Chris Lattner1dd054c2004-01-12 22:07:24 +00002169 NewIndices.push_back(Combined);
Chris Lattner302116a2007-01-31 04:40:28 +00002170 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
Dan Gohman21c62162009-09-11 00:04:14 +00002171 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2172 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2173 &NewIndices[0],
2174 NewIndices.size()) :
2175 ConstantExpr::getGetElementPtr(CE->getOperand(0),
2176 &NewIndices[0],
2177 NewIndices.size());
Chris Lattner1dd054c2004-01-12 22:07:24 +00002178 }
2179 }
2180
2181 // Implement folding of:
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002182 // int* getelementptr ([2 x int]* bitcast ([3 x int]* %X to [2 x int]*),
Chris Lattner1dd054c2004-01-12 22:07:24 +00002183 // long 0, long 0)
2184 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2185 //
Chris Lattneraadc7782007-08-13 17:09:08 +00002186 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002187 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00002188 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2189 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2190 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00002191 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00002192 if (CAT->getElementType() == SAT->getElementType())
Dan Gohman21c62162009-09-11 00:04:14 +00002193 return inBounds ?
2194 ConstantExpr::getInBoundsGetElementPtr(
2195 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2196 ConstantExpr::getGetElementPtr(
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002197 (Constant*)CE->getOperand(0), Idxs, NumIdx);
Chris Lattneraadc7782007-08-13 17:09:08 +00002198 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00002199 }
Dan Gohman21c62162009-09-11 00:04:14 +00002200
2201 // Check to see if any array indices are not within the corresponding
2202 // notional array bounds. If so, try to determine if they can be factored
2203 // out into preceding dimensions.
2204 bool Unknown = false;
2205 SmallVector<Constant *, 8> NewIdxs;
2206 const Type *Ty = C->getType();
2207 const Type *Prev = 0;
2208 for (unsigned i = 0; i != NumIdx;
2209 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2210 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2211 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2212 if (ATy->getNumElements() <= INT64_MAX &&
2213 ATy->getNumElements() != 0 &&
2214 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2215 if (isa<SequentialType>(Prev)) {
2216 // It's out of range, but we can factor it into the prior
2217 // dimension.
2218 NewIdxs.resize(NumIdx);
2219 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2220 ATy->getNumElements());
2221 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2222
2223 Constant *PrevIdx = Idxs[i-1];
2224 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2225
2226 // Before adding, extend both operands to i64 to avoid
2227 // overflow trouble.
Benjamin Kramerd2564e32010-01-05 21:05:54 +00002228 if (!PrevIdx->getType()->isInteger(64))
Dan Gohman21c62162009-09-11 00:04:14 +00002229 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2230 Type::getInt64Ty(Context));
Benjamin Kramerd2564e32010-01-05 21:05:54 +00002231 if (!Div->getType()->isInteger(64))
Dan Gohman21c62162009-09-11 00:04:14 +00002232 Div = ConstantExpr::getSExt(Div,
2233 Type::getInt64Ty(Context));
2234
2235 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2236 } else {
2237 // It's out of range, but the prior dimension is a struct
2238 // so we can't do anything about it.
2239 Unknown = true;
2240 }
2241 }
2242 } else {
2243 // We don't know if it's in range or not.
2244 Unknown = true;
2245 }
2246 }
2247
2248 // If we did any factoring, start over with the adjusted indices.
2249 if (!NewIdxs.empty()) {
2250 for (unsigned i = 0; i != NumIdx; ++i)
2251 if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2252 return inBounds ?
Nick Lewyckye0332982009-09-20 01:35:59 +00002253 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2254 NewIdxs.size()) :
2255 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
Dan Gohman21c62162009-09-11 00:04:14 +00002256 }
2257
2258 // If all indices are known integers and normalized, we can do a simple
2259 // check for the "inbounds" property.
2260 if (!Unknown && !inBounds &&
2261 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
Nick Lewyckye0332982009-09-20 01:35:59 +00002262 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
Dan Gohman21c62162009-09-11 00:04:14 +00002263
Chris Lattner1dd054c2004-01-12 22:07:24 +00002264 return 0;
2265}