blob: ffdc52ce743b0329e43472220f0dfae9ae6f9a7f [file] [log] [blame]
John Criswellbd9d3702005-10-27 16:00:10 +00001//===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
2//
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//
10// This family of functions determines the possibility of performing constant
11// folding.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ConstantFolding.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
Chris Lattner55207322007-01-30 23:45:45 +000018#include "llvm/Function.h"
Dan Gohman9a38e3e2009-05-07 19:46:24 +000019#include "llvm/GlobalVariable.h"
John Criswellbd9d3702005-10-27 16:00:10 +000020#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
Owen Anderson50895512009-07-06 18:42:36 +000022#include "llvm/LLVMContext.h"
Chris Lattner55207322007-01-30 23:45:45 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000024#include "llvm/ADT/StringMap.h"
Chris Lattner03dd25c2007-01-31 00:51:48 +000025#include "llvm/Target/TargetData.h"
John Criswellbd9d3702005-10-27 16:00:10 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
27#include "llvm/Support/MathExtras.h"
28#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000029#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000030using namespace llvm;
31
Chris Lattner03dd25c2007-01-31 00:51:48 +000032//===----------------------------------------------------------------------===//
33// Constant Folding internal helper functions
34//===----------------------------------------------------------------------===//
35
36/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
37/// from a global, return the global and the constant. Because of
38/// constantexprs, this function is recursive.
39static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
40 int64_t &Offset, const TargetData &TD) {
41 // Trivial case, constant is the global.
42 if ((GV = dyn_cast<GlobalValue>(C))) {
43 Offset = 0;
44 return true;
45 }
46
47 // Otherwise, if this isn't a constant expr, bail out.
48 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
49 if (!CE) return false;
50
51 // Look through ptr->int and ptr->ptr casts.
52 if (CE->getOpcode() == Instruction::PtrToInt ||
53 CE->getOpcode() == Instruction::BitCast)
54 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
55
56 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
57 if (CE->getOpcode() == Instruction::GetElementPtr) {
58 // Cannot compute this if the element type of the pointer is missing size
59 // info.
Chris Lattnerf286f6f2007-12-10 22:53:04 +000060 if (!cast<PointerType>(CE->getOperand(0)->getType())
61 ->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +000062 return false;
63
64 // If the base isn't a global+constant, we aren't either.
65 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
66 return false;
67
68 // Otherwise, add any offset that our operands provide.
69 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifde2d74b2008-05-22 06:43:33 +000070 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greif785c6af2008-05-22 19:24:54 +000071 i != e; ++i, ++GTI) {
Gabor Greifde2d74b2008-05-22 06:43:33 +000072 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Chris Lattner03dd25c2007-01-31 00:51:48 +000073 if (!CI) return false; // Index isn't a simple constant?
74 if (CI->getZExtValue() == 0) continue; // Not adding anything.
75
76 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
77 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000078 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000079 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000080 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands777d2302009-05-09 07:06:46 +000081 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000082 }
83 }
84 return true;
85 }
86
87 return false;
88}
89
90
91/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +000092/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +000093/// these together. If target data info is available, it is provided as TD,
94/// otherwise TD is null.
95static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +000096 Constant *Op1, const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +000097 LLVMContext *Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +000098 // SROA
99
100 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
101 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
102 // bits.
103
104
105 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
106 // constant. This happens frequently when iterating over a global array.
107 if (Opc == Instruction::Sub && TD) {
108 GlobalValue *GV1, *GV2;
109 int64_t Offs1, Offs2;
110
111 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
112 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
113 GV1 == GV2) {
114 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Anderson50895512009-07-06 18:42:36 +0000115 return Context->getConstantInt(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000116 }
117 }
118
Chris Lattner03dd25c2007-01-31 00:51:48 +0000119 return 0;
120}
121
122/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
123/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000124static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000125 const Type *ResultTy,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000126 LLVMContext *Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000127 const TargetData *TD) {
128 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000129 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000130 return 0;
131
Chris Lattner268e7d72008-05-08 04:54:43 +0000132 uint64_t BasePtr = 0;
133 if (!Ptr->isNullValue()) {
134 // If this is a inttoptr from a constant int, we can fold this as the base,
135 // otherwise we can't.
136 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
137 if (CE->getOpcode() == Instruction::IntToPtr)
138 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
139 BasePtr = Base->getZExtValue();
140
141 if (BasePtr == 0)
142 return 0;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000143 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000144
145 // If this is a constant expr gep that is effectively computing an
146 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
147 for (unsigned i = 1; i != NumOps; ++i)
148 if (!isa<ConstantInt>(Ops[i]))
149 return false;
150
151 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
152 (Value**)Ops+1, NumOps-1);
Owen Anderson50895512009-07-06 18:42:36 +0000153 Constant *C = Context->getConstantInt(TD->getIntPtrType(), Offset+BasePtr);
154 return Context->getConstantExprIntToPtr(C, ResultTy);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000155}
156
Chris Lattner1afab9c2007-12-11 07:29:44 +0000157/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
158/// targetdata. Return 0 if unfoldable.
159static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000160 const TargetData &TD, LLVMContext *Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000161 // If this is a bitcast from constant vector -> vector, fold it.
162 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
163 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
164 // If the element types match, VMCore can fold it.
165 unsigned NumDstElt = DestVTy->getNumElements();
166 unsigned NumSrcElt = CV->getNumOperands();
167 if (NumDstElt == NumSrcElt)
168 return 0;
169
170 const Type *SrcEltTy = CV->getType()->getElementType();
171 const Type *DstEltTy = DestVTy->getElementType();
172
173 // Otherwise, we're changing the number of elements in a vector, which
174 // requires endianness information to do the right thing. For example,
175 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
176 // folds to (little endian):
177 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
178 // and to (big endian):
179 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
180
181 // First thing is first. We only want to think about integer here, so if
182 // we have something in FP form, recast it as integer.
183 if (DstEltTy->isFloatingPoint()) {
184 // Fold to an vector of integers with same size as our FP type.
185 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Anderson50895512009-07-06 18:42:36 +0000186 const Type *DestIVTy = Context->getVectorType(
187 Context->getIntegerType(FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000188 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000189 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000190 if (!C) return 0;
191
192 // Finally, VMCore can handle this now that #elts line up.
Owen Anderson50895512009-07-06 18:42:36 +0000193 return Context->getConstantExprBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000194 }
195
196 // Okay, we know the destination is integer, if the input is FP, convert
197 // it to integer first.
198 if (SrcEltTy->isFloatingPoint()) {
199 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Anderson50895512009-07-06 18:42:36 +0000200 const Type *SrcIVTy = Context->getVectorType(
201 Context->getIntegerType(FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000202 // Ask VMCore to do the conversion now that #elts line up.
Owen Anderson50895512009-07-06 18:42:36 +0000203 C = Context->getConstantExprBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000204 CV = dyn_cast<ConstantVector>(C);
205 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
206 }
207
208 // Now we know that the input and output vectors are both integer vectors
209 // of the same size, and that their #elements is not the same. Do the
210 // conversion here, which depends on whether the input or output has
211 // more elements.
212 bool isLittleEndian = TD.isLittleEndian();
213
214 SmallVector<Constant*, 32> Result;
215 if (NumDstElt < NumSrcElt) {
216 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Anderson50895512009-07-06 18:42:36 +0000217 Constant *Zero = Context->getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000218 unsigned Ratio = NumSrcElt/NumDstElt;
219 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
220 unsigned SrcElt = 0;
221 for (unsigned i = 0; i != NumDstElt; ++i) {
222 // Build each element of the result.
223 Constant *Elt = Zero;
224 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
225 for (unsigned j = 0; j != Ratio; ++j) {
226 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
227 if (!Src) return 0; // Reject constantexpr elements.
228
229 // Zero extend the element to the right size.
Owen Anderson50895512009-07-06 18:42:36 +0000230 Src = Context->getConstantExprZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000231
232 // Shift it to the right place, depending on endianness.
Owen Anderson50895512009-07-06 18:42:36 +0000233 Src = Context->getConstantExprShl(Src,
234 Context->getConstantInt(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000235 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
236
237 // Mix it in.
Owen Anderson50895512009-07-06 18:42:36 +0000238 Elt = Context->getConstantExprOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000239 }
240 Result.push_back(Elt);
241 }
242 } else {
243 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
244 unsigned Ratio = NumDstElt/NumSrcElt;
245 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
246
247 // Loop over each source value, expanding into multiple results.
248 for (unsigned i = 0; i != NumSrcElt; ++i) {
249 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
250 if (!Src) return 0; // Reject constantexpr elements.
251
252 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
253 for (unsigned j = 0; j != Ratio; ++j) {
254 // Shift the piece of the value into the right place, depending on
255 // endianness.
Owen Anderson50895512009-07-06 18:42:36 +0000256 Constant *Elt = Context->getConstantExprLShr(Src,
257 Context->getConstantInt(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000258 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
259
260 // Truncate and remember this piece.
Owen Anderson50895512009-07-06 18:42:36 +0000261 Result.push_back(Context->getConstantExprTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000262 }
263 }
264 }
265
Owen Anderson50895512009-07-06 18:42:36 +0000266 return Context->getConstantVector(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000267 }
268 }
269
270 return 0;
271}
272
Chris Lattner03dd25c2007-01-31 00:51:48 +0000273
274//===----------------------------------------------------------------------===//
275// Constant Folding public APIs
276//===----------------------------------------------------------------------===//
277
278
Chris Lattner55207322007-01-30 23:45:45 +0000279/// ConstantFoldInstruction - Attempt to constant fold the specified
280/// instruction. If successful, the constant result is returned, if not, null
281/// is returned. Note that this function can only fail when attempting to fold
282/// instructions like loads and stores, which have no constant expression form.
283///
Owen Anderson07cf79e2009-07-06 23:00:19 +0000284Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext *Context,
Owen Anderson50895512009-07-06 18:42:36 +0000285 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000286 if (PHINode *PN = dyn_cast<PHINode>(I)) {
287 if (PN->getNumIncomingValues() == 0)
Owen Anderson50895512009-07-06 18:42:36 +0000288 return Context->getUndef(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000289
Chris Lattner55207322007-01-30 23:45:45 +0000290 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
291 if (Result == 0) return 0;
292
293 // Handle PHI nodes specially here...
294 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
295 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
296 return 0; // Not all the same incoming constants...
297
298 // If we reach here, all incoming values are the same constant.
299 return Result;
300 }
301
302 // Scan the operand list, checking to see if they are all constants, if so,
303 // hand off to ConstantFoldInstOperands.
304 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000305 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
306 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000307 Ops.push_back(Op);
308 else
309 return 0; // All operands not constant!
310
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000311 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
312 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000313 Ops.data(), Ops.size(),
314 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000315 else
316 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +0000317 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000318}
319
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000320/// ConstantFoldConstantExpression - Attempt to fold the constant expression
321/// using the specified TargetData. If successful, the constant result is
322/// result is returned, if not, null is returned.
323Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000324 LLVMContext *Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000325 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000326 SmallVector<Constant*, 8> Ops;
327 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
328 Ops.push_back(cast<Constant>(*i));
329
330 if (CE->isCompare())
331 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000332 Ops.data(), Ops.size(),
333 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000334 else
335 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
Owen Anderson50895512009-07-06 18:42:36 +0000336 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000337}
338
Chris Lattner55207322007-01-30 23:45:45 +0000339/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
340/// specified opcode and operands. If successful, the constant result is
341/// returned, if not, null is returned. Note that this function can fail when
342/// attempting to fold instructions like loads and stores, which have no
343/// constant expression form.
344///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000345Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
346 Constant* const* Ops, unsigned NumOps,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000347 LLVMContext *Context,
Chris Lattner55207322007-01-30 23:45:45 +0000348 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000349 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000350 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000351 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000352 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
353 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000354 return C;
355
Owen Anderson50895512009-07-06 18:42:36 +0000356 return Context->getConstantExpr(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000357 }
Chris Lattner55207322007-01-30 23:45:45 +0000358
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000359 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000360 default: return 0;
361 case Instruction::Call:
362 if (Function *F = dyn_cast<Function>(Ops[0]))
363 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000364 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000365 return 0;
366 case Instruction::ICmp:
367 case Instruction::FCmp:
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000368 assert(0 &&"This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000369 case Instruction::PtrToInt:
370 // If the input is a inttoptr, eliminate the pair. This requires knowing
371 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
373 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
374 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000375 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000376 if (TD->getPointerSizeInBits() < InWidth) {
377 Constant *Mask =
Owen Anderson50895512009-07-06 18:42:36 +0000378 Context->getConstantInt(APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000379 TD->getPointerSizeInBits()));
Owen Anderson50895512009-07-06 18:42:36 +0000380 Input = Context->getConstantExprAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000381 }
Chris Lattner001f7532007-08-11 23:49:01 +0000382 // Do a zext or trunc to get to the dest size.
Owen Anderson50895512009-07-06 18:42:36 +0000383 return Context->getConstantExprIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000384 }
385 }
Owen Anderson50895512009-07-06 18:42:36 +0000386 return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000387 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000388 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
389 // the int size is >= the ptr size. This requires knowing the width of a
390 // pointer, so it can't be done in ConstantExpr::getCast.
391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000392 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000393 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000394 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000395 if (CE->getOpcode() == Instruction::PtrToInt) {
396 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000397 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
398 return C ? C : Context->getConstantExprBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000399 }
400 // If there's a constant offset added to the integer value before
401 // it is casted back to a pointer, see if the expression can be
402 // converted into a GEP.
403 if (CE->getOpcode() == Instruction::Add)
404 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
405 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
406 if (R->getOpcode() == Instruction::PtrToInt)
407 if (GlobalVariable *GV =
408 dyn_cast<GlobalVariable>(R->getOperand(0))) {
409 const PointerType *GVTy = cast<PointerType>(GV->getType());
410 if (const ArrayType *AT =
411 dyn_cast<ArrayType>(GVTy->getElementType())) {
412 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000413 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
414 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000415 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
416 L->getValue().urem(PSA) == 0) {
417 APInt ElemIdx = L->getValue().udiv(PSA);
418 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
419 AT->getNumElements()))) {
420 Constant *Index[] = {
Owen Anderson50895512009-07-06 18:42:36 +0000421 Context->getNullValue(CE->getType()),
422 Context->getConstantInt(ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000423 };
Owen Anderson50895512009-07-06 18:42:36 +0000424 return
425 Context->getConstantExprGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000426 }
427 }
428 }
429 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000430 }
431 }
Owen Anderson50895512009-07-06 18:42:36 +0000432 return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000433 case Instruction::Trunc:
434 case Instruction::ZExt:
435 case Instruction::SExt:
436 case Instruction::FPTrunc:
437 case Instruction::FPExt:
438 case Instruction::UIToFP:
439 case Instruction::SIToFP:
440 case Instruction::FPToUI:
441 case Instruction::FPToSI:
Owen Anderson50895512009-07-06 18:42:36 +0000442 return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000443 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000444 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000445 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000446 return C;
Owen Anderson50895512009-07-06 18:42:36 +0000447 return Context->getConstantExprBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000448 case Instruction::Select:
Owen Anderson50895512009-07-06 18:42:36 +0000449 return Context->getConstantExprSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000450 case Instruction::ExtractElement:
Owen Anderson50895512009-07-06 18:42:36 +0000451 return Context->getConstantExprExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000452 case Instruction::InsertElement:
Owen Anderson50895512009-07-06 18:42:36 +0000453 return Context->getConstantExprInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000454 case Instruction::ShuffleVector:
Owen Anderson50895512009-07-06 18:42:36 +0000455 return Context->getConstantExprShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000456 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000457 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000458 return C;
459
Owen Anderson50895512009-07-06 18:42:36 +0000460 return Context->getConstantExprGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000461 }
462}
463
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000464/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
465/// instruction (icmp/fcmp) with the specified operands. If it fails, it
466/// returns a constant expression of the specified operands.
467///
468Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
469 Constant*const * Ops,
470 unsigned NumOps,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000471 LLVMContext *Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000472 const TargetData *TD) {
473 // fold: icmp (inttoptr x), null -> icmp x, 0
474 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000475 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000476 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
477 //
478 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
479 // around to know if bit truncation is happening.
480 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
481 if (TD && Ops[1]->isNullValue()) {
482 const Type *IntPtrTy = TD->getIntPtrType();
483 if (CE0->getOpcode() == Instruction::IntToPtr) {
484 // Convert the integer value to the right size to ensure we get the
485 // proper extension or truncation.
Owen Anderson50895512009-07-06 18:42:36 +0000486 Constant *C = Context->getConstantExprIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000487 IntPtrTy, false);
Owen Anderson50895512009-07-06 18:42:36 +0000488 Constant *NewOps[] = { C, Context->getNullValue(C->getType()) };
489 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
490 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000491 }
492
493 // Only do this transformation if the int is intptrty in size, otherwise
494 // there is a truncation or extension that we aren't modeling.
495 if (CE0->getOpcode() == Instruction::PtrToInt &&
496 CE0->getType() == IntPtrTy) {
497 Constant *C = CE0->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000498 Constant *NewOps[] = { C, Context->getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000499 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000500 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
501 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000502 }
503 }
504
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000505 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
506 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
507 const Type *IntPtrTy = TD->getIntPtrType();
508
509 if (CE0->getOpcode() == Instruction::IntToPtr) {
510 // Convert the integer value to the right size to ensure we get the
511 // proper extension or truncation.
Owen Anderson50895512009-07-06 18:42:36 +0000512 Constant *C0 = Context->getConstantExprIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000513 IntPtrTy, false);
Owen Anderson50895512009-07-06 18:42:36 +0000514 Constant *C1 = Context->getConstantExprIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000515 IntPtrTy, false);
516 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000517 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
518 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000519 }
520
521 // Only do this transformation if the int is intptrty in size, otherwise
522 // there is a truncation or extension that we aren't modeling.
523 if ((CE0->getOpcode() == Instruction::PtrToInt &&
524 CE0->getType() == IntPtrTy &&
525 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
526 Constant *NewOps[] = {
527 CE0->getOperand(0), CE1->getOperand(0)
528 };
Owen Anderson50895512009-07-06 18:42:36 +0000529 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
530 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000531 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000532 }
533 }
534 }
Owen Anderson50895512009-07-06 18:42:36 +0000535 return Context->getConstantExprCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000536}
537
538
Chris Lattner55207322007-01-30 23:45:45 +0000539/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
540/// getelementptr constantexpr, return the constant value being addressed by the
541/// constant expression, or null if something is funny and we can't decide.
542Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Owen Anderson50895512009-07-06 18:42:36 +0000543 ConstantExpr *CE,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000544 LLVMContext *Context) {
Owen Anderson50895512009-07-06 18:42:36 +0000545 if (CE->getOperand(1) != Context->getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000546 return 0; // Do not allow stepping over the value!
547
548 // Loop over all of the operands, tracking down which value we are
549 // addressing...
550 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
551 for (++I; I != E; ++I)
552 if (const StructType *STy = dyn_cast<StructType>(*I)) {
553 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
554 assert(CU->getZExtValue() < STy->getNumElements() &&
555 "Struct index out of range!");
556 unsigned El = (unsigned)CU->getZExtValue();
557 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
558 C = CS->getOperand(El);
559 } else if (isa<ConstantAggregateZero>(C)) {
Owen Anderson50895512009-07-06 18:42:36 +0000560 C = Context->getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000561 } else if (isa<UndefValue>(C)) {
Owen Anderson50895512009-07-06 18:42:36 +0000562 C = Context->getUndef(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000563 } else {
564 return 0;
565 }
566 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
567 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
568 if (CI->getZExtValue() >= ATy->getNumElements())
569 return 0;
570 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
571 C = CA->getOperand(CI->getZExtValue());
572 else if (isa<ConstantAggregateZero>(C))
Owen Anderson50895512009-07-06 18:42:36 +0000573 C = Context->getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000574 else if (isa<UndefValue>(C))
Owen Anderson50895512009-07-06 18:42:36 +0000575 C = Context->getUndef(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000576 else
577 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000578 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
Chris Lattner55207322007-01-30 23:45:45 +0000579 if (CI->getZExtValue() >= PTy->getNumElements())
580 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000581 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000582 C = CP->getOperand(CI->getZExtValue());
583 else if (isa<ConstantAggregateZero>(C))
Owen Anderson50895512009-07-06 18:42:36 +0000584 C = Context->getNullValue(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000585 else if (isa<UndefValue>(C))
Owen Anderson50895512009-07-06 18:42:36 +0000586 C = Context->getUndef(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000587 else
588 return 0;
589 } else {
590 return 0;
591 }
592 } else {
593 return 0;
594 }
595 return C;
596}
597
598
599//===----------------------------------------------------------------------===//
600// Constant Folding for Calls
601//
John Criswellbd9d3702005-10-27 16:00:10 +0000602
603/// canConstantFoldCallTo - Return true if its even possible to fold a call to
604/// the specified function.
605bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000606llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000607 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000608 case Intrinsic::sqrt:
609 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000610 case Intrinsic::bswap:
611 case Intrinsic::ctpop:
612 case Intrinsic::ctlz:
613 case Intrinsic::cttz:
John Criswellbd9d3702005-10-27 16:00:10 +0000614 return true;
615 default: break;
616 }
617
Chris Lattner6f532a92009-04-03 00:02:39 +0000618 if (!F->hasName()) return false;
619 const char *Str = F->getNameStart();
620 unsigned Len = F->getNameLen();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000621
622 // In these cases, the check of the length is required. We don't want to
623 // return true for a name like "cos\0blah" which strcmp would return equal to
624 // "cos", but has length 8.
625 switch (Str[0]) {
626 default: return false;
627 case 'a':
628 if (Len == 4)
629 return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
630 !strcmp(Str, "atan");
631 else if (Len == 5)
632 return !strcmp(Str, "atan2");
633 return false;
634 case 'c':
635 if (Len == 3)
636 return !strcmp(Str, "cos");
637 else if (Len == 4)
638 return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
639 !strcmp(Str, "cosh");
640 return false;
641 case 'e':
642 if (Len == 3)
643 return !strcmp(Str, "exp");
644 return false;
645 case 'f':
646 if (Len == 4)
647 return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
648 else if (Len == 5)
649 return !strcmp(Str, "floor");
650 return false;
651 break;
652 case 'l':
653 if (Len == 3 && !strcmp(Str, "log"))
654 return true;
655 if (Len == 5 && !strcmp(Str, "log10"))
656 return true;
657 return false;
658 case 'p':
659 if (Len == 3 && !strcmp(Str, "pow"))
660 return true;
661 return false;
662 case 's':
663 if (Len == 3)
664 return !strcmp(Str, "sin");
665 if (Len == 4)
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000666 return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
667 !strcmp(Str, "sinf");
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000668 if (Len == 5)
669 return !strcmp(Str, "sqrtf");
670 return false;
671 case 't':
672 if (Len == 3 && !strcmp(Str, "tan"))
673 return true;
674 else if (Len == 4 && !strcmp(Str, "tanh"))
675 return true;
676 return false;
John Criswellbd9d3702005-10-27 16:00:10 +0000677 }
678}
679
Chris Lattner72d88ae2007-01-30 23:15:43 +0000680static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000681 const Type *Ty, LLVMContext *Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000682 errno = 0;
683 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000684 if (errno != 0) {
685 errno = 0;
686 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000687 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000688
689 if (Ty == Type::FloatTy)
Owen Anderson50895512009-07-06 18:42:36 +0000690 return Context->getConstantFP(APFloat((float)V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000691 if (Ty == Type::DoubleTy)
Owen Anderson50895512009-07-06 18:42:36 +0000692 return Context->getConstantFP(APFloat(V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000693 assert(0 && "Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000694 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000695}
696
Dan Gohman38415242007-07-16 15:26:22 +0000697static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
698 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +0000699 const Type *Ty,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000700 LLVMContext *Context) {
Dan Gohman38415242007-07-16 15:26:22 +0000701 errno = 0;
702 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000703 if (errno != 0) {
704 errno = 0;
705 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000706 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000707
708 if (Ty == Type::FloatTy)
Owen Anderson50895512009-07-06 18:42:36 +0000709 return Context->getConstantFP(APFloat((float)V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000710 if (Ty == Type::DoubleTy)
Owen Anderson50895512009-07-06 18:42:36 +0000711 return Context->getConstantFP(APFloat(V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000712 assert(0 && "Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000713 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000714}
715
John Criswellbd9d3702005-10-27 16:00:10 +0000716/// ConstantFoldCall - Attempt to constant fold a call to the specified function
717/// with the specified arguments, returning null if unsuccessful.
Dale Johannesen43421b32007-09-06 18:13:44 +0000718
John Criswellbd9d3702005-10-27 16:00:10 +0000719Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000720llvm::ConstantFoldCall(Function *F,
721 Constant* const* Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +0000722 if (!F->hasName()) return 0;
Owen Anderson07cf79e2009-07-06 23:00:19 +0000723 LLVMContext *Context = F->getContext();
Chris Lattner6f532a92009-04-03 00:02:39 +0000724 const char *Str = F->getNameStart();
725 unsigned Len = F->getNameLen();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000726
John Criswellbd9d3702005-10-27 16:00:10 +0000727 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000728 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000729 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Dale Johannesen43421b32007-09-06 18:13:44 +0000730 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
731 return 0;
732 /// Currently APFloat versions of these functions do not exist, so we use
733 /// the host native double versions. Float versions are not called
734 /// directly but for all these it is true (float)(f((double)arg)) ==
735 /// f(arg). Long double not supported yet.
736 double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
737 Op->getValueAPF().convertToDouble();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000738 switch (Str[0]) {
739 case 'a':
740 if (Len == 4 && !strcmp(Str, "acos"))
Owen Anderson50895512009-07-06 18:42:36 +0000741 return ConstantFoldFP(acos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000742 else if (Len == 4 && !strcmp(Str, "asin"))
Owen Anderson50895512009-07-06 18:42:36 +0000743 return ConstantFoldFP(asin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000744 else if (Len == 4 && !strcmp(Str, "atan"))
Owen Anderson50895512009-07-06 18:42:36 +0000745 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000746 break;
747 case 'c':
748 if (Len == 4 && !strcmp(Str, "ceil"))
Owen Anderson50895512009-07-06 18:42:36 +0000749 return ConstantFoldFP(ceil, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000750 else if (Len == 3 && !strcmp(Str, "cos"))
Owen Anderson50895512009-07-06 18:42:36 +0000751 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000752 else if (Len == 4 && !strcmp(Str, "cosh"))
Owen Anderson50895512009-07-06 18:42:36 +0000753 return ConstantFoldFP(cosh, V, Ty, Context);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000754 else if (Len == 4 && !strcmp(Str, "cosf"))
Owen Anderson50895512009-07-06 18:42:36 +0000755 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000756 break;
757 case 'e':
758 if (Len == 3 && !strcmp(Str, "exp"))
Owen Anderson50895512009-07-06 18:42:36 +0000759 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000760 break;
761 case 'f':
762 if (Len == 4 && !strcmp(Str, "fabs"))
Owen Anderson50895512009-07-06 18:42:36 +0000763 return ConstantFoldFP(fabs, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000764 else if (Len == 5 && !strcmp(Str, "floor"))
Owen Anderson50895512009-07-06 18:42:36 +0000765 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000766 break;
767 case 'l':
768 if (Len == 3 && !strcmp(Str, "log") && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000769 return ConstantFoldFP(log, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000770 else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000771 return ConstantFoldFP(log10, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000772 else if (!strcmp(Str, "llvm.sqrt.f32") ||
773 !strcmp(Str, "llvm.sqrt.f64")) {
774 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +0000775 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000776 else // Undefined
Owen Anderson50895512009-07-06 18:42:36 +0000777 return Context->getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000778 }
779 break;
780 case 's':
781 if (Len == 3 && !strcmp(Str, "sin"))
Owen Anderson50895512009-07-06 18:42:36 +0000782 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000783 else if (Len == 4 && !strcmp(Str, "sinh"))
Owen Anderson50895512009-07-06 18:42:36 +0000784 return ConstantFoldFP(sinh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000785 else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000786 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000787 else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000788 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000789 else if (Len == 4 && !strcmp(Str, "sinf"))
Owen Anderson50895512009-07-06 18:42:36 +0000790 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000791 break;
792 case 't':
793 if (Len == 3 && !strcmp(Str, "tan"))
Owen Anderson50895512009-07-06 18:42:36 +0000794 return ConstantFoldFP(tan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000795 else if (Len == 4 && !strcmp(Str, "tanh"))
Owen Anderson50895512009-07-06 18:42:36 +0000796 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000797 break;
798 default:
799 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000800 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000801 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Chris Lattnerecc02742007-11-23 22:34:59 +0000802 if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
Owen Anderson50895512009-07-06 18:42:36 +0000803 return Context->getConstantInt(Op->getValue().byteSwap());
Chris Lattnerecc02742007-11-23 22:34:59 +0000804 else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
Owen Anderson50895512009-07-06 18:42:36 +0000805 return Context->getConstantInt(Ty, Op->getValue().countPopulation());
Chris Lattnerecc02742007-11-23 22:34:59 +0000806 else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
Owen Anderson50895512009-07-06 18:42:36 +0000807 return Context->getConstantInt(Ty, Op->getValue().countTrailingZeros());
Chris Lattnerecc02742007-11-23 22:34:59 +0000808 else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
Owen Anderson50895512009-07-06 18:42:36 +0000809 return Context->getConstantInt(Ty, Op->getValue().countLeadingZeros());
John Criswellbd9d3702005-10-27 16:00:10 +0000810 }
Chris Lattner72d88ae2007-01-30 23:15:43 +0000811 } else if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000812 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000813 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
814 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000815 double Op1V = Ty==Type::FloatTy ?
816 (double)Op1->getValueAPF().convertToFloat():
817 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000818 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Dale Johannesen43421b32007-09-06 18:13:44 +0000819 double Op2V = Ty==Type::FloatTy ?
820 (double)Op2->getValueAPF().convertToFloat():
821 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000822
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000823 if (Len == 3 && !strcmp(Str, "pow")) {
Owen Anderson50895512009-07-06 18:42:36 +0000824 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000825 } else if (Len == 4 && !strcmp(Str, "fmod")) {
Owen Anderson50895512009-07-06 18:42:36 +0000826 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000827 } else if (Len == 5 && !strcmp(Str, "atan2")) {
Owen Anderson50895512009-07-06 18:42:36 +0000828 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000829 }
830 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000831 if (!strcmp(Str, "llvm.powi.f32")) {
Owen Anderson50895512009-07-06 18:42:36 +0000832 return Context->getConstantFP(APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000833 (int)Op2C->getZExtValue())));
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000834 } else if (!strcmp(Str, "llvm.powi.f64")) {
Owen Anderson50895512009-07-06 18:42:36 +0000835 return Context->getConstantFP(APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000836 (int)Op2C->getZExtValue())));
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000837 }
John Criswellbd9d3702005-10-27 16:00:10 +0000838 }
839 }
840 }
841 return 0;
842}
843