blob: 074ff790e1fb362c6b4e32468ea0aab0299d8eeb [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
Chris Lattnerc7b13822009-10-24 05:27:19 +0000106 // If this element is zero or undefined, we can just return since *CurPtr is
107 // zero initialized.
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000108 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
109 return true;
110
111 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
112 if (CI->getBitWidth() > 64 ||
113 (CI->getBitWidth() & 7) != 0)
114 return false;
115
116 uint64_t Val = CI->getZExtValue();
117 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
118
119 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
Chris Lattnerc7b13822009-10-24 05:27:19 +0000120 CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000121 ++ByteOffset;
122 }
123 return true;
124 }
125
126 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
127 if (CFP->getType()->isDoubleTy()) {
128 C = ConstantExpr::getBitCast(C, Type::getInt64Ty(C->getContext()));
129 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
130 }
131 if (CFP->getType()->isFloatTy()){
132 C = ConstantExpr::getBitCast(C, Type::getInt32Ty(C->getContext()));
133 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
134 }
Chris Lattnerc7b13822009-10-24 05:27:19 +0000135 return false;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000136 }
137
138 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
139 const StructLayout *SL = TD.getStructLayout(CS->getType());
140 unsigned Index = SL->getElementContainingOffset(ByteOffset);
141 uint64_t CurEltOffset = SL->getElementOffset(Index);
142 ByteOffset -= CurEltOffset;
143
144 while (1) {
145 // If the element access is to the element itself and not to tail padding,
146 // read the bytes from the element.
147 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
148
149 if (ByteOffset < EltSize &&
150 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
151 BytesLeft, TD))
152 return false;
153
154 ++Index;
155
156 // Check to see if we read from the last struct element, if so we're done.
157 if (Index == CS->getType()->getNumElements())
158 return true;
159
160 // If we read all of the bytes we needed from this element we're done.
161 uint64_t NextEltOffset = SL->getElementOffset(Index);
162
163 if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
164 return true;
165
166 // Move to the next element of the struct.
Chris Lattnerc5af6492009-10-24 05:22:15 +0000167 CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000168 BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
169 ByteOffset = 0;
170 CurEltOffset = NextEltOffset;
171 }
172 // not reached.
173 }
174
175 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
176 uint64_t EltSize = TD.getTypeAllocSize(CA->getType()->getElementType());
177 uint64_t Index = ByteOffset / EltSize;
178 uint64_t Offset = ByteOffset - Index * EltSize;
179 for (; Index != CA->getType()->getNumElements(); ++Index) {
180 if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
181 BytesLeft, TD))
182 return false;
183 if (EltSize >= BytesLeft)
184 return true;
185
186 Offset = 0;
187 BytesLeft -= EltSize;
188 CurPtr += EltSize;
189 }
190 return true;
191 }
192
193 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
194 uint64_t EltSize = TD.getTypeAllocSize(CV->getType()->getElementType());
195 uint64_t Index = ByteOffset / EltSize;
196 uint64_t Offset = ByteOffset - Index * EltSize;
197 for (; Index != CV->getType()->getNumElements(); ++Index) {
198 if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
199 BytesLeft, TD))
200 return false;
201 if (EltSize >= BytesLeft)
202 return true;
203
204 Offset = 0;
205 BytesLeft -= EltSize;
206 CurPtr += EltSize;
207 }
208 return true;
209 }
210
211 // Otherwise, unknown initializer type.
212 return false;
213}
214
215static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
216 const TargetData &TD) {
Chris Lattner17f0cd32009-10-23 06:57:37 +0000217 const Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
218 const IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000219
220 // If this isn't an integer load we can't fold it directly.
221 if (!IntType) {
222 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattner17f0cd32009-10-23 06:57:37 +0000223 // and then bitcast the result. This can be useful for union cases. Note
224 // that address spaces don't matter here since we're not going to result in
225 // an actual new load.
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000226 const Type *MapTy;
Chris Lattner17f0cd32009-10-23 06:57:37 +0000227 if (LoadTy->isFloatTy())
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000228 MapTy = Type::getInt32PtrTy(C->getContext());
Chris Lattner17f0cd32009-10-23 06:57:37 +0000229 else if (LoadTy->isDoubleTy())
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000230 MapTy = Type::getInt64PtrTy(C->getContext());
Chris Lattner17f0cd32009-10-23 06:57:37 +0000231 else if (isa<VectorType>(LoadTy)) {
232 MapTy = IntegerType::get(C->getContext(),
233 TD.getTypeAllocSizeInBits(LoadTy));
234 MapTy = PointerType::getUnqual(MapTy);
235 } else
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000236 return 0;
237
238 C = ConstantExpr::getBitCast(C, MapTy);
239 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
Chris Lattner17f0cd32009-10-23 06:57:37 +0000240 return ConstantExpr::getBitCast(Res, LoadTy);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000241 return 0;
242 }
243
244 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Chris Lattner739208a2009-10-23 06:50:36 +0000245 if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000246
247 GlobalValue *GVal;
248 int64_t Offset;
249 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
250 return 0;
251
252 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattnerc7b13822009-10-24 05:27:19 +0000253 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000254 !GV->getInitializer()->getType()->isSized())
255 return 0;
256
257 // If we're loading off the beginning of the global, some bytes may be valid,
258 // but we don't try to handle this.
259 if (Offset < 0) return 0;
260
261 // If we're not accessing anything in this constant, the result is undefined.
262 if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
263 return UndefValue::get(IntType);
264
Chris Lattner739208a2009-10-23 06:50:36 +0000265 unsigned char RawBytes[32] = {0};
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000266 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
267 BytesLoaded, TD))
268 return 0;
269
Chris Lattner739208a2009-10-23 06:50:36 +0000270 APInt ResultVal(IntType->getBitWidth(), 0);
271 for (unsigned i = 0; i != BytesLoaded; ++i) {
272 ResultVal <<= 8;
273 ResultVal |= APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1-i]);
274 }
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000275
Chris Lattner739208a2009-10-23 06:50:36 +0000276 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000277}
278
Chris Lattner878e4942009-10-22 06:25:11 +0000279/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
280/// produce if it is constant and determinable. If this is not determinable,
281/// return null.
282Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
283 const TargetData *TD) {
284 // First, try the easy cases:
285 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
286 if (GV->isConstant() && GV->hasDefinitiveInitializer())
287 return GV->getInitializer();
288
Chris Lattnere00c43f2009-10-22 06:44:07 +0000289 // If the loaded value isn't a constant expr, we can't handle it.
290 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
291 if (!CE) return 0;
292
293 if (CE->getOpcode() == Instruction::GetElementPtr) {
294 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
295 if (GV->isConstant() && GV->hasDefinitiveInitializer())
296 if (Constant *V =
297 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
298 return V;
299 }
300
301 // Instead of loading constant c string, use corresponding integer value
302 // directly if string length is small enough.
303 std::string Str;
304 if (TD && GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000305 unsigned StrLen = Str.length();
Chris Lattnere00c43f2009-10-22 06:44:07 +0000306 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000307 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnere00c43f2009-10-22 06:44:07 +0000308 // Replace LI with immediate integer store.
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000309 if ((NumBits >> 3) == StrLen + 1) {
310 APInt StrVal(NumBits, 0);
311 APInt SingleChar(NumBits, 0);
Chris Lattnere00c43f2009-10-22 06:44:07 +0000312 if (TD->isLittleEndian()) {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000313 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnere00c43f2009-10-22 06:44:07 +0000314 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner62d327e2009-10-22 06:38:35 +0000315 StrVal = (StrVal << 8) | SingleChar;
316 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000317 } else {
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000318 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnere00c43f2009-10-22 06:44:07 +0000319 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
320 StrVal = (StrVal << 8) | SingleChar;
321 }
322 // Append NULL at the end.
323 SingleChar = 0;
324 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner62d327e2009-10-22 06:38:35 +0000325 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000326 return ConstantInt::get(CE->getContext(), StrVal);
Chris Lattner62d327e2009-10-22 06:38:35 +0000327 }
Chris Lattner878e4942009-10-22 06:25:11 +0000328 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000329
330 // If this load comes from anywhere in a constant global, and if the global
331 // is all undef or zero, we know what it loads.
332 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getUnderlyingObject())){
333 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
334 const Type *ResTy = cast<PointerType>(C->getType())->getElementType();
335 if (GV->getInitializer()->isNullValue())
336 return Constant::getNullValue(ResTy);
337 if (isa<UndefValue>(GV->getInitializer()))
338 return UndefValue::get(ResTy);
339 }
340 }
341
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000342 // Try hard to fold loads from bitcasted strange and non-type-safe things. We
343 // currently don't do any of this for big endian systems. It can be
344 // generalized in the future if someone is interested.
345 if (TD && TD->isLittleEndian())
346 return FoldReinterpretLoadFromConstPtr(CE, *TD);
Chris Lattner878e4942009-10-22 06:25:11 +0000347 return 0;
348}
349
350static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
351 if (LI->isVolatile()) return 0;
352
353 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
354 return ConstantFoldLoadFromConstPtr(C, TD);
Chris Lattnerfe8c7c82009-10-23 06:23:49 +0000355
Chris Lattner878e4942009-10-22 06:25:11 +0000356 return 0;
357}
Chris Lattner03dd25c2007-01-31 00:51:48 +0000358
359/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +0000360/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +0000361/// these together. If target data info is available, it is provided as TD,
362/// otherwise TD is null.
363static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +0000364 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +0000365 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +0000366 // SROA
367
368 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
369 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
370 // bits.
371
372
373 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
374 // constant. This happens frequently when iterating over a global array.
375 if (Opc == Instruction::Sub && TD) {
376 GlobalValue *GV1, *GV2;
377 int64_t Offs1, Offs2;
378
379 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
380 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
381 GV1 == GV2) {
382 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000383 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000384 }
385 }
386
Chris Lattner03dd25c2007-01-31 00:51:48 +0000387 return 0;
388}
389
390/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
391/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000392static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000393 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000394 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000395 const TargetData *TD) {
396 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000397 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000398 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000399
400 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
401 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000402 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000403 if (!Ptr->isNullValue()) {
404 // If this is a inttoptr from a constant int, we can fold this as the base,
405 // otherwise we can't.
406 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
407 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000408 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000409 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000410 BasePtr.zextOrTrunc(BitWidth);
411 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000412
413 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000414 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000415 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000416
417 // If this is a constant expr gep that is effectively computing an
418 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
419 for (unsigned i = 1; i != NumOps; ++i)
420 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000421 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000422
Dan Gohmancda97062009-08-21 16:52:54 +0000423 APInt Offset = APInt(BitWidth,
424 TD->getIndexedOffset(Ptr->getType(),
425 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000426 // If the base value for this address is a literal integer value, fold the
427 // getelementptr to the resulting integer value casted to the pointer type.
428 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000429 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000430 return ConstantExpr::getIntToPtr(C, ResultTy);
431 }
432
433 // Otherwise form a regular getelementptr. Recompute the indices so that
434 // we eliminate over-indexing of the notional static type array bounds.
435 // This makes it easy to determine if the getelementptr is "inbounds".
436 // Also, this helps GlobalOpt do SROA on GlobalVariables.
437 const Type *Ty = Ptr->getType();
438 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000439 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000440 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000441 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000442 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000443 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000444 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000445 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000446 if (ElemSize == 0)
447 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000448 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000449 Offset -= NewIdx * ElemSize;
450 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
451 Ty = ATy->getElementType();
452 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000453 // Determine which field of the struct the offset points into. The
454 // getZExtValue is at least as safe as the StructLayout API because we
455 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000456 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000457 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000458 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000459 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000460 Ty = STy->getTypeAtIndex(ElIdx);
461 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000462 // We've reached some non-indexable type.
463 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000464 }
Dan Gohman3d013342009-08-19 22:46:59 +0000465 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
466
467 // If we haven't used up the entire offset by descending the static
468 // type, then the offset is pointing into the middle of an indivisible
469 // member, so we can't simplify it.
470 if (Offset != 0)
471 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000472
Dan Gohman3bfbc452009-09-11 00:04:14 +0000473 // Create a GEP.
474 Constant *C =
Dan Gohman6e7ad952009-09-03 23:34:49 +0000475 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
476 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
477 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000478
Dan Gohman3d013342009-08-19 22:46:59 +0000479 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000480 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000481 if (Ty != cast<PointerType>(ResultTy)->getElementType())
482 C = ConstantExpr::getBitCast(C, ResultTy);
483
484 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000485}
486
Chris Lattner1afab9c2007-12-11 07:29:44 +0000487/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
488/// targetdata. Return 0 if unfoldable.
489static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000490 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000491 // If this is a bitcast from constant vector -> vector, fold it.
492 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
493 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
494 // If the element types match, VMCore can fold it.
495 unsigned NumDstElt = DestVTy->getNumElements();
496 unsigned NumSrcElt = CV->getNumOperands();
497 if (NumDstElt == NumSrcElt)
498 return 0;
499
500 const Type *SrcEltTy = CV->getType()->getElementType();
501 const Type *DstEltTy = DestVTy->getElementType();
502
503 // Otherwise, we're changing the number of elements in a vector, which
504 // requires endianness information to do the right thing. For example,
505 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
506 // folds to (little endian):
507 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
508 // and to (big endian):
509 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
510
511 // First thing is first. We only want to think about integer here, so if
512 // we have something in FP form, recast it as integer.
513 if (DstEltTy->isFloatingPoint()) {
514 // Fold to an vector of integers with same size as our FP type.
515 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000516 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000518 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000519 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000520 if (!C) return 0;
521
522 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000523 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000524 }
525
526 // Okay, we know the destination is integer, if the input is FP, convert
527 // it to integer first.
528 if (SrcEltTy->isFloatingPoint()) {
529 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000530 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000531 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000532 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000533 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000534 CV = dyn_cast<ConstantVector>(C);
535 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
536 }
537
538 // Now we know that the input and output vectors are both integer vectors
539 // of the same size, and that their #elements is not the same. Do the
540 // conversion here, which depends on whether the input or output has
541 // more elements.
542 bool isLittleEndian = TD.isLittleEndian();
543
544 SmallVector<Constant*, 32> Result;
545 if (NumDstElt < NumSrcElt) {
546 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000547 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000548 unsigned Ratio = NumSrcElt/NumDstElt;
549 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
550 unsigned SrcElt = 0;
551 for (unsigned i = 0; i != NumDstElt; ++i) {
552 // Build each element of the result.
553 Constant *Elt = Zero;
554 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
555 for (unsigned j = 0; j != Ratio; ++j) {
556 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
557 if (!Src) return 0; // Reject constantexpr elements.
558
559 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000560 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000561
562 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000563 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000564 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000565 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
566
567 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000568 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000569 }
570 Result.push_back(Elt);
571 }
572 } else {
573 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
574 unsigned Ratio = NumDstElt/NumSrcElt;
575 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
576
577 // Loop over each source value, expanding into multiple results.
578 for (unsigned i = 0; i != NumSrcElt; ++i) {
579 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
580 if (!Src) return 0; // Reject constantexpr elements.
581
582 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
583 for (unsigned j = 0; j != Ratio; ++j) {
584 // Shift the piece of the value into the right place, depending on
585 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000586 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000587 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000588 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
589
590 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000591 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000592 }
593 }
594 }
595
Owen Andersonaf7ec972009-07-28 21:19:26 +0000596 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000597 }
598 }
599
600 return 0;
601}
602
Chris Lattner03dd25c2007-01-31 00:51:48 +0000603
604//===----------------------------------------------------------------------===//
605// Constant Folding public APIs
606//===----------------------------------------------------------------------===//
607
608
Chris Lattner55207322007-01-30 23:45:45 +0000609/// ConstantFoldInstruction - Attempt to constant fold the specified
610/// instruction. If successful, the constant result is returned, if not, null
611/// is returned. Note that this function can only fail when attempting to fold
612/// instructions like loads and stores, which have no constant expression form.
613///
Owen Andersone922c022009-07-22 00:24:57 +0000614Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000615 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000616 if (PHINode *PN = dyn_cast<PHINode>(I)) {
617 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000618 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000619
Chris Lattner55207322007-01-30 23:45:45 +0000620 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
621 if (Result == 0) return 0;
622
623 // Handle PHI nodes specially here...
624 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
625 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
626 return 0; // Not all the same incoming constants...
627
628 // If we reach here, all incoming values are the same constant.
629 return Result;
630 }
631
632 // Scan the operand list, checking to see if they are all constants, if so,
633 // hand off to ConstantFoldInstOperands.
634 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000635 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
636 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000637 Ops.push_back(Op);
638 else
639 return 0; // All operands not constant!
640
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000641 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
642 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000643 Ops.data(), Ops.size(),
644 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000645
Chris Lattner878e4942009-10-22 06:25:11 +0000646 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
647 return ConstantFoldLoadInst(LI, TD);
648
Chris Lattner58665d42009-09-16 00:08:07 +0000649 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
650 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000651}
652
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000653/// ConstantFoldConstantExpression - Attempt to fold the constant expression
654/// using the specified TargetData. If successful, the constant result is
655/// result is returned, if not, null is returned.
656Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000657 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000658 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000659 SmallVector<Constant*, 8> Ops;
660 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
661 Ops.push_back(cast<Constant>(*i));
662
663 if (CE->isCompare())
664 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000665 Ops.data(), Ops.size(),
666 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000667 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
668 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000669}
670
Chris Lattner55207322007-01-30 23:45:45 +0000671/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
672/// specified opcode and operands. If successful, the constant result is
673/// returned, if not, null is returned. Note that this function can fail when
674/// attempting to fold instructions like loads and stores, which have no
675/// constant expression form.
676///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000677Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
678 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000679 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000680 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000681 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000682 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000683 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000684 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
685 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000686 return C;
687
Owen Andersonbaf3c402009-07-29 18:55:55 +0000688 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000689 }
Chris Lattner55207322007-01-30 23:45:45 +0000690
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000691 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000692 default: return 0;
693 case Instruction::Call:
694 if (Function *F = dyn_cast<Function>(Ops[0]))
695 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000696 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000697 return 0;
698 case Instruction::ICmp:
699 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000700 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000701 case Instruction::PtrToInt:
702 // If the input is a inttoptr, eliminate the pair. This requires knowing
703 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
704 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
705 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
706 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000707 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000708 if (TD->getPointerSizeInBits() < InWidth) {
709 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000710 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000711 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000712 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000713 }
Chris Lattner001f7532007-08-11 23:49:01 +0000714 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000715 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000716 }
717 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000718 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000719 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000720 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
721 // the int size is >= the ptr size. This requires knowing the width of a
722 // pointer, so it can't be done in ConstantExpr::getCast.
723 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000724 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000725 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000726 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000727 if (CE->getOpcode() == Instruction::PtrToInt) {
728 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000729 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000730 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000731 }
732 // If there's a constant offset added to the integer value before
733 // it is casted back to a pointer, see if the expression can be
734 // converted into a GEP.
735 if (CE->getOpcode() == Instruction::Add)
736 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
737 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
738 if (R->getOpcode() == Instruction::PtrToInt)
739 if (GlobalVariable *GV =
740 dyn_cast<GlobalVariable>(R->getOperand(0))) {
741 const PointerType *GVTy = cast<PointerType>(GV->getType());
742 if (const ArrayType *AT =
743 dyn_cast<ArrayType>(GVTy->getElementType())) {
744 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000745 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
746 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000747 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
748 L->getValue().urem(PSA) == 0) {
749 APInt ElemIdx = L->getValue().udiv(PSA);
750 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
751 AT->getNumElements()))) {
752 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000753 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000754 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000755 };
Owen Anderson50895512009-07-06 18:42:36 +0000756 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000757 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000758 }
759 }
760 }
761 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000762 }
763 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000764 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000765 case Instruction::Trunc:
766 case Instruction::ZExt:
767 case Instruction::SExt:
768 case Instruction::FPTrunc:
769 case Instruction::FPExt:
770 case Instruction::UIToFP:
771 case Instruction::SIToFP:
772 case Instruction::FPToUI:
773 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000774 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000775 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000776 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000777 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000778 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000779 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000780 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000781 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000782 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000783 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000784 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000785 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000786 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000787 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000788 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000789 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000790 return C;
791
Owen Andersonbaf3c402009-07-29 18:55:55 +0000792 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000793 }
794}
795
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000796/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
797/// instruction (icmp/fcmp) with the specified operands. If it fails, it
798/// returns a constant expression of the specified operands.
799///
800Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
801 Constant*const * Ops,
802 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000803 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000804 const TargetData *TD) {
805 // fold: icmp (inttoptr x), null -> icmp x, 0
806 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000807 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000808 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
809 //
810 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
811 // around to know if bit truncation is happening.
812 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
813 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000814 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000815 if (CE0->getOpcode() == Instruction::IntToPtr) {
816 // Convert the integer value to the right size to ensure we get the
817 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000818 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000819 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000820 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000821 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
822 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000823 }
824
825 // Only do this transformation if the int is intptrty in size, otherwise
826 // there is a truncation or extension that we aren't modeling.
827 if (CE0->getOpcode() == Instruction::PtrToInt &&
828 CE0->getType() == IntPtrTy) {
829 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000830 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000831 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000832 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
833 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000834 }
835 }
836
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000837 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
838 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000839 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000840
841 if (CE0->getOpcode() == Instruction::IntToPtr) {
842 // Convert the integer value to the right size to ensure we get the
843 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000844 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000845 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000846 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000847 IntPtrTy, false);
848 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000849 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
850 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000851 }
852
853 // Only do this transformation if the int is intptrty in size, otherwise
854 // there is a truncation or extension that we aren't modeling.
855 if ((CE0->getOpcode() == Instruction::PtrToInt &&
856 CE0->getType() == IntPtrTy &&
857 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
858 Constant *NewOps[] = {
859 CE0->getOperand(0), CE1->getOperand(0)
860 };
Owen Anderson50895512009-07-06 18:42:36 +0000861 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
862 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000863 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000864 }
865 }
866 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000867 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000868}
869
870
Chris Lattner55207322007-01-30 23:45:45 +0000871/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
872/// getelementptr constantexpr, return the constant value being addressed by the
873/// constant expression, or null if something is funny and we can't decide.
874Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000875 ConstantExpr *CE) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000876 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000877 return 0; // Do not allow stepping over the value!
878
879 // Loop over all of the operands, tracking down which value we are
880 // addressing...
881 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
882 for (++I; I != E; ++I)
883 if (const StructType *STy = dyn_cast<StructType>(*I)) {
884 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
885 assert(CU->getZExtValue() < STy->getNumElements() &&
886 "Struct index out of range!");
887 unsigned El = (unsigned)CU->getZExtValue();
888 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
889 C = CS->getOperand(El);
890 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000891 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000892 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000893 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000894 } else {
895 return 0;
896 }
897 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
898 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
899 if (CI->getZExtValue() >= ATy->getNumElements())
900 return 0;
901 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
902 C = CA->getOperand(CI->getZExtValue());
903 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000904 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000905 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000906 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000907 else
908 return 0;
Chris Lattner62d327e2009-10-22 06:38:35 +0000909 } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
910 if (CI->getZExtValue() >= VTy->getNumElements())
Chris Lattner55207322007-01-30 23:45:45 +0000911 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000912 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000913 C = CP->getOperand(CI->getZExtValue());
914 else if (isa<ConstantAggregateZero>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000915 C = Constant::getNullValue(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000916 else if (isa<UndefValue>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000917 C = UndefValue::get(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000918 else
919 return 0;
920 } else {
921 return 0;
922 }
923 } else {
924 return 0;
925 }
926 return C;
927}
928
929
930//===----------------------------------------------------------------------===//
931// Constant Folding for Calls
932//
John Criswellbd9d3702005-10-27 16:00:10 +0000933
934/// canConstantFoldCallTo - Return true if its even possible to fold a call to
935/// the specified function.
936bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000937llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000938 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000939 case Intrinsic::sqrt:
940 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000941 case Intrinsic::bswap:
942 case Intrinsic::ctpop:
943 case Intrinsic::ctlz:
944 case Intrinsic::cttz:
Chris Lattnere65cd402009-10-05 05:26:04 +0000945 case Intrinsic::uadd_with_overflow:
946 case Intrinsic::usub_with_overflow:
Evan Phoenix1614e502009-10-05 22:53:52 +0000947 case Intrinsic::sadd_with_overflow:
948 case Intrinsic::ssub_with_overflow:
John Criswellbd9d3702005-10-27 16:00:10 +0000949 return true;
Chris Lattner68a06032009-10-05 05:00:35 +0000950 default:
951 return false;
952 case 0: break;
John Criswellbd9d3702005-10-27 16:00:10 +0000953 }
954
Chris Lattner6f532a92009-04-03 00:02:39 +0000955 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000956 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000957
958 // In these cases, the check of the length is required. We don't want to
959 // return true for a name like "cos\0blah" which strcmp would return equal to
960 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000961 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000962 default: return false;
963 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000964 return Name == "acos" || Name == "asin" ||
965 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000966 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000967 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000968 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000969 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000970 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000971 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000972 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000973 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000974 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000975 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000976 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000977 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
978 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000979 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000980 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000981 }
982}
983
Chris Lattner72d88ae2007-01-30 23:15:43 +0000984static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000985 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000986 errno = 0;
987 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000988 if (errno != 0) {
989 errno = 0;
990 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000991 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000992
Chris Lattnerd0806a12009-10-05 05:06:24 +0000993 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000994 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000995 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000996 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000997 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000998 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000999}
1000
Dan Gohman38415242007-07-16 15:26:22 +00001001static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1002 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +00001003 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +00001004 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +00001005 errno = 0;
1006 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +00001007 if (errno != 0) {
1008 errno = 0;
1009 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +00001010 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +00001011
Chris Lattnerd0806a12009-10-05 05:06:24 +00001012 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001013 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +00001014 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001015 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +00001016 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +00001017 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +00001018}
1019
John Criswellbd9d3702005-10-27 16:00:10 +00001020/// ConstantFoldCall - Attempt to constant fold a call to the specified function
1021/// with the specified arguments, returning null if unsuccessful.
1022Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +00001023llvm::ConstantFoldCall(Function *F,
Chris Lattner68a06032009-10-05 05:00:35 +00001024 Constant *const *Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +00001025 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +00001026 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001027 StringRef Name = F->getName();
Chris Lattnere65cd402009-10-05 05:26:04 +00001028
John Criswellbd9d3702005-10-27 16:00:10 +00001029 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +00001030 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +00001031 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001032 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen43421b32007-09-06 18:13:44 +00001033 return 0;
1034 /// Currently APFloat versions of these functions do not exist, so we use
1035 /// the host native double versions. Float versions are not called
1036 /// directly but for all these it is true (float)(f((double)arg)) ==
1037 /// f(arg). Long double not supported yet.
Chris Lattnerd0806a12009-10-05 05:06:24 +00001038 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +00001039 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001040 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001041 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001042 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +00001043 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001044 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +00001045 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001046 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +00001047 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001048 break;
1049 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001050 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +00001051 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001052 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +00001053 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001054 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +00001055 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001056 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +00001057 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001058 break;
1059 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001060 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +00001061 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001062 break;
1063 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001064 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +00001065 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001066 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +00001067 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001068 break;
1069 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001070 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +00001071 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001072 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +00001073 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001074 else if (Name == "llvm.sqrt.f32" ||
1075 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001076 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +00001077 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001078 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +00001079 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001080 }
1081 break;
1082 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001083 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +00001084 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001085 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +00001086 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001087 else if (Name == "sqrt" && 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 == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +00001090 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001091 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +00001092 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001093 break;
1094 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001095 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +00001096 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001097 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +00001098 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +00001099 break;
1100 default:
1101 break;
John Criswellbd9d3702005-10-27 16:00:10 +00001102 }
Chris Lattner68a06032009-10-05 05:00:35 +00001103 return 0;
1104 }
1105
1106
1107 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001108 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001109 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001110 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001111 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001112 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001113 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001114 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +00001115 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Chris Lattner68a06032009-10-05 05:00:35 +00001116 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001117 }
Chris Lattner68a06032009-10-05 05:00:35 +00001118
1119 return 0;
1120 }
1121
1122 if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +00001123 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001124 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00001125 return 0;
Chris Lattnerd0806a12009-10-05 05:06:24 +00001126 double Op1V = Ty->isFloatTy() ?
1127 (double)Op1->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +00001128 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +00001129 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +00001130 if (Op2->getType() != Op1->getType())
1131 return 0;
1132
1133 double Op2V = Ty->isFloatTy() ?
Dale Johannesen43421b32007-09-06 18:13:44 +00001134 (double)Op2->getValueAPF().convertToFloat():
1135 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +00001136
Chris Lattner68a06032009-10-05 05:00:35 +00001137 if (Name == "pow")
Owen Anderson50895512009-07-06 18:42:36 +00001138 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +00001139 if (Name == "fmod")
Owen Anderson50895512009-07-06 18:42:36 +00001140 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +00001141 if (Name == "atan2")
Owen Anderson50895512009-07-06 18:42:36 +00001142 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +00001143 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattner68a06032009-10-05 05:00:35 +00001144 if (Name == "llvm.powi.f32")
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001145 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +00001146 (int)Op2C->getZExtValue())));
Chris Lattner68a06032009-10-05 05:00:35 +00001147 if (Name == "llvm.powi.f64")
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001148 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +00001149 (int)Op2C->getZExtValue())));
John Criswellbd9d3702005-10-27 16:00:10 +00001150 }
Chris Lattner68a06032009-10-05 05:00:35 +00001151 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001152 }
Chris Lattnere65cd402009-10-05 05:26:04 +00001153
1154
1155 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1156 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1157 switch (F->getIntrinsicID()) {
1158 default: break;
1159 case Intrinsic::uadd_with_overflow: {
1160 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
1161 Constant *Ops[] = {
1162 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
1163 };
1164 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1165 }
1166 case Intrinsic::usub_with_overflow: {
1167 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
1168 Constant *Ops[] = {
1169 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
1170 };
1171 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1172 }
Evan Phoenix1614e502009-10-05 22:53:52 +00001173 case Intrinsic::sadd_with_overflow: {
1174 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
1175 Constant *Overflow = ConstantExpr::getSelect(
1176 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1177 ConstantInt::get(Op1->getType(), 0), Op1),
1178 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
1179 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
1180
1181 Constant *Ops[] = { Res, Overflow };
1182 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1183 }
1184 case Intrinsic::ssub_with_overflow: {
1185 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
1186 Constant *Overflow = ConstantExpr::getSelect(
1187 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1188 ConstantInt::get(Op2->getType(), 0), Op2),
1189 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
1190 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
1191
1192 Constant *Ops[] = { Res, Overflow };
1193 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1194 }
Chris Lattnere65cd402009-10-05 05:26:04 +00001195 }
1196 }
1197
1198 return 0;
1199 }
1200 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001201 }
1202 return 0;
1203}
1204