blob: 3fe1d754546bb2056c916c8a895ad7329705f47e [file] [log] [blame]
Dan Gohman83e3c4f2009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
John Criswellbd9d3702005-10-27 16:00:10 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswellbd9d3702005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohman83e3c4f2009-09-10 23:07:18 +000010// This file defines routines for folding instructions into constants.
11//
12// Also, to supplement the basic VMCore ConstantExpr simplifications,
13// this file defines some additional folding routines that can make use of
14// TargetData information. These functions cannot go in VMCore due to library
15// dependency issues.
John Criswellbd9d3702005-10-27 16:00:10 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattner55207322007-01-30 23:45:45 +000022#include "llvm/Function.h"
Dan Gohman9a38e3e2009-05-07 19:46:24 +000023#include "llvm/GlobalVariable.h"
John Criswellbd9d3702005-10-27 16:00:10 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Owen Anderson50895512009-07-06 18:42:36 +000026#include "llvm/LLVMContext.h"
Chris Lattner62d327e2009-10-22 06:38:35 +000027#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/Target/TargetData.h"
Chris Lattner55207322007-01-30 23:45:45 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000030#include "llvm/ADT/StringMap.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
John Criswellbd9d3702005-10-27 16:00:10 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
33#include "llvm/Support/MathExtras.h"
34#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000035#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000036using namespace llvm;
37
Chris Lattner03dd25c2007-01-31 00:51:48 +000038//===----------------------------------------------------------------------===//
39// Constant Folding internal helper functions
40//===----------------------------------------------------------------------===//
41
42/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
43/// from a global, return the global and the constant. Because of
44/// constantexprs, this function is recursive.
45static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
46 int64_t &Offset, const TargetData &TD) {
47 // Trivial case, constant is the global.
48 if ((GV = dyn_cast<GlobalValue>(C))) {
49 Offset = 0;
50 return true;
51 }
52
53 // Otherwise, if this isn't a constant expr, bail out.
54 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
55 if (!CE) return false;
56
57 // Look through ptr->int and ptr->ptr casts.
58 if (CE->getOpcode() == Instruction::PtrToInt ||
59 CE->getOpcode() == Instruction::BitCast)
60 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
61
62 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
63 if (CE->getOpcode() == Instruction::GetElementPtr) {
64 // Cannot compute this if the element type of the pointer is missing size
65 // info.
Chris Lattnerf286f6f2007-12-10 22:53:04 +000066 if (!cast<PointerType>(CE->getOperand(0)->getType())
67 ->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +000068 return false;
69
70 // If the base isn't a global+constant, we aren't either.
71 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
72 return false;
73
74 // Otherwise, add any offset that our operands provide.
75 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifde2d74b2008-05-22 06:43:33 +000076 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greif785c6af2008-05-22 19:24:54 +000077 i != e; ++i, ++GTI) {
Gabor Greifde2d74b2008-05-22 06:43:33 +000078 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Chris Lattner03dd25c2007-01-31 00:51:48 +000079 if (!CI) return false; // Index isn't a simple constant?
80 if (CI->getZExtValue() == 0) continue; // Not adding anything.
81
82 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
83 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000084 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000085 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000086 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands777d2302009-05-09 07:06:46 +000087 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000088 }
89 }
90 return true;
91 }
92
93 return false;
94}
95
Chris Lattnerfe8c7c82009-10-23 06:23:49 +000096/// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
97/// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
98/// pointer to copy results into and BytesLeft is the number of bytes left in
99/// the CurPtr buffer. TD is the target data.
100static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
101 unsigned char *CurPtr, unsigned BytesLeft,
102 const TargetData &TD) {
103 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
104 "Out of range access");
105
106 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
107 return true;
108
109 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
110 if (CI->getBitWidth() > 64 ||
111 (CI->getBitWidth() & 7) != 0)
112 return false;
113
114 uint64_t Val = CI->getZExtValue();
115 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
116
117 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
118 CurPtr[i] = (unsigned char)(Val >> ByteOffset * 8);
119 ++ByteOffset;
120 }
121 return true;
122 }
123
124 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
125 if (CFP->getType()->isDoubleTy()) {
126 C = ConstantExpr::getBitCast(C, Type::getInt64Ty(C->getContext()));
127 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
128 }
129 if (CFP->getType()->isFloatTy()){
130 C = ConstantExpr::getBitCast(C, Type::getInt32Ty(C->getContext()));
131 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
132 }
133 }
134
135 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
136 const StructLayout *SL = TD.getStructLayout(CS->getType());
137 unsigned Index = SL->getElementContainingOffset(ByteOffset);
138 uint64_t CurEltOffset = SL->getElementOffset(Index);
139 ByteOffset -= CurEltOffset;
140
141 while (1) {
142 // If the element access is to the element itself and not to tail padding,
143 // read the bytes from the element.
144 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
145
146 if (ByteOffset < EltSize &&
147 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
148 BytesLeft, TD))
149 return false;
150
151 ++Index;
152
153 // Check to see if we read from the last struct element, if so we're done.
154 if (Index == CS->getType()->getNumElements())
155 return true;
156
157 // If we read all of the bytes we needed from this element we're done.
158 uint64_t NextEltOffset = SL->getElementOffset(Index);
159
160 if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
161 return true;
162
163 // Move to the next element of the struct.
Chris Lattnerc5af6492009-10-24 05:22:15 +0000164 CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000165 BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
166 ByteOffset = 0;
167 CurEltOffset = NextEltOffset;
168 }
169 // not reached.
170 }
171
172 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
173 uint64_t EltSize = TD.getTypeAllocSize(CA->getType()->getElementType());
174 uint64_t Index = ByteOffset / EltSize;
175 uint64_t Offset = ByteOffset - Index * EltSize;
176 for (; Index != CA->getType()->getNumElements(); ++Index) {
177 if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
178 BytesLeft, TD))
179 return false;
180 if (EltSize >= BytesLeft)
181 return true;
182
183 Offset = 0;
184 BytesLeft -= EltSize;
185 CurPtr += EltSize;
186 }
187 return true;
188 }
189
190 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
191 uint64_t EltSize = TD.getTypeAllocSize(CV->getType()->getElementType());
192 uint64_t Index = ByteOffset / EltSize;
193 uint64_t Offset = ByteOffset - Index * EltSize;
194 for (; Index != CV->getType()->getNumElements(); ++Index) {
195 if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
196 BytesLeft, TD))
197 return false;
198 if (EltSize >= BytesLeft)
199 return true;
200
201 Offset = 0;
202 BytesLeft -= EltSize;
203 CurPtr += EltSize;
204 }
205 return true;
206 }
207
208 // Otherwise, unknown initializer type.
209 return false;
210}
211
212static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
213 const TargetData &TD) {
Chris Lattner17f0cd32009-10-23 06:57:37 +0000214 const Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
215 const IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000216
217 // If this isn't an integer load we can't fold it directly.
218 if (!IntType) {
219 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattner17f0cd32009-10-23 06:57:37 +0000220 // and then bitcast the result. This can be useful for union cases. Note
221 // that address spaces don't matter here since we're not going to result in
222 // an actual new load.
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000223 const Type *MapTy;
Chris Lattner17f0cd32009-10-23 06:57:37 +0000224 if (LoadTy->isFloatTy())
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000225 MapTy = Type::getInt32PtrTy(C->getContext());
Chris Lattner17f0cd32009-10-23 06:57:37 +0000226 else if (LoadTy->isDoubleTy())
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000227 MapTy = Type::getInt64PtrTy(C->getContext());
Chris Lattner17f0cd32009-10-23 06:57:37 +0000228 else if (isa<VectorType>(LoadTy)) {
229 MapTy = IntegerType::get(C->getContext(),
230 TD.getTypeAllocSizeInBits(LoadTy));
231 MapTy = PointerType::getUnqual(MapTy);
232 } else
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000233 return 0;
234
235 C = ConstantExpr::getBitCast(C, MapTy);
236 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
Chris Lattner17f0cd32009-10-23 06:57:37 +0000237 return ConstantExpr::getBitCast(Res, LoadTy);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000238 return 0;
239 }
240
241 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Chris Lattner739208a2009-10-23 06:50:36 +0000242 if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000243
244 GlobalValue *GVal;
245 int64_t Offset;
246 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
247 return 0;
248
249 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
250 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
251 !GV->hasDefinitiveInitializer() ||
252 !GV->getInitializer()->getType()->isSized())
253 return 0;
254
255 // If we're loading off the beginning of the global, some bytes may be valid,
256 // but we don't try to handle this.
257 if (Offset < 0) return 0;
258
259 // If we're not accessing anything in this constant, the result is undefined.
260 if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
261 return UndefValue::get(IntType);
262
Chris Lattner739208a2009-10-23 06:50:36 +0000263 unsigned char RawBytes[32] = {0};
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000264 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
265 BytesLoaded, TD))
266 return 0;
267
Chris Lattner739208a2009-10-23 06:50:36 +0000268 APInt ResultVal(IntType->getBitWidth(), 0);
269 for (unsigned i = 0; i != BytesLoaded; ++i) {
270 ResultVal <<= 8;
271 ResultVal |= APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1-i]);
272 }
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000273
Chris Lattner739208a2009-10-23 06:50:36 +0000274 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000275}
276
Chris Lattner878e4942009-10-22 06:25:11 +0000277/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
278/// produce if it is constant and determinable. If this is not determinable,
279/// return null.
280Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
281 const TargetData *TD) {
282 // First, try the easy cases:
283 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
284 if (GV->isConstant() && GV->hasDefinitiveInitializer())
285 return GV->getInitializer();
286
Chris Lattnere00c43f2009-10-22 06:44:07 +0000287 // If the loaded value isn't a constant expr, we can't handle it.
288 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
289 if (!CE) return 0;
290
291 if (CE->getOpcode() == Instruction::GetElementPtr) {
292 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
293 if (GV->isConstant() && GV->hasDefinitiveInitializer())
294 if (Constant *V =
295 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
296 return V;
297 }
298
299 // Instead of loading constant c string, use corresponding integer value
300 // directly if string length is small enough.
301 std::string Str;
302 if (TD && GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000303 unsigned StrLen = Str.length();
Chris Lattnere00c43f2009-10-22 06:44:07 +0000304 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000305 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnere00c43f2009-10-22 06:44:07 +0000306 // Replace LI with immediate integer store.
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000307 if ((NumBits >> 3) == StrLen + 1) {
308 APInt StrVal(NumBits, 0);
309 APInt SingleChar(NumBits, 0);
Chris Lattnere00c43f2009-10-22 06:44:07 +0000310 if (TD->isLittleEndian()) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000311 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnere00c43f2009-10-22 06:44:07 +0000312 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner62d327e2009-10-22 06:38:35 +0000313 StrVal = (StrVal << 8) | SingleChar;
314 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000315 } else {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000316 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnere00c43f2009-10-22 06:44:07 +0000317 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
318 StrVal = (StrVal << 8) | SingleChar;
319 }
320 // Append NULL at the end.
321 SingleChar = 0;
322 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner62d327e2009-10-22 06:38:35 +0000323 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000324 return ConstantInt::get(CE->getContext(), StrVal);
Chris Lattner62d327e2009-10-22 06:38:35 +0000325 }
Chris Lattner878e4942009-10-22 06:25:11 +0000326 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000327
328 // If this load comes from anywhere in a constant global, and if the global
329 // is all undef or zero, we know what it loads.
330 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getUnderlyingObject())){
331 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
332 const Type *ResTy = cast<PointerType>(C->getType())->getElementType();
333 if (GV->getInitializer()->isNullValue())
334 return Constant::getNullValue(ResTy);
335 if (isa<UndefValue>(GV->getInitializer()))
336 return UndefValue::get(ResTy);
337 }
338 }
339
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000340 // Try hard to fold loads from bitcasted strange and non-type-safe things. We
341 // currently don't do any of this for big endian systems. It can be
342 // generalized in the future if someone is interested.
343 if (TD && TD->isLittleEndian())
344 return FoldReinterpretLoadFromConstPtr(CE, *TD);
Chris Lattner878e4942009-10-22 06:25:11 +0000345 return 0;
346}
347
348static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
349 if (LI->isVolatile()) return 0;
350
351 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
352 return ConstantFoldLoadFromConstPtr(C, TD);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000353
Chris Lattner878e4942009-10-22 06:25:11 +0000354 return 0;
355}
Chris Lattner03dd25c2007-01-31 00:51:48 +0000356
357/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +0000358/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +0000359/// these together. If target data info is available, it is provided as TD,
360/// otherwise TD is null.
361static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +0000362 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +0000363 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +0000364 // SROA
365
366 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
367 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
368 // bits.
369
370
371 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
372 // constant. This happens frequently when iterating over a global array.
373 if (Opc == Instruction::Sub && TD) {
374 GlobalValue *GV1, *GV2;
375 int64_t Offs1, Offs2;
376
377 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
378 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
379 GV1 == GV2) {
380 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000381 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000382 }
383 }
384
Chris Lattner03dd25c2007-01-31 00:51:48 +0000385 return 0;
386}
387
388/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
389/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000390static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000391 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000392 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000393 const TargetData *TD) {
394 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000395 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000396 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000397
398 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
399 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000400 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000401 if (!Ptr->isNullValue()) {
402 // If this is a inttoptr from a constant int, we can fold this as the base,
403 // otherwise we can't.
404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
405 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000406 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000407 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000408 BasePtr.zextOrTrunc(BitWidth);
409 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000410
411 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000412 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000413 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000414
415 // If this is a constant expr gep that is effectively computing an
416 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
417 for (unsigned i = 1; i != NumOps; ++i)
418 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000419 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000420
Dan Gohmancda97062009-08-21 16:52:54 +0000421 APInt Offset = APInt(BitWidth,
422 TD->getIndexedOffset(Ptr->getType(),
423 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000424 // If the base value for this address is a literal integer value, fold the
425 // getelementptr to the resulting integer value casted to the pointer type.
426 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000427 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000428 return ConstantExpr::getIntToPtr(C, ResultTy);
429 }
430
431 // Otherwise form a regular getelementptr. Recompute the indices so that
432 // we eliminate over-indexing of the notional static type array bounds.
433 // This makes it easy to determine if the getelementptr is "inbounds".
434 // Also, this helps GlobalOpt do SROA on GlobalVariables.
435 const Type *Ty = Ptr->getType();
436 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000437 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000438 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000439 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000440 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000441 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000442 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000443 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000444 if (ElemSize == 0)
445 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000446 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000447 Offset -= NewIdx * ElemSize;
448 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
449 Ty = ATy->getElementType();
450 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000451 // Determine which field of the struct the offset points into. The
452 // getZExtValue is at least as safe as the StructLayout API because we
453 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000454 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000455 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000456 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000457 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000458 Ty = STy->getTypeAtIndex(ElIdx);
459 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000460 // We've reached some non-indexable type.
461 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000462 }
Dan Gohman3d013342009-08-19 22:46:59 +0000463 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
464
465 // If we haven't used up the entire offset by descending the static
466 // type, then the offset is pointing into the middle of an indivisible
467 // member, so we can't simplify it.
468 if (Offset != 0)
469 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000470
Dan Gohman3bfbc452009-09-11 00:04:14 +0000471 // Create a GEP.
472 Constant *C =
Dan Gohman6e7ad952009-09-03 23:34:49 +0000473 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
474 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
475 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000476
Dan Gohman3d013342009-08-19 22:46:59 +0000477 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000478 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000479 if (Ty != cast<PointerType>(ResultTy)->getElementType())
480 C = ConstantExpr::getBitCast(C, ResultTy);
481
482 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000483}
484
Chris Lattner1afab9c2007-12-11 07:29:44 +0000485/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
486/// targetdata. Return 0 if unfoldable.
487static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000488 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000489 // If this is a bitcast from constant vector -> vector, fold it.
490 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
491 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
492 // If the element types match, VMCore can fold it.
493 unsigned NumDstElt = DestVTy->getNumElements();
494 unsigned NumSrcElt = CV->getNumOperands();
495 if (NumDstElt == NumSrcElt)
496 return 0;
497
498 const Type *SrcEltTy = CV->getType()->getElementType();
499 const Type *DstEltTy = DestVTy->getElementType();
500
501 // Otherwise, we're changing the number of elements in a vector, which
502 // requires endianness information to do the right thing. For example,
503 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
504 // folds to (little endian):
505 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
506 // and to (big endian):
507 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
508
509 // First thing is first. We only want to think about integer here, so if
510 // we have something in FP form, recast it as integer.
511 if (DstEltTy->isFloatingPoint()) {
512 // Fold to an vector of integers with same size as our FP type.
513 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000514 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000515 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000516 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000517 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000518 if (!C) return 0;
519
520 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000521 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000522 }
523
524 // Okay, we know the destination is integer, if the input is FP, convert
525 // it to integer first.
526 if (SrcEltTy->isFloatingPoint()) {
527 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000528 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000529 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000530 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000531 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000532 CV = dyn_cast<ConstantVector>(C);
533 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
534 }
535
536 // Now we know that the input and output vectors are both integer vectors
537 // of the same size, and that their #elements is not the same. Do the
538 // conversion here, which depends on whether the input or output has
539 // more elements.
540 bool isLittleEndian = TD.isLittleEndian();
541
542 SmallVector<Constant*, 32> Result;
543 if (NumDstElt < NumSrcElt) {
544 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000545 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000546 unsigned Ratio = NumSrcElt/NumDstElt;
547 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
548 unsigned SrcElt = 0;
549 for (unsigned i = 0; i != NumDstElt; ++i) {
550 // Build each element of the result.
551 Constant *Elt = Zero;
552 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
553 for (unsigned j = 0; j != Ratio; ++j) {
554 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
555 if (!Src) return 0; // Reject constantexpr elements.
556
557 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000558 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000559
560 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000561 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000562 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000563 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
564
565 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000566 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000567 }
568 Result.push_back(Elt);
569 }
570 } else {
571 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
572 unsigned Ratio = NumDstElt/NumSrcElt;
573 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
574
575 // Loop over each source value, expanding into multiple results.
576 for (unsigned i = 0; i != NumSrcElt; ++i) {
577 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
578 if (!Src) return 0; // Reject constantexpr elements.
579
580 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
581 for (unsigned j = 0; j != Ratio; ++j) {
582 // Shift the piece of the value into the right place, depending on
583 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000584 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000585 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000586 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
587
588 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000589 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000590 }
591 }
592 }
593
Owen Andersonaf7ec972009-07-28 21:19:26 +0000594 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000595 }
596 }
597
598 return 0;
599}
600
Chris Lattner03dd25c2007-01-31 00:51:48 +0000601
602//===----------------------------------------------------------------------===//
603// Constant Folding public APIs
604//===----------------------------------------------------------------------===//
605
606
Chris Lattner55207322007-01-30 23:45:45 +0000607/// ConstantFoldInstruction - Attempt to constant fold the specified
608/// instruction. If successful, the constant result is returned, if not, null
609/// is returned. Note that this function can only fail when attempting to fold
610/// instructions like loads and stores, which have no constant expression form.
611///
Owen Andersone922c022009-07-22 00:24:57 +0000612Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000613 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000614 if (PHINode *PN = dyn_cast<PHINode>(I)) {
615 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000616 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000617
Chris Lattner55207322007-01-30 23:45:45 +0000618 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
619 if (Result == 0) return 0;
620
621 // Handle PHI nodes specially here...
622 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
623 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
624 return 0; // Not all the same incoming constants...
625
626 // If we reach here, all incoming values are the same constant.
627 return Result;
628 }
629
630 // Scan the operand list, checking to see if they are all constants, if so,
631 // hand off to ConstantFoldInstOperands.
632 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000633 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
634 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000635 Ops.push_back(Op);
636 else
637 return 0; // All operands not constant!
638
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000639 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
640 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000641 Ops.data(), Ops.size(),
642 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000643
Chris Lattner878e4942009-10-22 06:25:11 +0000644 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
645 return ConstantFoldLoadInst(LI, TD);
646
Chris Lattner58665d42009-09-16 00:08:07 +0000647 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
648 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000649}
650
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000651/// ConstantFoldConstantExpression - Attempt to fold the constant expression
652/// using the specified TargetData. If successful, the constant result is
653/// result is returned, if not, null is returned.
654Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000655 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000656 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000657 SmallVector<Constant*, 8> Ops;
658 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
659 Ops.push_back(cast<Constant>(*i));
660
661 if (CE->isCompare())
662 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000663 Ops.data(), Ops.size(),
664 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000665 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
666 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000667}
668
Chris Lattner55207322007-01-30 23:45:45 +0000669/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
670/// specified opcode and operands. If successful, the constant result is
671/// returned, if not, null is returned. Note that this function can fail when
672/// attempting to fold instructions like loads and stores, which have no
673/// constant expression form.
674///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000675Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
676 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000677 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000678 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000679 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000680 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000681 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000682 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
683 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000684 return C;
685
Owen Andersonbaf3c402009-07-29 18:55:55 +0000686 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000687 }
Chris Lattner55207322007-01-30 23:45:45 +0000688
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000689 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000690 default: return 0;
691 case Instruction::Call:
692 if (Function *F = dyn_cast<Function>(Ops[0]))
693 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000694 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000695 return 0;
696 case Instruction::ICmp:
697 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000698 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000699 case Instruction::PtrToInt:
700 // If the input is a inttoptr, eliminate the pair. This requires knowing
701 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
702 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
703 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
704 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000705 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000706 if (TD->getPointerSizeInBits() < InWidth) {
707 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000708 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000709 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000710 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000711 }
Chris Lattner001f7532007-08-11 23:49:01 +0000712 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000713 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000714 }
715 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000716 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000717 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000718 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
719 // the int size is >= the ptr size. This requires knowing the width of a
720 // pointer, so it can't be done in ConstantExpr::getCast.
721 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000722 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000723 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000724 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000725 if (CE->getOpcode() == Instruction::PtrToInt) {
726 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000727 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000728 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000729 }
730 // If there's a constant offset added to the integer value before
731 // it is casted back to a pointer, see if the expression can be
732 // converted into a GEP.
733 if (CE->getOpcode() == Instruction::Add)
734 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
735 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
736 if (R->getOpcode() == Instruction::PtrToInt)
737 if (GlobalVariable *GV =
738 dyn_cast<GlobalVariable>(R->getOperand(0))) {
739 const PointerType *GVTy = cast<PointerType>(GV->getType());
740 if (const ArrayType *AT =
741 dyn_cast<ArrayType>(GVTy->getElementType())) {
742 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000743 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
744 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000745 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
746 L->getValue().urem(PSA) == 0) {
747 APInt ElemIdx = L->getValue().udiv(PSA);
748 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
749 AT->getNumElements()))) {
750 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000751 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000752 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000753 };
Owen Anderson50895512009-07-06 18:42:36 +0000754 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000755 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000756 }
757 }
758 }
759 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000760 }
761 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000762 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000763 case Instruction::Trunc:
764 case Instruction::ZExt:
765 case Instruction::SExt:
766 case Instruction::FPTrunc:
767 case Instruction::FPExt:
768 case Instruction::UIToFP:
769 case Instruction::SIToFP:
770 case Instruction::FPToUI:
771 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000772 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000773 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000774 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000775 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000776 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000777 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000778 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000779 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000780 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000781 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000782 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000783 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000784 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000785 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000786 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000787 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000788 return C;
789
Owen Andersonbaf3c402009-07-29 18:55:55 +0000790 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000791 }
792}
793
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000794/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
795/// instruction (icmp/fcmp) with the specified operands. If it fails, it
796/// returns a constant expression of the specified operands.
797///
798Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
799 Constant*const * Ops,
800 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000801 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000802 const TargetData *TD) {
803 // fold: icmp (inttoptr x), null -> icmp x, 0
804 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000805 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000806 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
807 //
808 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
809 // around to know if bit truncation is happening.
810 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
811 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000812 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000813 if (CE0->getOpcode() == Instruction::IntToPtr) {
814 // Convert the integer value to the right size to ensure we get the
815 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000816 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000817 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000818 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000819 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
820 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000821 }
822
823 // Only do this transformation if the int is intptrty in size, otherwise
824 // there is a truncation or extension that we aren't modeling.
825 if (CE0->getOpcode() == Instruction::PtrToInt &&
826 CE0->getType() == IntPtrTy) {
827 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000828 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000829 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000830 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
831 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000832 }
833 }
834
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000835 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
836 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000837 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000838
839 if (CE0->getOpcode() == Instruction::IntToPtr) {
840 // Convert the integer value to the right size to ensure we get the
841 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000842 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000843 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000844 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000845 IntPtrTy, false);
846 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000847 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
848 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000849 }
850
851 // Only do this transformation if the int is intptrty in size, otherwise
852 // there is a truncation or extension that we aren't modeling.
853 if ((CE0->getOpcode() == Instruction::PtrToInt &&
854 CE0->getType() == IntPtrTy &&
855 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
856 Constant *NewOps[] = {
857 CE0->getOperand(0), CE1->getOperand(0)
858 };
Owen Anderson50895512009-07-06 18:42:36 +0000859 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
860 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000861 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000862 }
863 }
864 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000865 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000866}
867
868
Chris Lattner55207322007-01-30 23:45:45 +0000869/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
870/// getelementptr constantexpr, return the constant value being addressed by the
871/// constant expression, or null if something is funny and we can't decide.
872Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000873 ConstantExpr *CE) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000874 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000875 return 0; // Do not allow stepping over the value!
876
877 // Loop over all of the operands, tracking down which value we are
878 // addressing...
879 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
880 for (++I; I != E; ++I)
881 if (const StructType *STy = dyn_cast<StructType>(*I)) {
882 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
883 assert(CU->getZExtValue() < STy->getNumElements() &&
884 "Struct index out of range!");
885 unsigned El = (unsigned)CU->getZExtValue();
886 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
887 C = CS->getOperand(El);
888 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000889 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000890 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000891 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000892 } else {
893 return 0;
894 }
895 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
896 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
897 if (CI->getZExtValue() >= ATy->getNumElements())
898 return 0;
899 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
900 C = CA->getOperand(CI->getZExtValue());
901 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000902 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000903 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000904 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000905 else
906 return 0;
Chris Lattner62d327e2009-10-22 06:38:35 +0000907 } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
908 if (CI->getZExtValue() >= VTy->getNumElements())
Chris Lattner55207322007-01-30 23:45:45 +0000909 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000910 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000911 C = CP->getOperand(CI->getZExtValue());
912 else if (isa<ConstantAggregateZero>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000913 C = Constant::getNullValue(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000914 else if (isa<UndefValue>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000915 C = UndefValue::get(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000916 else
917 return 0;
918 } else {
919 return 0;
920 }
921 } else {
922 return 0;
923 }
924 return C;
925}
926
927
928//===----------------------------------------------------------------------===//
929// Constant Folding for Calls
930//
John Criswellbd9d3702005-10-27 16:00:10 +0000931
932/// canConstantFoldCallTo - Return true if its even possible to fold a call to
933/// the specified function.
934bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000935llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000936 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000937 case Intrinsic::sqrt:
938 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000939 case Intrinsic::bswap:
940 case Intrinsic::ctpop:
941 case Intrinsic::ctlz:
942 case Intrinsic::cttz:
Chris Lattnere65cd402009-10-05 05:26:04 +0000943 case Intrinsic::uadd_with_overflow:
944 case Intrinsic::usub_with_overflow:
Evan Phoenix1614e502009-10-05 22:53:52 +0000945 case Intrinsic::sadd_with_overflow:
946 case Intrinsic::ssub_with_overflow:
John Criswellbd9d3702005-10-27 16:00:10 +0000947 return true;
Chris Lattner68a06032009-10-05 05:00:35 +0000948 default:
949 return false;
950 case 0: break;
John Criswellbd9d3702005-10-27 16:00:10 +0000951 }
952
Chris Lattner6f532a92009-04-03 00:02:39 +0000953 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000954 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000955
956 // In these cases, the check of the length is required. We don't want to
957 // return true for a name like "cos\0blah" which strcmp would return equal to
958 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000959 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000960 default: return false;
961 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000962 return Name == "acos" || Name == "asin" ||
963 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000964 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000965 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000966 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000967 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000968 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000969 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000970 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000971 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000972 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000973 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000974 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000975 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
976 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000977 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000978 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000979 }
980}
981
Chris Lattner72d88ae2007-01-30 23:15:43 +0000982static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000983 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000984 errno = 0;
985 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000986 if (errno != 0) {
987 errno = 0;
988 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000989 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000990
Chris Lattnerd0806a12009-10-05 05:06:24 +0000991 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000992 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000993 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000994 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000995 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000996 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000997}
998
Dan Gohman38415242007-07-16 15:26:22 +0000999static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1000 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +00001001 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +00001002 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +00001003 errno = 0;
1004 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +00001005 if (errno != 0) {
1006 errno = 0;
1007 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +00001008 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +00001009
Chris Lattnerd0806a12009-10-05 05:06:24 +00001010 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001011 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +00001012 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001013 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +00001014 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +00001015 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +00001016}
1017
John Criswellbd9d3702005-10-27 16:00:10 +00001018/// ConstantFoldCall - Attempt to constant fold a call to the specified function
1019/// with the specified arguments, returning null if unsuccessful.
1020Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001021llvm::ConstantFoldCall(Function *F,
Chris Lattner68a06032009-10-05 05:00:35 +00001022 Constant *const *Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +00001023 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +00001024 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001025 StringRef Name = F->getName();
Chris Lattnere65cd402009-10-05 05:26:04 +00001026
John Criswellbd9d3702005-10-27 16:00:10 +00001027 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +00001028 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +00001029 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001030 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen43421b32007-09-06 18:13:44 +00001031 return 0;
1032 /// Currently APFloat versions of these functions do not exist, so we use
1033 /// the host native double versions. Float versions are not called
1034 /// directly but for all these it is true (float)(f((double)arg)) ==
1035 /// f(arg). Long double not supported yet.
Chris Lattnerd0806a12009-10-05 05:06:24 +00001036 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +00001037 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001038 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001039 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001040 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +00001041 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001042 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +00001043 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001044 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +00001045 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001046 break;
1047 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001048 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +00001049 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001050 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +00001051 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001052 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +00001053 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001054 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +00001055 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001056 break;
1057 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001058 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +00001059 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001060 break;
1061 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001062 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +00001063 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001064 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +00001065 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001066 break;
1067 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001068 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +00001069 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001070 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +00001071 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001072 else if (Name == "llvm.sqrt.f32" ||
1073 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001074 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +00001075 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001076 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +00001077 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001078 }
1079 break;
1080 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001081 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +00001082 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001083 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +00001084 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001085 else if (Name == "sqrt" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +00001086 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001087 else if (Name == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +00001088 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001089 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +00001090 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001091 break;
1092 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001093 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +00001094 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001095 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +00001096 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001097 break;
1098 default:
1099 break;
John Criswellbd9d3702005-10-27 16:00:10 +00001100 }
Chris Lattner68a06032009-10-05 05:00:35 +00001101 return 0;
1102 }
1103
1104
1105 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001106 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001107 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001108 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001109 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001110 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001111 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001112 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001113 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Chris Lattner68a06032009-10-05 05:00:35 +00001114 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001115 }
Chris Lattner68a06032009-10-05 05:00:35 +00001116
1117 return 0;
1118 }
1119
1120 if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +00001121 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001122 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00001123 return 0;
Chris Lattnerd0806a12009-10-05 05:06:24 +00001124 double Op1V = Ty->isFloatTy() ?
1125 (double)Op1->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +00001126 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +00001127 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001128 if (Op2->getType() != Op1->getType())
1129 return 0;
1130
1131 double Op2V = Ty->isFloatTy() ?
Dale Johannesen43421b32007-09-06 18:13:44 +00001132 (double)Op2->getValueAPF().convertToFloat():
1133 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +00001134
Chris Lattner68a06032009-10-05 05:00:35 +00001135 if (Name == "pow")
Owen Anderson50895512009-07-06 18:42:36 +00001136 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +00001137 if (Name == "fmod")
Owen Anderson50895512009-07-06 18:42:36 +00001138 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +00001139 if (Name == "atan2")
Owen Anderson50895512009-07-06 18:42:36 +00001140 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +00001141 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattner68a06032009-10-05 05:00:35 +00001142 if (Name == "llvm.powi.f32")
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001143 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +00001144 (int)Op2C->getZExtValue())));
Chris Lattner68a06032009-10-05 05:00:35 +00001145 if (Name == "llvm.powi.f64")
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001146 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +00001147 (int)Op2C->getZExtValue())));
John Criswellbd9d3702005-10-27 16:00:10 +00001148 }
Chris Lattner68a06032009-10-05 05:00:35 +00001149 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001150 }
Chris Lattnere65cd402009-10-05 05:26:04 +00001151
1152
1153 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1154 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1155 switch (F->getIntrinsicID()) {
1156 default: break;
1157 case Intrinsic::uadd_with_overflow: {
1158 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
1159 Constant *Ops[] = {
1160 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
1161 };
1162 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1163 }
1164 case Intrinsic::usub_with_overflow: {
1165 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
1166 Constant *Ops[] = {
1167 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
1168 };
1169 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1170 }
Evan Phoenix1614e502009-10-05 22:53:52 +00001171 case Intrinsic::sadd_with_overflow: {
1172 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
1173 Constant *Overflow = ConstantExpr::getSelect(
1174 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1175 ConstantInt::get(Op1->getType(), 0), Op1),
1176 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
1177 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
1178
1179 Constant *Ops[] = { Res, Overflow };
1180 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1181 }
1182 case Intrinsic::ssub_with_overflow: {
1183 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
1184 Constant *Overflow = ConstantExpr::getSelect(
1185 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1186 ConstantInt::get(Op2->getType(), 0), Op2),
1187 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
1188 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
1189
1190 Constant *Ops[] = { Res, Overflow };
1191 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1192 }
Chris Lattnere65cd402009-10-05 05:26:04 +00001193 }
1194 }
1195
1196 return 0;
1197 }
1198 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001199 }
1200 return 0;
1201}
1202