blob: e9efb292e5bd477a676b9a916138be05b1512bd7 [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);
68 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i, ++GTI) {
69 ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(i));
70 if (!CI) return false; // Index isn't a simple constant?
71 if (CI->getZExtValue() == 0) continue; // Not adding anything.
72
73 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
74 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000075 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000076 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000077 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands514ab342007-11-01 20:53:16 +000078 Offset += TD.getABITypeSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000079 }
80 }
81 return true;
82 }
83
84 return false;
85}
86
87
88/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
89/// Attempt to symbolically evaluate the result of a binary operator merging
90/// these together. If target data info is available, it is provided as TD,
91/// otherwise TD is null.
92static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
93 Constant *Op1, const TargetData *TD){
94 // SROA
95
96 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
97 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
98 // bits.
99
100
101 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
102 // constant. This happens frequently when iterating over a global array.
103 if (Opc == Instruction::Sub && TD) {
104 GlobalValue *GV1, *GV2;
105 int64_t Offs1, Offs2;
106
107 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
108 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
109 GV1 == GV2) {
110 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
111 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
112 }
113 }
114
115 // TODO: Fold icmp setne/seteq as well.
116 return 0;
117}
118
119/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
120/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000121static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000122 const Type *ResultTy,
123 const TargetData *TD) {
124 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000125 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000126 return 0;
127
Chris Lattner268e7d72008-05-08 04:54:43 +0000128 uint64_t BasePtr = 0;
129 if (!Ptr->isNullValue()) {
130 // If this is a inttoptr from a constant int, we can fold this as the base,
131 // otherwise we can't.
132 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
133 if (CE->getOpcode() == Instruction::IntToPtr)
134 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
135 BasePtr = Base->getZExtValue();
136
137 if (BasePtr == 0)
138 return 0;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000139 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000140
141 // If this is a constant expr gep that is effectively computing an
142 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
143 for (unsigned i = 1; i != NumOps; ++i)
144 if (!isa<ConstantInt>(Ops[i]))
145 return false;
146
147 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
148 (Value**)Ops+1, NumOps-1);
149 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset+BasePtr);
150 return ConstantExpr::getIntToPtr(C, ResultTy);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000151
152 return 0;
153}
154
Chris Lattner1afab9c2007-12-11 07:29:44 +0000155/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
156/// targetdata. Return 0 if unfoldable.
157static Constant *FoldBitCast(Constant *C, const Type *DestTy,
158 const TargetData &TD) {
159 // If this is a bitcast from constant vector -> vector, fold it.
160 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
161 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
162 // If the element types match, VMCore can fold it.
163 unsigned NumDstElt = DestVTy->getNumElements();
164 unsigned NumSrcElt = CV->getNumOperands();
165 if (NumDstElt == NumSrcElt)
166 return 0;
167
168 const Type *SrcEltTy = CV->getType()->getElementType();
169 const Type *DstEltTy = DestVTy->getElementType();
170
171 // Otherwise, we're changing the number of elements in a vector, which
172 // requires endianness information to do the right thing. For example,
173 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
174 // folds to (little endian):
175 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
176 // and to (big endian):
177 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
178
179 // First thing is first. We only want to think about integer here, so if
180 // we have something in FP form, recast it as integer.
181 if (DstEltTy->isFloatingPoint()) {
182 // Fold to an vector of integers with same size as our FP type.
183 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
184 const Type *DestIVTy = VectorType::get(IntegerType::get(FPWidth),
185 NumDstElt);
186 // Recursively handle this integer conversion, if possible.
187 C = FoldBitCast(C, DestIVTy, TD);
188 if (!C) return 0;
189
190 // Finally, VMCore can handle this now that #elts line up.
191 return ConstantExpr::getBitCast(C, DestTy);
192 }
193
194 // Okay, we know the destination is integer, if the input is FP, convert
195 // it to integer first.
196 if (SrcEltTy->isFloatingPoint()) {
197 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
198 const Type *SrcIVTy = VectorType::get(IntegerType::get(FPWidth),
199 NumSrcElt);
200 // Ask VMCore to do the conversion now that #elts line up.
201 C = ConstantExpr::getBitCast(C, SrcIVTy);
202 CV = dyn_cast<ConstantVector>(C);
203 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
204 }
205
206 // Now we know that the input and output vectors are both integer vectors
207 // of the same size, and that their #elements is not the same. Do the
208 // conversion here, which depends on whether the input or output has
209 // more elements.
210 bool isLittleEndian = TD.isLittleEndian();
211
212 SmallVector<Constant*, 32> Result;
213 if (NumDstElt < NumSrcElt) {
214 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
215 Constant *Zero = Constant::getNullValue(DstEltTy);
216 unsigned Ratio = NumSrcElt/NumDstElt;
217 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
218 unsigned SrcElt = 0;
219 for (unsigned i = 0; i != NumDstElt; ++i) {
220 // Build each element of the result.
221 Constant *Elt = Zero;
222 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
223 for (unsigned j = 0; j != Ratio; ++j) {
224 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
225 if (!Src) return 0; // Reject constantexpr elements.
226
227 // Zero extend the element to the right size.
228 Src = ConstantExpr::getZExt(Src, Elt->getType());
229
230 // Shift it to the right place, depending on endianness.
231 Src = ConstantExpr::getShl(Src,
232 ConstantInt::get(Src->getType(), ShiftAmt));
233 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
234
235 // Mix it in.
236 Elt = ConstantExpr::getOr(Elt, Src);
237 }
238 Result.push_back(Elt);
239 }
240 } else {
241 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
242 unsigned Ratio = NumDstElt/NumSrcElt;
243 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
244
245 // Loop over each source value, expanding into multiple results.
246 for (unsigned i = 0; i != NumSrcElt; ++i) {
247 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
248 if (!Src) return 0; // Reject constantexpr elements.
249
250 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
251 for (unsigned j = 0; j != Ratio; ++j) {
252 // Shift the piece of the value into the right place, depending on
253 // endianness.
254 Constant *Elt = ConstantExpr::getLShr(Src,
255 ConstantInt::get(Src->getType(), ShiftAmt));
256 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
257
258 // Truncate and remember this piece.
259 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
260 }
261 }
262 }
263
264 return ConstantVector::get(&Result[0], Result.size());
265 }
266 }
267
268 return 0;
269}
270
Chris Lattner03dd25c2007-01-31 00:51:48 +0000271
272//===----------------------------------------------------------------------===//
273// Constant Folding public APIs
274//===----------------------------------------------------------------------===//
275
276
Chris Lattner55207322007-01-30 23:45:45 +0000277/// ConstantFoldInstruction - Attempt to constant fold the specified
278/// instruction. If successful, the constant result is returned, if not, null
279/// is returned. Note that this function can only fail when attempting to fold
280/// instructions like loads and stores, which have no constant expression form.
281///
282Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
283 if (PHINode *PN = dyn_cast<PHINode>(I)) {
284 if (PN->getNumIncomingValues() == 0)
285 return Constant::getNullValue(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000286
Chris Lattner55207322007-01-30 23:45:45 +0000287 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
288 if (Result == 0) return 0;
289
290 // Handle PHI nodes specially here...
291 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
292 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
293 return 0; // Not all the same incoming constants...
294
295 // If we reach here, all incoming values are the same constant.
296 return Result;
297 }
298
299 // Scan the operand list, checking to see if they are all constants, if so,
300 // hand off to ConstantFoldInstOperands.
301 SmallVector<Constant*, 8> Ops;
302 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
303 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
304 Ops.push_back(Op);
305 else
306 return 0; // All operands not constant!
307
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000308 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
309 return ConstantFoldCompareInstOperands(CI->getPredicate(),
310 &Ops[0], Ops.size(), TD);
311 else
312 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
313 &Ops[0], Ops.size(), TD);
Chris Lattner55207322007-01-30 23:45:45 +0000314}
315
316/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
317/// specified opcode and operands. If successful, the constant result is
318/// returned, if not, null is returned. Note that this function can fail when
319/// attempting to fold instructions like loads and stores, which have no
320/// constant expression form.
321///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000322Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
323 Constant* const* Ops, unsigned NumOps,
Chris Lattner55207322007-01-30 23:45:45 +0000324 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000325 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000326 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000327 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000328 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000329 return C;
330
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000331 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000332 }
Chris Lattner55207322007-01-30 23:45:45 +0000333
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000334 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000335 default: return 0;
336 case Instruction::Call:
337 if (Function *F = dyn_cast<Function>(Ops[0]))
338 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000339 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000340 return 0;
341 case Instruction::ICmp:
342 case Instruction::FCmp:
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000343 assert(0 &&"This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000344 case Instruction::PtrToInt:
345 // If the input is a inttoptr, eliminate the pair. This requires knowing
346 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
347 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
348 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
349 Constant *Input = CE->getOperand(0);
350 unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
351 Constant *Mask =
352 ConstantInt::get(APInt::getLowBitsSet(InWidth,
353 TD->getPointerSizeInBits()));
354 Input = ConstantExpr::getAnd(Input, Mask);
355 // Do a zext or trunc to get to the dest size.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000356 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000357 }
358 }
Chris Lattner1afab9c2007-12-11 07:29:44 +0000359 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000360 case Instruction::IntToPtr:
Chris Lattner55207322007-01-30 23:45:45 +0000361 case Instruction::Trunc:
362 case Instruction::ZExt:
363 case Instruction::SExt:
364 case Instruction::FPTrunc:
365 case Instruction::FPExt:
366 case Instruction::UIToFP:
367 case Instruction::SIToFP:
368 case Instruction::FPToUI:
369 case Instruction::FPToSI:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000370 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000371 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000372 if (TD)
373 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD))
374 return C;
375 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000376 case Instruction::Select:
377 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
378 case Instruction::ExtractElement:
379 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
380 case Instruction::InsertElement:
381 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
382 case Instruction::ShuffleVector:
383 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
384 case Instruction::GetElementPtr:
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000385 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000386 return C;
387
Chris Lattnerd917fe52007-01-31 04:42:05 +0000388 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000389 }
390}
391
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000392/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
393/// instruction (icmp/fcmp) with the specified operands. If it fails, it
394/// returns a constant expression of the specified operands.
395///
396Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
397 Constant*const * Ops,
398 unsigned NumOps,
399 const TargetData *TD) {
400 // fold: icmp (inttoptr x), null -> icmp x, 0
401 // fold: icmp (ptrtoint x), 0 -> icmp x, null
402 // fold: icmp (inttoptr x), (inttoptr y) -> icmp x, y
403 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
404 //
405 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
406 // around to know if bit truncation is happening.
407 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
408 if (TD && Ops[1]->isNullValue()) {
409 const Type *IntPtrTy = TD->getIntPtrType();
410 if (CE0->getOpcode() == Instruction::IntToPtr) {
411 // Convert the integer value to the right size to ensure we get the
412 // proper extension or truncation.
413 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
414 IntPtrTy, false);
415 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
416 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
417 }
418
419 // Only do this transformation if the int is intptrty in size, otherwise
420 // there is a truncation or extension that we aren't modeling.
421 if (CE0->getOpcode() == Instruction::PtrToInt &&
422 CE0->getType() == IntPtrTy) {
423 Constant *C = CE0->getOperand(0);
424 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
425 // FIXME!
426 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
427 }
428 }
429
430 if (TD && isa<ConstantExpr>(Ops[1]) &&
431 cast<ConstantExpr>(Ops[1])->getOpcode() == CE0->getOpcode()) {
432 const Type *IntPtrTy = TD->getIntPtrType();
433 // Only do this transformation if the int is intptrty in size, otherwise
434 // there is a truncation or extension that we aren't modeling.
435 if ((CE0->getOpcode() == Instruction::IntToPtr &&
436 CE0->getOperand(0)->getType() == IntPtrTy &&
Chris Lattner7f135cc2007-12-12 03:56:54 +0000437 Ops[1]->getOperand(0)->getType() == IntPtrTy) ||
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000438 (CE0->getOpcode() == Instruction::PtrToInt &&
439 CE0->getType() == IntPtrTy &&
Chris Lattner7f135cc2007-12-12 03:56:54 +0000440 CE0->getOperand(0)->getType() == Ops[1]->getOperand(0)->getType())) {
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000441 Constant *NewOps[] = {
442 CE0->getOperand(0), cast<ConstantExpr>(Ops[1])->getOperand(0)
443 };
444 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
445 }
446 }
447 }
448 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
449}
450
451
Chris Lattner55207322007-01-30 23:45:45 +0000452/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
453/// getelementptr constantexpr, return the constant value being addressed by the
454/// constant expression, or null if something is funny and we can't decide.
455Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
456 ConstantExpr *CE) {
457 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
458 return 0; // Do not allow stepping over the value!
459
460 // Loop over all of the operands, tracking down which value we are
461 // addressing...
462 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
463 for (++I; I != E; ++I)
464 if (const StructType *STy = dyn_cast<StructType>(*I)) {
465 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
466 assert(CU->getZExtValue() < STy->getNumElements() &&
467 "Struct index out of range!");
468 unsigned El = (unsigned)CU->getZExtValue();
469 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
470 C = CS->getOperand(El);
471 } else if (isa<ConstantAggregateZero>(C)) {
472 C = Constant::getNullValue(STy->getElementType(El));
473 } else if (isa<UndefValue>(C)) {
474 C = UndefValue::get(STy->getElementType(El));
475 } else {
476 return 0;
477 }
478 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
479 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
480 if (CI->getZExtValue() >= ATy->getNumElements())
481 return 0;
482 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
483 C = CA->getOperand(CI->getZExtValue());
484 else if (isa<ConstantAggregateZero>(C))
485 C = Constant::getNullValue(ATy->getElementType());
486 else if (isa<UndefValue>(C))
487 C = UndefValue::get(ATy->getElementType());
488 else
489 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000490 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
Chris Lattner55207322007-01-30 23:45:45 +0000491 if (CI->getZExtValue() >= PTy->getNumElements())
492 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000493 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000494 C = CP->getOperand(CI->getZExtValue());
495 else if (isa<ConstantAggregateZero>(C))
496 C = Constant::getNullValue(PTy->getElementType());
497 else if (isa<UndefValue>(C))
498 C = UndefValue::get(PTy->getElementType());
499 else
500 return 0;
501 } else {
502 return 0;
503 }
504 } else {
505 return 0;
506 }
507 return C;
508}
509
510
511//===----------------------------------------------------------------------===//
512// Constant Folding for Calls
513//
John Criswellbd9d3702005-10-27 16:00:10 +0000514
515/// canConstantFoldCallTo - Return true if its even possible to fold a call to
516/// the specified function.
517bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000518llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000519 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000520 case Intrinsic::sqrt:
521 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000522 case Intrinsic::bswap:
523 case Intrinsic::ctpop:
524 case Intrinsic::ctlz:
525 case Intrinsic::cttz:
John Criswellbd9d3702005-10-27 16:00:10 +0000526 return true;
527 default: break;
528 }
529
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000530 const ValueName *NameVal = F->getValueName();
Chris Lattnera099b6c2007-08-08 16:07:23 +0000531 if (NameVal == 0) return false;
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000532 const char *Str = NameVal->getKeyData();
533 unsigned Len = NameVal->getKeyLength();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000534
535 // In these cases, the check of the length is required. We don't want to
536 // return true for a name like "cos\0blah" which strcmp would return equal to
537 // "cos", but has length 8.
538 switch (Str[0]) {
539 default: return false;
540 case 'a':
541 if (Len == 4)
542 return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
543 !strcmp(Str, "atan");
544 else if (Len == 5)
545 return !strcmp(Str, "atan2");
546 return false;
547 case 'c':
548 if (Len == 3)
549 return !strcmp(Str, "cos");
550 else if (Len == 4)
551 return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
552 !strcmp(Str, "cosh");
553 return false;
554 case 'e':
555 if (Len == 3)
556 return !strcmp(Str, "exp");
557 return false;
558 case 'f':
559 if (Len == 4)
560 return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
561 else if (Len == 5)
562 return !strcmp(Str, "floor");
563 return false;
564 break;
565 case 'l':
566 if (Len == 3 && !strcmp(Str, "log"))
567 return true;
568 if (Len == 5 && !strcmp(Str, "log10"))
569 return true;
570 return false;
571 case 'p':
572 if (Len == 3 && !strcmp(Str, "pow"))
573 return true;
574 return false;
575 case 's':
576 if (Len == 3)
577 return !strcmp(Str, "sin");
578 if (Len == 4)
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000579 return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
580 !strcmp(Str, "sinf");
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000581 if (Len == 5)
582 return !strcmp(Str, "sqrtf");
583 return false;
584 case 't':
585 if (Len == 3 && !strcmp(Str, "tan"))
586 return true;
587 else if (Len == 4 && !strcmp(Str, "tanh"))
588 return true;
589 return false;
John Criswellbd9d3702005-10-27 16:00:10 +0000590 }
591}
592
Chris Lattner72d88ae2007-01-30 23:15:43 +0000593static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
594 const Type *Ty) {
John Criswellbd9d3702005-10-27 16:00:10 +0000595 errno = 0;
596 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000597 if (errno != 0) {
598 errno = 0;
599 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000600 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000601
602 if (Ty == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000603 return ConstantFP::get(APFloat((float)V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000604 if (Ty == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000605 return ConstantFP::get(APFloat(V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000606 assert(0 && "Can only constant fold float/double");
John Criswellbd9d3702005-10-27 16:00:10 +0000607}
608
Dan Gohman38415242007-07-16 15:26:22 +0000609static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
610 double V, double W,
611 const Type *Ty) {
612 errno = 0;
613 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000614 if (errno != 0) {
615 errno = 0;
616 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000617 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000618
619 if (Ty == Type::FloatTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000620 return ConstantFP::get(APFloat((float)V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000621 if (Ty == Type::DoubleTy)
Chris Lattner02a260a2008-04-20 00:41:09 +0000622 return ConstantFP::get(APFloat(V));
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000623 assert(0 && "Can only constant fold float/double");
Dan Gohman38415242007-07-16 15:26:22 +0000624}
625
John Criswellbd9d3702005-10-27 16:00:10 +0000626/// ConstantFoldCall - Attempt to constant fold a call to the specified function
627/// with the specified arguments, returning null if unsuccessful.
Dale Johannesen43421b32007-09-06 18:13:44 +0000628
John Criswellbd9d3702005-10-27 16:00:10 +0000629Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000630llvm::ConstantFoldCall(Function *F,
631 Constant* const* Operands, unsigned NumOperands) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000632 const ValueName *NameVal = F->getValueName();
Chris Lattnera099b6c2007-08-08 16:07:23 +0000633 if (NameVal == 0) return 0;
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000634 const char *Str = NameVal->getKeyData();
635 unsigned Len = NameVal->getKeyLength();
636
John Criswellbd9d3702005-10-27 16:00:10 +0000637 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000638 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000639 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Dale Johannesen43421b32007-09-06 18:13:44 +0000640 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
641 return 0;
642 /// Currently APFloat versions of these functions do not exist, so we use
643 /// the host native double versions. Float versions are not called
644 /// directly but for all these it is true (float)(f((double)arg)) ==
645 /// f(arg). Long double not supported yet.
646 double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
647 Op->getValueAPF().convertToDouble();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000648 switch (Str[0]) {
649 case 'a':
650 if (Len == 4 && !strcmp(Str, "acos"))
651 return ConstantFoldFP(acos, V, Ty);
652 else if (Len == 4 && !strcmp(Str, "asin"))
653 return ConstantFoldFP(asin, V, Ty);
654 else if (Len == 4 && !strcmp(Str, "atan"))
655 return ConstantFoldFP(atan, V, Ty);
656 break;
657 case 'c':
658 if (Len == 4 && !strcmp(Str, "ceil"))
659 return ConstantFoldFP(ceil, V, Ty);
660 else if (Len == 3 && !strcmp(Str, "cos"))
661 return ConstantFoldFP(cos, V, Ty);
662 else if (Len == 4 && !strcmp(Str, "cosh"))
663 return ConstantFoldFP(cosh, V, Ty);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000664 else if (Len == 4 && !strcmp(Str, "cosf"))
665 return ConstantFoldFP(cos, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000666 break;
667 case 'e':
668 if (Len == 3 && !strcmp(Str, "exp"))
669 return ConstantFoldFP(exp, V, Ty);
670 break;
671 case 'f':
672 if (Len == 4 && !strcmp(Str, "fabs"))
Dale Johannesen43421b32007-09-06 18:13:44 +0000673 return ConstantFoldFP(fabs, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000674 else if (Len == 5 && !strcmp(Str, "floor"))
675 return ConstantFoldFP(floor, V, Ty);
676 break;
677 case 'l':
678 if (Len == 3 && !strcmp(Str, "log") && V > 0)
679 return ConstantFoldFP(log, V, Ty);
680 else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
681 return ConstantFoldFP(log10, V, Ty);
682 else if (!strcmp(Str, "llvm.sqrt.f32") ||
683 !strcmp(Str, "llvm.sqrt.f64")) {
684 if (V >= -0.0)
Dale Johannesen43421b32007-09-06 18:13:44 +0000685 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000686 else // Undefined
Chris Lattner02a260a2008-04-20 00:41:09 +0000687 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000688 }
689 break;
690 case 's':
691 if (Len == 3 && !strcmp(Str, "sin"))
692 return ConstantFoldFP(sin, V, Ty);
693 else if (Len == 4 && !strcmp(Str, "sinh"))
694 return ConstantFoldFP(sinh, V, Ty);
695 else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
696 return ConstantFoldFP(sqrt, V, Ty);
697 else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
698 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000699 else if (Len == 4 && !strcmp(Str, "sinf"))
700 return ConstantFoldFP(sin, V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000701 break;
702 case 't':
703 if (Len == 3 && !strcmp(Str, "tan"))
704 return ConstantFoldFP(tan, V, Ty);
705 else if (Len == 4 && !strcmp(Str, "tanh"))
706 return ConstantFoldFP(tanh, V, Ty);
707 break;
708 default:
709 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000710 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000711 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Chris Lattnerecc02742007-11-23 22:34:59 +0000712 if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
Reid Spencere9391fd2007-04-01 07:35:23 +0000713 return ConstantInt::get(Op->getValue().byteSwap());
Chris Lattnerecc02742007-11-23 22:34:59 +0000714 else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
715 return ConstantInt::get(Ty, Op->getValue().countPopulation());
716 else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
717 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
718 else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
719 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
John Criswellbd9d3702005-10-27 16:00:10 +0000720 }
Chris Lattner72d88ae2007-01-30 23:15:43 +0000721 } else if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000722 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000723 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
724 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000725 double Op1V = Ty==Type::FloatTy ?
726 (double)Op1->getValueAPF().convertToFloat():
727 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000728 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Dale Johannesen43421b32007-09-06 18:13:44 +0000729 double Op2V = Ty==Type::FloatTy ?
730 (double)Op2->getValueAPF().convertToFloat():
731 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000732
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000733 if (Len == 3 && !strcmp(Str, "pow")) {
Dan Gohman38415242007-07-16 15:26:22 +0000734 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000735 } else if (Len == 4 && !strcmp(Str, "fmod")) {
Dan Gohman38415242007-07-16 15:26:22 +0000736 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000737 } else if (Len == 5 && !strcmp(Str, "atan2")) {
Dan Gohman38415242007-07-16 15:26:22 +0000738 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000739 }
740 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000741 if (!strcmp(Str, "llvm.powi.f32")) {
Chris Lattner02a260a2008-04-20 00:41:09 +0000742 return ConstantFP::get(APFloat((float)std::pow((float)Op1V,
743 (int)Op2C->getZExtValue())));
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000744 } else if (!strcmp(Str, "llvm.powi.f64")) {
Chris Lattner02a260a2008-04-20 00:41:09 +0000745 return ConstantFP::get(APFloat((double)std::pow((double)Op1V,
746 (int)Op2C->getZExtValue())));
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000747 }
John Criswellbd9d3702005-10-27 16:00:10 +0000748 }
749 }
750 }
751 return 0;
752}
753