blob: f07d03aa0f3d2ee0b4b6b7e8529985cb2e08c557 [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 Lattner55207322007-01-30 23:45:45 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000028#include "llvm/ADT/StringMap.h"
Chris Lattner03dd25c2007-01-31 00:51:48 +000029#include "llvm/Target/TargetData.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
John Criswellbd9d3702005-10-27 16:00:10 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/MathExtras.h"
33#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000034#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000035using namespace llvm;
36
Chris Lattner03dd25c2007-01-31 00:51:48 +000037//===----------------------------------------------------------------------===//
38// Constant Folding internal helper functions
39//===----------------------------------------------------------------------===//
40
41/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
42/// from a global, return the global and the constant. Because of
43/// constantexprs, this function is recursive.
44static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
45 int64_t &Offset, const TargetData &TD) {
46 // Trivial case, constant is the global.
47 if ((GV = dyn_cast<GlobalValue>(C))) {
48 Offset = 0;
49 return true;
50 }
51
52 // Otherwise, if this isn't a constant expr, bail out.
53 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
54 if (!CE) return false;
55
56 // Look through ptr->int and ptr->ptr casts.
57 if (CE->getOpcode() == Instruction::PtrToInt ||
58 CE->getOpcode() == Instruction::BitCast)
59 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
60
61 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
62 if (CE->getOpcode() == Instruction::GetElementPtr) {
63 // Cannot compute this if the element type of the pointer is missing size
64 // info.
Chris Lattnerf286f6f2007-12-10 22:53:04 +000065 if (!cast<PointerType>(CE->getOperand(0)->getType())
66 ->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +000067 return false;
68
69 // If the base isn't a global+constant, we aren't either.
70 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
71 return false;
72
73 // Otherwise, add any offset that our operands provide.
74 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifde2d74b2008-05-22 06:43:33 +000075 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greif785c6af2008-05-22 19:24:54 +000076 i != e; ++i, ++GTI) {
Gabor Greifde2d74b2008-05-22 06:43:33 +000077 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Chris Lattner03dd25c2007-01-31 00:51:48 +000078 if (!CI) return false; // Index isn't a simple constant?
79 if (CI->getZExtValue() == 0) continue; // Not adding anything.
80
81 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
82 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000083 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000084 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000085 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands777d2302009-05-09 07:06:46 +000086 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000087 }
88 }
89 return true;
90 }
91
92 return false;
93}
94
95
96/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +000097/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +000098/// these together. If target data info is available, it is provided as TD,
99/// otherwise TD is null.
100static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +0000101 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +0000102 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +0000103 // SROA
104
105 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
106 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
107 // bits.
108
109
110 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
111 // constant. This happens frequently when iterating over a global array.
112 if (Opc == Instruction::Sub && TD) {
113 GlobalValue *GV1, *GV2;
114 int64_t Offs1, Offs2;
115
116 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
117 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
118 GV1 == GV2) {
119 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000120 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000121 }
122 }
123
Chris Lattner03dd25c2007-01-31 00:51:48 +0000124 return 0;
125}
126
127/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
128/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000129static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000130 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000131 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000132 const TargetData *TD) {
133 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000134 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000135 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000136
137 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
138 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000139 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000140 if (!Ptr->isNullValue()) {
141 // If this is a inttoptr from a constant int, we can fold this as the base,
142 // otherwise we can't.
143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
144 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000145 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000146 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000147 BasePtr.zextOrTrunc(BitWidth);
148 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000149
150 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000151 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000152 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000153
154 // If this is a constant expr gep that is effectively computing an
155 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
156 for (unsigned i = 1; i != NumOps; ++i)
157 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000158 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000159
Dan Gohmancda97062009-08-21 16:52:54 +0000160 APInt Offset = APInt(BitWidth,
161 TD->getIndexedOffset(Ptr->getType(),
162 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000163 // If the base value for this address is a literal integer value, fold the
164 // getelementptr to the resulting integer value casted to the pointer type.
165 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000166 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000167 return ConstantExpr::getIntToPtr(C, ResultTy);
168 }
169
170 // Otherwise form a regular getelementptr. Recompute the indices so that
171 // we eliminate over-indexing of the notional static type array bounds.
172 // This makes it easy to determine if the getelementptr is "inbounds".
173 // Also, this helps GlobalOpt do SROA on GlobalVariables.
174 const Type *Ty = Ptr->getType();
175 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000176 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000177 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000178 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000179 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000180 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000181 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000182 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000183 if (ElemSize == 0)
184 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000185 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000186 Offset -= NewIdx * ElemSize;
187 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
188 Ty = ATy->getElementType();
189 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000190 // Determine which field of the struct the offset points into. The
191 // getZExtValue is at least as safe as the StructLayout API because we
192 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000193 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000194 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000195 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000196 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000197 Ty = STy->getTypeAtIndex(ElIdx);
198 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000199 // We've reached some non-indexable type.
200 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000201 }
Dan Gohman3d013342009-08-19 22:46:59 +0000202 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
203
204 // If we haven't used up the entire offset by descending the static
205 // type, then the offset is pointing into the middle of an indivisible
206 // member, so we can't simplify it.
207 if (Offset != 0)
208 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000209
210 // If the base is the start of a GlobalVariable and all the array indices
211 // remain in their static bounds, the GEP is inbounds. We can check that
212 // all indices are in bounds by just checking the first index only
Dan Gohman6e7ad952009-09-03 23:34:49 +0000213 // because we've just normalized all the indices.
214 Constant *C = isa<GlobalVariable>(Ptr) && NewIdxs[0]->isNullValue() ?
215 ConstantExpr::getInBoundsGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size()) :
216 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
217 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
218 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000219
Dan Gohman3d013342009-08-19 22:46:59 +0000220 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000221 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000222 if (Ty != cast<PointerType>(ResultTy)->getElementType())
223 C = ConstantExpr::getBitCast(C, ResultTy);
224
225 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000226}
227
Chris Lattner1afab9c2007-12-11 07:29:44 +0000228/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
229/// targetdata. Return 0 if unfoldable.
230static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000231 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000232 // If this is a bitcast from constant vector -> vector, fold it.
233 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
234 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
235 // If the element types match, VMCore can fold it.
236 unsigned NumDstElt = DestVTy->getNumElements();
237 unsigned NumSrcElt = CV->getNumOperands();
238 if (NumDstElt == NumSrcElt)
239 return 0;
240
241 const Type *SrcEltTy = CV->getType()->getElementType();
242 const Type *DstEltTy = DestVTy->getElementType();
243
244 // Otherwise, we're changing the number of elements in a vector, which
245 // requires endianness information to do the right thing. For example,
246 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
247 // folds to (little endian):
248 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
249 // and to (big endian):
250 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
251
252 // First thing is first. We only want to think about integer here, so if
253 // we have something in FP form, recast it as integer.
254 if (DstEltTy->isFloatingPoint()) {
255 // Fold to an vector of integers with same size as our FP type.
256 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000257 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000258 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000259 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000260 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000261 if (!C) return 0;
262
263 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000264 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000265 }
266
267 // Okay, we know the destination is integer, if the input is FP, convert
268 // it to integer first.
269 if (SrcEltTy->isFloatingPoint()) {
270 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000271 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000272 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000273 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000274 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000275 CV = dyn_cast<ConstantVector>(C);
276 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
277 }
278
279 // Now we know that the input and output vectors are both integer vectors
280 // of the same size, and that their #elements is not the same. Do the
281 // conversion here, which depends on whether the input or output has
282 // more elements.
283 bool isLittleEndian = TD.isLittleEndian();
284
285 SmallVector<Constant*, 32> Result;
286 if (NumDstElt < NumSrcElt) {
287 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000288 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000289 unsigned Ratio = NumSrcElt/NumDstElt;
290 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
291 unsigned SrcElt = 0;
292 for (unsigned i = 0; i != NumDstElt; ++i) {
293 // Build each element of the result.
294 Constant *Elt = Zero;
295 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
296 for (unsigned j = 0; j != Ratio; ++j) {
297 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
298 if (!Src) return 0; // Reject constantexpr elements.
299
300 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000301 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000302
303 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000304 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000305 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000306 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
307
308 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000309 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000310 }
311 Result.push_back(Elt);
312 }
313 } else {
314 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
315 unsigned Ratio = NumDstElt/NumSrcElt;
316 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
317
318 // Loop over each source value, expanding into multiple results.
319 for (unsigned i = 0; i != NumSrcElt; ++i) {
320 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
321 if (!Src) return 0; // Reject constantexpr elements.
322
323 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
324 for (unsigned j = 0; j != Ratio; ++j) {
325 // Shift the piece of the value into the right place, depending on
326 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000327 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000328 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000329 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
330
331 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000332 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000333 }
334 }
335 }
336
Owen Andersonaf7ec972009-07-28 21:19:26 +0000337 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000338 }
339 }
340
341 return 0;
342}
343
Chris Lattner03dd25c2007-01-31 00:51:48 +0000344
345//===----------------------------------------------------------------------===//
346// Constant Folding public APIs
347//===----------------------------------------------------------------------===//
348
349
Chris Lattner55207322007-01-30 23:45:45 +0000350/// ConstantFoldInstruction - Attempt to constant fold the specified
351/// instruction. If successful, the constant result is returned, if not, null
352/// is returned. Note that this function can only fail when attempting to fold
353/// instructions like loads and stores, which have no constant expression form.
354///
Owen Andersone922c022009-07-22 00:24:57 +0000355Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000356 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000357 if (PHINode *PN = dyn_cast<PHINode>(I)) {
358 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000359 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000360
Chris Lattner55207322007-01-30 23:45:45 +0000361 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
362 if (Result == 0) return 0;
363
364 // Handle PHI nodes specially here...
365 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
366 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
367 return 0; // Not all the same incoming constants...
368
369 // If we reach here, all incoming values are the same constant.
370 return Result;
371 }
372
373 // Scan the operand list, checking to see if they are all constants, if so,
374 // hand off to ConstantFoldInstOperands.
375 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000376 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
377 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000378 Ops.push_back(Op);
379 else
380 return 0; // All operands not constant!
381
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000382 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
383 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000384 Ops.data(), Ops.size(),
385 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000386 else
387 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +0000388 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000389}
390
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000391/// ConstantFoldConstantExpression - Attempt to fold the constant expression
392/// using the specified TargetData. If successful, the constant result is
393/// result is returned, if not, null is returned.
394Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000395 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000396 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000397 SmallVector<Constant*, 8> Ops;
398 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
399 Ops.push_back(cast<Constant>(*i));
400
401 if (CE->isCompare())
402 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000403 Ops.data(), Ops.size(),
404 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000405 else
406 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
Owen Anderson50895512009-07-06 18:42:36 +0000407 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000408}
409
Chris Lattner55207322007-01-30 23:45:45 +0000410/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
411/// specified opcode and operands. If successful, the constant result is
412/// returned, if not, null is returned. Note that this function can fail when
413/// attempting to fold instructions like loads and stores, which have no
414/// constant expression form.
415///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000416Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
417 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000418 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000419 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000420 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000421 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000422 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000423 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
424 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000425 return C;
426
Owen Andersonbaf3c402009-07-29 18:55:55 +0000427 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000428 }
Chris Lattner55207322007-01-30 23:45:45 +0000429
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000430 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000431 default: return 0;
432 case Instruction::Call:
433 if (Function *F = dyn_cast<Function>(Ops[0]))
434 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000435 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000436 return 0;
437 case Instruction::ICmp:
438 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000439 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000440 case Instruction::PtrToInt:
441 // If the input is a inttoptr, eliminate the pair. This requires knowing
442 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
443 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
444 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
445 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000446 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000447 if (TD->getPointerSizeInBits() < InWidth) {
448 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000449 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000450 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000451 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000452 }
Chris Lattner001f7532007-08-11 23:49:01 +0000453 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000454 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000455 }
456 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000457 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000458 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000459 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
460 // the int size is >= the ptr size. This requires knowing the width of a
461 // pointer, so it can't be done in ConstantExpr::getCast.
462 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000463 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000464 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000465 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000466 if (CE->getOpcode() == Instruction::PtrToInt) {
467 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000468 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000469 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000470 }
471 // If there's a constant offset added to the integer value before
472 // it is casted back to a pointer, see if the expression can be
473 // converted into a GEP.
474 if (CE->getOpcode() == Instruction::Add)
475 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
476 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
477 if (R->getOpcode() == Instruction::PtrToInt)
478 if (GlobalVariable *GV =
479 dyn_cast<GlobalVariable>(R->getOperand(0))) {
480 const PointerType *GVTy = cast<PointerType>(GV->getType());
481 if (const ArrayType *AT =
482 dyn_cast<ArrayType>(GVTy->getElementType())) {
483 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000484 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
485 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000486 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
487 L->getValue().urem(PSA) == 0) {
488 APInt ElemIdx = L->getValue().udiv(PSA);
489 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
490 AT->getNumElements()))) {
491 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000492 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000493 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000494 };
Owen Anderson50895512009-07-06 18:42:36 +0000495 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000496 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000497 }
498 }
499 }
500 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000501 }
502 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000503 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000504 case Instruction::Trunc:
505 case Instruction::ZExt:
506 case Instruction::SExt:
507 case Instruction::FPTrunc:
508 case Instruction::FPExt:
509 case Instruction::UIToFP:
510 case Instruction::SIToFP:
511 case Instruction::FPToUI:
512 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000513 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000514 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000515 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000516 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000517 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000518 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000519 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000520 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000521 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000522 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000523 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000524 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000525 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000526 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000527 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000528 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000529 return C;
530
Owen Andersonbaf3c402009-07-29 18:55:55 +0000531 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000532 }
533}
534
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000535/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
536/// instruction (icmp/fcmp) with the specified operands. If it fails, it
537/// returns a constant expression of the specified operands.
538///
539Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
540 Constant*const * Ops,
541 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000542 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000543 const TargetData *TD) {
544 // fold: icmp (inttoptr x), null -> icmp x, 0
545 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000546 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000547 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
548 //
549 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
550 // around to know if bit truncation is happening.
551 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
552 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000553 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000554 if (CE0->getOpcode() == Instruction::IntToPtr) {
555 // Convert the integer value to the right size to ensure we get the
556 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000557 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000558 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000559 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000560 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
561 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000562 }
563
564 // Only do this transformation if the int is intptrty in size, otherwise
565 // there is a truncation or extension that we aren't modeling.
566 if (CE0->getOpcode() == Instruction::PtrToInt &&
567 CE0->getType() == IntPtrTy) {
568 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000569 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000570 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000571 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
572 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000573 }
574 }
575
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000576 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
577 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000578 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000579
580 if (CE0->getOpcode() == Instruction::IntToPtr) {
581 // Convert the integer value to the right size to ensure we get the
582 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000583 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000584 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000585 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000586 IntPtrTy, false);
587 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000588 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
589 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000590 }
591
592 // Only do this transformation if the int is intptrty in size, otherwise
593 // there is a truncation or extension that we aren't modeling.
594 if ((CE0->getOpcode() == Instruction::PtrToInt &&
595 CE0->getType() == IntPtrTy &&
596 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
597 Constant *NewOps[] = {
598 CE0->getOperand(0), CE1->getOperand(0)
599 };
Owen Anderson50895512009-07-06 18:42:36 +0000600 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
601 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000602 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000603 }
604 }
605 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000606 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000607}
608
609
Chris Lattner55207322007-01-30 23:45:45 +0000610/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
611/// getelementptr constantexpr, return the constant value being addressed by the
612/// constant expression, or null if something is funny and we can't decide.
613Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Owen Anderson50895512009-07-06 18:42:36 +0000614 ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000615 LLVMContext &Context) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000616 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000617 return 0; // Do not allow stepping over the value!
618
619 // Loop over all of the operands, tracking down which value we are
620 // addressing...
621 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
622 for (++I; I != E; ++I)
623 if (const StructType *STy = dyn_cast<StructType>(*I)) {
624 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
625 assert(CU->getZExtValue() < STy->getNumElements() &&
626 "Struct index out of range!");
627 unsigned El = (unsigned)CU->getZExtValue();
628 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
629 C = CS->getOperand(El);
630 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000631 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000632 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000633 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000634 } else {
635 return 0;
636 }
637 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
638 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
639 if (CI->getZExtValue() >= ATy->getNumElements())
640 return 0;
641 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
642 C = CA->getOperand(CI->getZExtValue());
643 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000644 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000645 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000646 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000647 else
648 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000649 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
Chris Lattner55207322007-01-30 23:45:45 +0000650 if (CI->getZExtValue() >= PTy->getNumElements())
651 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000652 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000653 C = CP->getOperand(CI->getZExtValue());
654 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000655 C = Constant::getNullValue(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000656 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000657 C = UndefValue::get(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000658 else
659 return 0;
660 } else {
661 return 0;
662 }
663 } else {
664 return 0;
665 }
666 return C;
667}
668
669
670//===----------------------------------------------------------------------===//
671// Constant Folding for Calls
672//
John Criswellbd9d3702005-10-27 16:00:10 +0000673
674/// canConstantFoldCallTo - Return true if its even possible to fold a call to
675/// the specified function.
676bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000677llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000678 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000679 case Intrinsic::sqrt:
680 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000681 case Intrinsic::bswap:
682 case Intrinsic::ctpop:
683 case Intrinsic::ctlz:
684 case Intrinsic::cttz:
John Criswellbd9d3702005-10-27 16:00:10 +0000685 return true;
686 default: break;
687 }
688
Chris Lattner6f532a92009-04-03 00:02:39 +0000689 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000690 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000691
692 // In these cases, the check of the length is required. We don't want to
693 // return true for a name like "cos\0blah" which strcmp would return equal to
694 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000695 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000696 default: return false;
697 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000698 return Name == "acos" || Name == "asin" ||
699 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000700 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000701 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000702 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000703 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000704 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000705 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000706 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000707 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000708 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000709 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000710 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000711 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
712 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000713 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000714 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000715 }
716}
717
Chris Lattner72d88ae2007-01-30 23:15:43 +0000718static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000719 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000720 errno = 0;
721 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000722 if (errno != 0) {
723 errno = 0;
724 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000725 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000726
Owen Anderson1d0be152009-08-13 21:58:54 +0000727 if (Ty == Type::getFloatTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000728 return ConstantFP::get(Context, APFloat((float)V));
Owen Anderson1d0be152009-08-13 21:58:54 +0000729 if (Ty == Type::getDoubleTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000730 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000731 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000732 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000733}
734
Dan Gohman38415242007-07-16 15:26:22 +0000735static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
736 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +0000737 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +0000738 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +0000739 errno = 0;
740 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000741 if (errno != 0) {
742 errno = 0;
743 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000744 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000745
Owen Anderson1d0be152009-08-13 21:58:54 +0000746 if (Ty == Type::getFloatTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000747 return ConstantFP::get(Context, APFloat((float)V));
Owen Anderson1d0be152009-08-13 21:58:54 +0000748 if (Ty == Type::getDoubleTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000749 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000750 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000751 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000752}
753
John Criswellbd9d3702005-10-27 16:00:10 +0000754/// ConstantFoldCall - Attempt to constant fold a call to the specified function
755/// with the specified arguments, returning null if unsuccessful.
Dale Johannesen43421b32007-09-06 18:13:44 +0000756
John Criswellbd9d3702005-10-27 16:00:10 +0000757Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000758llvm::ConstantFoldCall(Function *F,
759 Constant* const* Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +0000760 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +0000761 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000762 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000763
John Criswellbd9d3702005-10-27 16:00:10 +0000764 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000765 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000766 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000767 if (Ty!=Type::getFloatTy(F->getContext()) &&
768 Ty!=Type::getDoubleTy(Context))
Dale Johannesen43421b32007-09-06 18:13:44 +0000769 return 0;
770 /// Currently APFloat versions of these functions do not exist, so we use
771 /// the host native double versions. Float versions are not called
772 /// directly but for all these it is true (float)(f((double)arg)) ==
773 /// f(arg). Long double not supported yet.
Owen Anderson1d0be152009-08-13 21:58:54 +0000774 double V = Ty==Type::getFloatTy(F->getContext()) ?
775 (double)Op->getValueAPF().convertToFloat():
Dale Johannesen43421b32007-09-06 18:13:44 +0000776 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000777 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000778 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000779 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +0000780 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000781 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +0000782 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000783 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +0000784 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000785 break;
786 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000787 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +0000788 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000789 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +0000790 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000791 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +0000792 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000793 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +0000794 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000795 break;
796 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000797 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +0000798 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000799 break;
800 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000801 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +0000802 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000803 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +0000804 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000805 break;
806 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000807 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000808 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000809 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000810 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000811 else if (Name == "llvm.sqrt.f32" ||
812 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000813 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +0000814 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000815 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +0000816 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000817 }
818 break;
819 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000820 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +0000821 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000822 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +0000823 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000824 else if (Name == "sqrt" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000825 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000826 else if (Name == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000827 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000828 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +0000829 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000830 break;
831 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000832 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +0000833 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000834 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +0000835 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000836 break;
837 default:
838 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000839 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000840 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000841 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000842 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000843 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000844 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000845 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000846 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000847 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000848 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
John Criswellbd9d3702005-10-27 16:00:10 +0000849 }
Chris Lattner72d88ae2007-01-30 23:15:43 +0000850 } else if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000851 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000852 if (Ty!=Type::getFloatTy(F->getContext()) &&
853 Ty!=Type::getDoubleTy(Context))
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000854 return 0;
Owen Anderson1d0be152009-08-13 21:58:54 +0000855 double Op1V = Ty==Type::getFloatTy(F->getContext()) ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000856 (double)Op1->getValueAPF().convertToFloat():
857 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000858 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000859 double Op2V = Ty==Type::getFloatTy(F->getContext()) ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000860 (double)Op2->getValueAPF().convertToFloat():
861 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000862
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000863 if (Name == "pow") {
Owen Anderson50895512009-07-06 18:42:36 +0000864 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000865 } else if (Name == "fmod") {
Owen Anderson50895512009-07-06 18:42:36 +0000866 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000867 } else if (Name == "atan2") {
Owen Anderson50895512009-07-06 18:42:36 +0000868 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000869 }
870 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000871 if (Name == "llvm.powi.f32") {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000872 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000873 (int)Op2C->getZExtValue())));
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000874 } else if (Name == "llvm.powi.f64") {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000875 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000876 (int)Op2C->getZExtValue())));
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000877 }
John Criswellbd9d3702005-10-27 16:00:10 +0000878 }
879 }
880 }
881 return 0;
882}
883