blob: 1a0e4b410c3a201dfbf0633e2b0de0b7272c70fc [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"
John Criswellbd9d3702005-10-27 16:00:10 +000019#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
Chris Lattner55207322007-01-30 23:45:45 +000021#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000022#include "llvm/ADT/StringMap.h"
Chris Lattner03dd25c2007-01-31 00:51:48 +000023#include "llvm/Target/TargetData.h"
John Criswellbd9d3702005-10-27 16:00:10 +000024#include "llvm/Support/GetElementPtrTypeIterator.h"
25#include "llvm/Support/MathExtras.h"
26#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000027#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000028using namespace llvm;
29
Chris Lattner03dd25c2007-01-31 00:51:48 +000030//===----------------------------------------------------------------------===//
31// Constant Folding internal helper functions
32//===----------------------------------------------------------------------===//
33
34/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
35/// from a global, return the global and the constant. Because of
36/// constantexprs, this function is recursive.
37static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
38 int64_t &Offset, const TargetData &TD) {
39 // Trivial case, constant is the global.
40 if ((GV = dyn_cast<GlobalValue>(C))) {
41 Offset = 0;
42 return true;
43 }
44
45 // Otherwise, if this isn't a constant expr, bail out.
46 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
47 if (!CE) return false;
48
49 // Look through ptr->int and ptr->ptr casts.
50 if (CE->getOpcode() == Instruction::PtrToInt ||
51 CE->getOpcode() == Instruction::BitCast)
52 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
53
54 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
55 if (CE->getOpcode() == Instruction::GetElementPtr) {
56 // Cannot compute this if the element type of the pointer is missing size
57 // info.
Chris Lattnerf286f6f2007-12-10 22:53:04 +000058 if (!cast<PointerType>(CE->getOperand(0)->getType())
59 ->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +000060 return false;
61
62 // If the base isn't a global+constant, we aren't either.
63 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
64 return false;
65
66 // Otherwise, add any offset that our operands provide.
67 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifde2d74b2008-05-22 06:43:33 +000068 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greif785c6af2008-05-22 19:24:54 +000069 i != e; ++i, ++GTI) {
Gabor Greifde2d74b2008-05-22 06:43:33 +000070 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Chris Lattner03dd25c2007-01-31 00:51:48 +000071 if (!CI) return false; // Index isn't a simple constant?
72 if (CI->getZExtValue() == 0) continue; // Not adding anything.
73
74 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
75 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000076 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000077 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000078 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands514ab342007-11-01 20:53:16 +000079 Offset += TD.getABITypeSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000080 }
81 }
82 return true;
83 }
84
85 return false;
86}
87
88
89/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
90/// Attempt to symbolically evaluate the result of a binary operator merging
91/// these together. If target data info is available, it is provided as TD,
92/// otherwise TD is null.
93static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
94 Constant *Op1, const TargetData *TD){
95 // SROA
96
97 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
98 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
99 // bits.
100
101
102 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
103 // constant. This happens frequently when iterating over a global array.
104 if (Opc == Instruction::Sub && TD) {
105 GlobalValue *GV1, *GV2;
106 int64_t Offs1, Offs2;
107
108 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
109 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
110 GV1 == GV2) {
111 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
112 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
113 }
114 }
115
116 // TODO: Fold icmp setne/seteq as well.
117 return 0;
118}
119
120/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
121/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000122static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000123 const Type *ResultTy,
124 const TargetData *TD) {
125 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000126 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000127 return 0;
128
Chris Lattner268e7d72008-05-08 04:54:43 +0000129 uint64_t BasePtr = 0;
130 if (!Ptr->isNullValue()) {
131 // If this is a inttoptr from a constant int, we can fold this as the base,
132 // otherwise we can't.
133 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
134 if (CE->getOpcode() == Instruction::IntToPtr)
135 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
136 BasePtr = Base->getZExtValue();
137
138 if (BasePtr == 0)
139 return 0;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000140 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000141
142 // If this is a constant expr gep that is effectively computing an
143 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
144 for (unsigned i = 1; i != NumOps; ++i)
145 if (!isa<ConstantInt>(Ops[i]))
146 return false;
147
148 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
149 (Value**)Ops+1, NumOps-1);
150 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset+BasePtr);
151 return ConstantExpr::getIntToPtr(C, ResultTy);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000152}
153
Chris Lattner1afab9c2007-12-11 07:29:44 +0000154/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
155/// targetdata. Return 0 if unfoldable.
156static Constant *FoldBitCast(Constant *C, const Type *DestTy,
157 const TargetData &TD) {
158 // If this is a bitcast from constant vector -> vector, fold it.
159 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
160 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
161 // If the element types match, VMCore can fold it.
162 unsigned NumDstElt = DestVTy->getNumElements();
163 unsigned NumSrcElt = CV->getNumOperands();
164 if (NumDstElt == NumSrcElt)
165 return 0;
166
167 const Type *SrcEltTy = CV->getType()->getElementType();
168 const Type *DstEltTy = DestVTy->getElementType();
169
170 // Otherwise, we're changing the number of elements in a vector, which
171 // requires endianness information to do the right thing. For example,
172 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
173 // folds to (little endian):
174 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
175 // and to (big endian):
176 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
177
178 // First thing is first. We only want to think about integer here, so if
179 // we have something in FP form, recast it as integer.
180 if (DstEltTy->isFloatingPoint()) {
181 // Fold to an vector of integers with same size as our FP type.
182 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
183 const Type *DestIVTy = VectorType::get(IntegerType::get(FPWidth),
184 NumDstElt);
185 // Recursively handle this integer conversion, if possible.
186 C = FoldBitCast(C, DestIVTy, TD);
187 if (!C) return 0;
188
189 // Finally, VMCore can handle this now that #elts line up.
190 return ConstantExpr::getBitCast(C, DestTy);
191 }
192
193 // Okay, we know the destination is integer, if the input is FP, convert
194 // it to integer first.
195 if (SrcEltTy->isFloatingPoint()) {
196 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
197 const Type *SrcIVTy = VectorType::get(IntegerType::get(FPWidth),
198 NumSrcElt);
199 // Ask VMCore to do the conversion now that #elts line up.
200 C = ConstantExpr::getBitCast(C, SrcIVTy);
201 CV = dyn_cast<ConstantVector>(C);
202 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
203 }
204
205 // Now we know that the input and output vectors are both integer vectors
206 // of the same size, and that their #elements is not the same. Do the
207 // conversion here, which depends on whether the input or output has
208 // more elements.
209 bool isLittleEndian = TD.isLittleEndian();
210
211 SmallVector<Constant*, 32> Result;
212 if (NumDstElt < NumSrcElt) {
213 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
214 Constant *Zero = Constant::getNullValue(DstEltTy);
215 unsigned Ratio = NumSrcElt/NumDstElt;
216 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
217 unsigned SrcElt = 0;
218 for (unsigned i = 0; i != NumDstElt; ++i) {
219 // Build each element of the result.
220 Constant *Elt = Zero;
221 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
222 for (unsigned j = 0; j != Ratio; ++j) {
223 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
224 if (!Src) return 0; // Reject constantexpr elements.
225
226 // Zero extend the element to the right size.
227 Src = ConstantExpr::getZExt(Src, Elt->getType());
228
229 // Shift it to the right place, depending on endianness.
230 Src = ConstantExpr::getShl(Src,
231 ConstantInt::get(Src->getType(), ShiftAmt));
232 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
233
234 // Mix it in.
235 Elt = ConstantExpr::getOr(Elt, Src);
236 }
237 Result.push_back(Elt);
238 }
239 } else {
240 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
241 unsigned Ratio = NumDstElt/NumSrcElt;
242 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
243
244 // Loop over each source value, expanding into multiple results.
245 for (unsigned i = 0; i != NumSrcElt; ++i) {
246 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
247 if (!Src) return 0; // Reject constantexpr elements.
248
249 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
250 for (unsigned j = 0; j != Ratio; ++j) {
251 // Shift the piece of the value into the right place, depending on
252 // endianness.
253 Constant *Elt = ConstantExpr::getLShr(Src,
254 ConstantInt::get(Src->getType(), ShiftAmt));
255 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
256
257 // Truncate and remember this piece.
258 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
259 }
260 }
261 }
262
263 return ConstantVector::get(&Result[0], Result.size());
264 }
265 }
266
267 return 0;
268}
269
Chris Lattner03dd25c2007-01-31 00:51:48 +0000270
271//===----------------------------------------------------------------------===//
272// Constant Folding public APIs
273//===----------------------------------------------------------------------===//
274
275
Chris Lattner55207322007-01-30 23:45:45 +0000276/// ConstantFoldInstruction - Attempt to constant fold the specified
277/// instruction. If successful, the constant result is returned, if not, null
278/// is returned. Note that this function can only fail when attempting to fold
279/// instructions like loads and stores, which have no constant expression form.
280///
281Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
282 if (PHINode *PN = dyn_cast<PHINode>(I)) {
283 if (PN->getNumIncomingValues() == 0)
284 return Constant::getNullValue(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000285
Chris Lattner55207322007-01-30 23:45:45 +0000286 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
287 if (Result == 0) return 0;
288
289 // Handle PHI nodes specially here...
290 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
291 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
292 return 0; // Not all the same incoming constants...
293
294 // If we reach here, all incoming values are the same constant.
295 return Result;
296 }
297
298 // Scan the operand list, checking to see if they are all constants, if so,
299 // hand off to ConstantFoldInstOperands.
300 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000301 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
302 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000303 Ops.push_back(Op);
304 else
305 return 0; // All operands not constant!
306
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000307 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
308 return ConstantFoldCompareInstOperands(CI->getPredicate(),
309 &Ops[0], Ops.size(), TD);
310 else
311 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
312 &Ops[0], Ops.size(), TD);
Chris Lattner55207322007-01-30 23:45:45 +0000313}
314
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000315/// ConstantFoldConstantExpression - Attempt to fold the constant expression
316/// using the specified TargetData. If successful, the constant result is
317/// result is returned, if not, null is returned.
318Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
319 const TargetData *TD) {
320 assert(TD && "ConstantFoldConstantExpression requires a valid TargetData.");
321
322 SmallVector<Constant*, 8> Ops;
323 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
324 Ops.push_back(cast<Constant>(*i));
325
326 if (CE->isCompare())
327 return ConstantFoldCompareInstOperands(CE->getPredicate(),
328 &Ops[0], Ops.size(), TD);
329 else
330 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
331 &Ops[0], Ops.size(), TD);
332}
333
Chris Lattner55207322007-01-30 23:45:45 +0000334/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
335/// specified opcode and operands. If successful, the constant result is
336/// returned, if not, null is returned. Note that this function can fail when
337/// attempting to fold instructions like loads and stores, which have no
338/// constant expression form.
339///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000340Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
341 Constant* const* Ops, unsigned NumOps,
Chris Lattner55207322007-01-30 23:45:45 +0000342 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000343 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000344 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000345 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000346 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000347 return C;
348
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000349 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000350 }
Chris Lattner55207322007-01-30 23:45:45 +0000351
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000352 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000353 default: return 0;
354 case Instruction::Call:
355 if (Function *F = dyn_cast<Function>(Ops[0]))
356 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000357 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000358 return 0;
359 case Instruction::ICmp:
360 case Instruction::FCmp:
Nate Begemanb5557ab2008-07-25 17:35:37 +0000361 case Instruction::VICmp:
362 case Instruction::VFCmp:
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000363 assert(0 &&"This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000364 case Instruction::PtrToInt:
365 // If the input is a inttoptr, eliminate the pair. This requires knowing
366 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
368 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
369 Constant *Input = CE->getOperand(0);
370 unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
371 Constant *Mask =
372 ConstantInt::get(APInt::getLowBitsSet(InWidth,
373 TD->getPointerSizeInBits()));
374 Input = ConstantExpr::getAnd(Input, Mask);
375 // Do a zext or trunc to get to the dest size.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000376 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000377 }
378 }
Chris Lattner1afab9c2007-12-11 07:29:44 +0000379 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000380 case Instruction::IntToPtr:
Chris Lattner55207322007-01-30 23:45:45 +0000381 case Instruction::Trunc:
382 case Instruction::ZExt:
383 case Instruction::SExt:
384 case Instruction::FPTrunc:
385 case Instruction::FPExt:
386 case Instruction::UIToFP:
387 case Instruction::SIToFP:
388 case Instruction::FPToUI:
389 case Instruction::FPToSI:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000390 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000391 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000392 if (TD)
393 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD))
394 return C;
395 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000396 case Instruction::Select:
397 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
398 case Instruction::ExtractElement:
399 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
400 case Instruction::InsertElement:
401 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
402 case Instruction::ShuffleVector:
403 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
404 case Instruction::GetElementPtr:
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000405 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000406 return C;
407
Chris Lattnerd917fe52007-01-31 04:42:05 +0000408 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000409 }
410}
411
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000412/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
413/// instruction (icmp/fcmp) with the specified operands. If it fails, it
414/// returns a constant expression of the specified operands.
415///
416Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
417 Constant*const * Ops,
418 unsigned NumOps,
419 const TargetData *TD) {
420 // fold: icmp (inttoptr x), null -> icmp x, 0
421 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000422 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000423 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
424 //
425 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
426 // around to know if bit truncation is happening.
427 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
428 if (TD && Ops[1]->isNullValue()) {
429 const Type *IntPtrTy = TD->getIntPtrType();
430 if (CE0->getOpcode() == Instruction::IntToPtr) {
431 // Convert the integer value to the right size to ensure we get the
432 // proper extension or truncation.
433 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
434 IntPtrTy, false);
435 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
436 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
437 }
438
439 // Only do this transformation if the int is intptrty in size, otherwise
440 // there is a truncation or extension that we aren't modeling.
441 if (CE0->getOpcode() == Instruction::PtrToInt &&
442 CE0->getType() == IntPtrTy) {
443 Constant *C = CE0->getOperand(0);
444 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
445 // FIXME!
446 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
447 }
448 }
449
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000450 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
451 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
452 const Type *IntPtrTy = TD->getIntPtrType();
453
454 if (CE0->getOpcode() == Instruction::IntToPtr) {
455 // Convert the integer value to the right size to ensure we get the
456 // proper extension or truncation.
457 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
458 IntPtrTy, false);
459 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
460 IntPtrTy, false);
461 Constant *NewOps[] = { C0, C1 };
462 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
463 }
464
465 // Only do this transformation if the int is intptrty in size, otherwise
466 // there is a truncation or extension that we aren't modeling.
467 if ((CE0->getOpcode() == Instruction::PtrToInt &&
468 CE0->getType() == IntPtrTy &&
469 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
470 Constant *NewOps[] = {
471 CE0->getOperand(0), CE1->getOperand(0)
472 };
473 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
474 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000475 }
476 }
477 }
Nate Begemanb5557ab2008-07-25 17:35:37 +0000478 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000479}
480
481
Chris Lattner55207322007-01-30 23:45:45 +0000482/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
483/// getelementptr constantexpr, return the constant value being addressed by the
484/// constant expression, or null if something is funny and we can't decide.
485Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
486 ConstantExpr *CE) {
487 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
488 return 0; // Do not allow stepping over the value!
489
490 // Loop over all of the operands, tracking down which value we are
491 // addressing...
492 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
493 for (++I; I != E; ++I)
494 if (const StructType *STy = dyn_cast<StructType>(*I)) {
495 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
496 assert(CU->getZExtValue() < STy->getNumElements() &&
497 "Struct index out of range!");
498 unsigned El = (unsigned)CU->getZExtValue();
499 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
500 C = CS->getOperand(El);
501 } else if (isa<ConstantAggregateZero>(C)) {
502 C = Constant::getNullValue(STy->getElementType(El));
503 } else if (isa<UndefValue>(C)) {
504 C = UndefValue::get(STy->getElementType(El));
505 } else {
506 return 0;
507 }
508 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
509 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
510 if (CI->getZExtValue() >= ATy->getNumElements())
511 return 0;
512 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
513 C = CA->getOperand(CI->getZExtValue());
514 else if (isa<ConstantAggregateZero>(C))
515 C = Constant::getNullValue(ATy->getElementType());
516 else if (isa<UndefValue>(C))
517 C = UndefValue::get(ATy->getElementType());
518 else
519 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000520 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
Chris Lattner55207322007-01-30 23:45:45 +0000521 if (CI->getZExtValue() >= PTy->getNumElements())
522 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000523 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000524 C = CP->getOperand(CI->getZExtValue());
525 else if (isa<ConstantAggregateZero>(C))
526 C = Constant::getNullValue(PTy->getElementType());
527 else if (isa<UndefValue>(C))
528 C = UndefValue::get(PTy->getElementType());
529 else
530 return 0;
531 } else {
532 return 0;
533 }
534 } else {
535 return 0;
536 }
537 return C;
538}
539
540
541//===----------------------------------------------------------------------===//
542// Constant Folding for Calls
543//
John Criswellbd9d3702005-10-27 16:00:10 +0000544
545/// canConstantFoldCallTo - Return true if its even possible to fold a call to
546/// the specified function.
547bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000548llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000549 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000550 case Intrinsic::sqrt:
551 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000552 case Intrinsic::bswap:
553 case Intrinsic::ctpop:
554 case Intrinsic::ctlz:
555 case Intrinsic::cttz:
John Criswellbd9d3702005-10-27 16:00:10 +0000556 return true;
557 default: break;
558 }
559
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000560 const ValueName *NameVal = F->getValueName();
Chris Lattnera099b6c2007-08-08 16:07:23 +0000561 if (NameVal == 0) return false;
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000562 const char *Str = NameVal->getKeyData();
563 unsigned Len = NameVal->getKeyLength();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000564
565 // In these cases, the check of the length is required. We don't want to
566 // return true for a name like "cos\0blah" which strcmp would return equal to
567 // "cos", but has length 8.
568 switch (Str[0]) {
569 default: return false;
570 case 'a':
571 if (Len == 4)
572 return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
573 !strcmp(Str, "atan");
574 else if (Len == 5)
575 return !strcmp(Str, "atan2");
576 return false;
577 case 'c':
578 if (Len == 3)
579 return !strcmp(Str, "cos");
580 else if (Len == 4)
581 return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
582 !strcmp(Str, "cosh");
583 return false;
584 case 'e':
585 if (Len == 3)
586 return !strcmp(Str, "exp");
587 return false;
588 case 'f':
589 if (Len == 4)
590 return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
591 else if (Len == 5)
592 return !strcmp(Str, "floor");
593 return false;
594 break;
595 case 'l':
596 if (Len == 3 && !strcmp(Str, "log"))
597 return true;
598 if (Len == 5 && !strcmp(Str, "log10"))
599 return true;
600 return false;
601 case 'p':
602 if (Len == 3 && !strcmp(Str, "pow"))
603 return true;
604 return false;
605 case 's':
606 if (Len == 3)
607 return !strcmp(Str, "sin");
608 if (Len == 4)
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000609 return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
610 !strcmp(Str, "sinf");
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000611 if (Len == 5)
612 return !strcmp(Str, "sqrtf");
613 return false;
614 case 't':
615 if (Len == 3 && !strcmp(Str, "tan"))
616 return true;
617 else if (Len == 4 && !strcmp(Str, "tanh"))
618 return true;
619 return false;
John Criswellbd9d3702005-10-27 16:00:10 +0000620 }
621}
622
Chris Lattner72d88ae2007-01-30 23:15:43 +0000623static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
624 const Type *Ty) {
John Criswellbd9d3702005-10-27 16:00:10 +0000625 errno = 0;
626 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000627 if (errno != 0) {
628 errno = 0;
629 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000630 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000631
632 if (Ty == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000633 return ConstantFP::get(APFloat((float)V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000634 if (Ty == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000635 return ConstantFP::get(APFloat(V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000636 assert(0 && "Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000637 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000638}
639
Dan Gohman38415242007-07-16 15:26:22 +0000640static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
641 double V, double W,
642 const Type *Ty) {
643 errno = 0;
644 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000645 if (errno != 0) {
646 errno = 0;
647 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000648 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000649
650 if (Ty == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000651 return ConstantFP::get(APFloat((float)V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000652 if (Ty == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000653 return ConstantFP::get(APFloat(V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000654 assert(0 && "Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000655 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000656}
657
John Criswellbd9d3702005-10-27 16:00:10 +0000658/// ConstantFoldCall - Attempt to constant fold a call to the specified function
659/// with the specified arguments, returning null if unsuccessful.
Dale Johannesen43421b32007-09-06 18:13:44 +0000660
John Criswellbd9d3702005-10-27 16:00:10 +0000661Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000662llvm::ConstantFoldCall(Function *F,
663 Constant* const* Operands, unsigned NumOperands) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000664 const ValueName *NameVal = F->getValueName();
Chris Lattnera099b6c2007-08-08 16:07:23 +0000665 if (NameVal == 0) return 0;
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000666 const char *Str = NameVal->getKeyData();
667 unsigned Len = NameVal->getKeyLength();
668
John Criswellbd9d3702005-10-27 16:00:10 +0000669 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000670 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000671 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Dale Johannesen43421b32007-09-06 18:13:44 +0000672 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
673 return 0;
674 /// Currently APFloat versions of these functions do not exist, so we use
675 /// the host native double versions. Float versions are not called
676 /// directly but for all these it is true (float)(f((double)arg)) ==
677 /// f(arg). Long double not supported yet.
678 double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
679 Op->getValueAPF().convertToDouble();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000680 switch (Str[0]) {
681 case 'a':
682 if (Len == 4 && !strcmp(Str, "acos"))
683 return ConstantFoldFP(acos, V, Ty);
684 else if (Len == 4 && !strcmp(Str, "asin"))
685 return ConstantFoldFP(asin, V, Ty);
686 else if (Len == 4 && !strcmp(Str, "atan"))
687 return ConstantFoldFP(atan, V, Ty);
688 break;
689 case 'c':
690 if (Len == 4 && !strcmp(Str, "ceil"))
691 return ConstantFoldFP(ceil, V, Ty);
692 else if (Len == 3 && !strcmp(Str, "cos"))
693 return ConstantFoldFP(cos, V, Ty);
694 else if (Len == 4 && !strcmp(Str, "cosh"))
695 return ConstantFoldFP(cosh, V, Ty);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000696 else if (Len == 4 && !strcmp(Str, "cosf"))
697 return ConstantFoldFP(cos, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000698 break;
699 case 'e':
700 if (Len == 3 && !strcmp(Str, "exp"))
701 return ConstantFoldFP(exp, V, Ty);
702 break;
703 case 'f':
704 if (Len == 4 && !strcmp(Str, "fabs"))
Dale Johannesen43421b32007-09-06 18:13:44 +0000705 return ConstantFoldFP(fabs, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000706 else if (Len == 5 && !strcmp(Str, "floor"))
707 return ConstantFoldFP(floor, V, Ty);
708 break;
709 case 'l':
710 if (Len == 3 && !strcmp(Str, "log") && V > 0)
711 return ConstantFoldFP(log, V, Ty);
712 else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
713 return ConstantFoldFP(log10, V, Ty);
714 else if (!strcmp(Str, "llvm.sqrt.f32") ||
715 !strcmp(Str, "llvm.sqrt.f64")) {
716 if (V >= -0.0)
Dale Johannesen43421b32007-09-06 18:13:44 +0000717 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000718 else // Undefined
Chris Lattner02a260a2008-04-20 00:41:09 +0000719 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000720 }
721 break;
722 case 's':
723 if (Len == 3 && !strcmp(Str, "sin"))
724 return ConstantFoldFP(sin, V, Ty);
725 else if (Len == 4 && !strcmp(Str, "sinh"))
726 return ConstantFoldFP(sinh, V, Ty);
727 else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
728 return ConstantFoldFP(sqrt, V, Ty);
729 else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
730 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000731 else if (Len == 4 && !strcmp(Str, "sinf"))
732 return ConstantFoldFP(sin, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000733 break;
734 case 't':
735 if (Len == 3 && !strcmp(Str, "tan"))
736 return ConstantFoldFP(tan, V, Ty);
737 else if (Len == 4 && !strcmp(Str, "tanh"))
738 return ConstantFoldFP(tanh, V, Ty);
739 break;
740 default:
741 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000742 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000743 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Chris Lattnerecc02742007-11-23 22:34:59 +0000744 if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
Reid Spencere9391fd2007-04-01 07:35:23 +0000745 return ConstantInt::get(Op->getValue().byteSwap());
Chris Lattnerecc02742007-11-23 22:34:59 +0000746 else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
747 return ConstantInt::get(Ty, Op->getValue().countPopulation());
748 else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
749 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
750 else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
751 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
John Criswellbd9d3702005-10-27 16:00:10 +0000752 }
Chris Lattner72d88ae2007-01-30 23:15:43 +0000753 } else if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000754 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000755 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
756 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000757 double Op1V = Ty==Type::FloatTy ?
758 (double)Op1->getValueAPF().convertToFloat():
759 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000760 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Dale Johannesen43421b32007-09-06 18:13:44 +0000761 double Op2V = Ty==Type::FloatTy ?
762 (double)Op2->getValueAPF().convertToFloat():
763 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000764
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000765 if (Len == 3 && !strcmp(Str, "pow")) {
Dan Gohman38415242007-07-16 15:26:22 +0000766 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000767 } else if (Len == 4 && !strcmp(Str, "fmod")) {
Dan Gohman38415242007-07-16 15:26:22 +0000768 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000769 } else if (Len == 5 && !strcmp(Str, "atan2")) {
Dan Gohman38415242007-07-16 15:26:22 +0000770 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000771 }
772 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000773 if (!strcmp(Str, "llvm.powi.f32")) {
Chris Lattner02a260a2008-04-20 00:41:09 +0000774 return ConstantFP::get(APFloat((float)std::pow((float)Op1V,
775 (int)Op2C->getZExtValue())));
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000776 } else if (!strcmp(Str, "llvm.powi.f64")) {
Chris Lattner02a260a2008-04-20 00:41:09 +0000777 return ConstantFP::get(APFloat((double)std::pow((double)Op1V,
778 (int)Op2C->getZExtValue())));
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000779 }
John Criswellbd9d3702005-10-27 16:00:10 +0000780 }
781 }
782 }
783 return 0;
784}
785