1 //===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions determines the possibility of performing constant
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/MathExtras.h"
32 //===----------------------------------------------------------------------===//
33 // Constant Folding internal helper functions
34 //===----------------------------------------------------------------------===//
36 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
37 /// from a global, return the global and the constant. Because of
38 /// constantexprs, this function is recursive.
39 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
40 int64_t &Offset, const TargetData &TD) {
41 // Trivial case, constant is the global.
42 if ((GV = dyn_cast<GlobalValue>(C))) {
47 // Otherwise, if this isn't a constant expr, bail out.
48 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
49 if (!CE) return false;
51 // Look through ptr->int and ptr->ptr casts.
52 if (CE->getOpcode() == Instruction::PtrToInt ||
53 CE->getOpcode() == Instruction::BitCast)
54 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
56 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
57 if (CE->getOpcode() == Instruction::GetElementPtr) {
58 // Cannot compute this if the element type of the pointer is missing size
60 if (!cast<PointerType>(CE->getOperand(0)->getType())
61 ->getElementType()->isSized())
64 // If the base isn't a global+constant, we aren't either.
65 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
68 // Otherwise, add any offset that our operands provide.
69 gep_type_iterator GTI = gep_type_begin(CE);
70 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
72 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
73 if (!CI) return false; // Index isn't a simple constant?
74 if (CI->getZExtValue() == 0) continue; // Not adding anything.
76 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
78 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
80 const SequentialType *SQT = cast<SequentialType>(*GTI);
81 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
91 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
92 /// Attempt to symbolically evaluate the result of a binary operator merging
93 /// these together. If target data info is available, it is provided as TD,
94 /// otherwise TD is null.
95 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
96 Constant *Op1, const TargetData *TD,
97 LLVMContext *Context){
100 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
101 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
105 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
106 // constant. This happens frequently when iterating over a global array.
107 if (Opc == Instruction::Sub && TD) {
108 GlobalValue *GV1, *GV2;
109 int64_t Offs1, Offs2;
111 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
112 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
114 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
115 return Context->getConstantInt(Op0->getType(), Offs1-Offs2);
122 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
123 /// constant expression, do so.
124 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
125 const Type *ResultTy,
126 LLVMContext *Context,
127 const TargetData *TD) {
128 Constant *Ptr = Ops[0];
129 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
132 uint64_t BasePtr = 0;
133 if (!Ptr->isNullValue()) {
134 // If this is a inttoptr from a constant int, we can fold this as the base,
135 // otherwise we can't.
136 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
137 if (CE->getOpcode() == Instruction::IntToPtr)
138 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
139 BasePtr = Base->getZExtValue();
145 // If this is a constant expr gep that is effectively computing an
146 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
147 for (unsigned i = 1; i != NumOps; ++i)
148 if (!isa<ConstantInt>(Ops[i]))
151 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
152 (Value**)Ops+1, NumOps-1);
153 Constant *C = Context->getConstantInt(TD->getIntPtrType(), Offset+BasePtr);
154 return Context->getConstantExprIntToPtr(C, ResultTy);
157 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
158 /// targetdata. Return 0 if unfoldable.
159 static Constant *FoldBitCast(Constant *C, const Type *DestTy,
160 const TargetData &TD, LLVMContext *Context) {
161 // If this is a bitcast from constant vector -> vector, fold it.
162 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
163 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
164 // If the element types match, VMCore can fold it.
165 unsigned NumDstElt = DestVTy->getNumElements();
166 unsigned NumSrcElt = CV->getNumOperands();
167 if (NumDstElt == NumSrcElt)
170 const Type *SrcEltTy = CV->getType()->getElementType();
171 const Type *DstEltTy = DestVTy->getElementType();
173 // Otherwise, we're changing the number of elements in a vector, which
174 // requires endianness information to do the right thing. For example,
175 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
176 // folds to (little endian):
177 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
178 // and to (big endian):
179 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
181 // First thing is first. We only want to think about integer here, so if
182 // we have something in FP form, recast it as integer.
183 if (DstEltTy->isFloatingPoint()) {
184 // Fold to an vector of integers with same size as our FP type.
185 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
186 const Type *DestIVTy = Context->getVectorType(
187 Context->getIntegerType(FPWidth), NumDstElt);
188 // Recursively handle this integer conversion, if possible.
189 C = FoldBitCast(C, DestIVTy, TD, Context);
192 // Finally, VMCore can handle this now that #elts line up.
193 return Context->getConstantExprBitCast(C, DestTy);
196 // Okay, we know the destination is integer, if the input is FP, convert
197 // it to integer first.
198 if (SrcEltTy->isFloatingPoint()) {
199 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
200 const Type *SrcIVTy = Context->getVectorType(
201 Context->getIntegerType(FPWidth), NumSrcElt);
202 // Ask VMCore to do the conversion now that #elts line up.
203 C = Context->getConstantExprBitCast(C, SrcIVTy);
204 CV = dyn_cast<ConstantVector>(C);
205 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
208 // Now we know that the input and output vectors are both integer vectors
209 // of the same size, and that their #elements is not the same. Do the
210 // conversion here, which depends on whether the input or output has
212 bool isLittleEndian = TD.isLittleEndian();
214 SmallVector<Constant*, 32> Result;
215 if (NumDstElt < NumSrcElt) {
216 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
217 Constant *Zero = Context->getNullValue(DstEltTy);
218 unsigned Ratio = NumSrcElt/NumDstElt;
219 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
221 for (unsigned i = 0; i != NumDstElt; ++i) {
222 // Build each element of the result.
223 Constant *Elt = Zero;
224 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
225 for (unsigned j = 0; j != Ratio; ++j) {
226 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
227 if (!Src) return 0; // Reject constantexpr elements.
229 // Zero extend the element to the right size.
230 Src = Context->getConstantExprZExt(Src, Elt->getType());
232 // Shift it to the right place, depending on endianness.
233 Src = Context->getConstantExprShl(Src,
234 Context->getConstantInt(Src->getType(), ShiftAmt));
235 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
238 Elt = Context->getConstantExprOr(Elt, Src);
240 Result.push_back(Elt);
243 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
244 unsigned Ratio = NumDstElt/NumSrcElt;
245 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
247 // Loop over each source value, expanding into multiple results.
248 for (unsigned i = 0; i != NumSrcElt; ++i) {
249 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
250 if (!Src) return 0; // Reject constantexpr elements.
252 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
253 for (unsigned j = 0; j != Ratio; ++j) {
254 // Shift the piece of the value into the right place, depending on
256 Constant *Elt = Context->getConstantExprLShr(Src,
257 Context->getConstantInt(Src->getType(), ShiftAmt));
258 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
260 // Truncate and remember this piece.
261 Result.push_back(Context->getConstantExprTrunc(Elt, DstEltTy));
266 return Context->getConstantVector(Result.data(), Result.size());
274 //===----------------------------------------------------------------------===//
275 // Constant Folding public APIs
276 //===----------------------------------------------------------------------===//
279 /// ConstantFoldInstruction - Attempt to constant fold the specified
280 /// instruction. If successful, the constant result is returned, if not, null
281 /// is returned. Note that this function can only fail when attempting to fold
282 /// instructions like loads and stores, which have no constant expression form.
284 Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext *Context,
285 const TargetData *TD) {
286 if (PHINode *PN = dyn_cast<PHINode>(I)) {
287 if (PN->getNumIncomingValues() == 0)
288 return Context->getUndef(PN->getType());
290 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
291 if (Result == 0) return 0;
293 // Handle PHI nodes specially here...
294 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
295 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
296 return 0; // Not all the same incoming constants...
298 // If we reach here, all incoming values are the same constant.
302 // Scan the operand list, checking to see if they are all constants, if so,
303 // hand off to ConstantFoldInstOperands.
304 SmallVector<Constant*, 8> Ops;
305 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
306 if (Constant *Op = dyn_cast<Constant>(*i))
309 return 0; // All operands not constant!
311 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
312 return ConstantFoldCompareInstOperands(CI->getPredicate(),
313 Ops.data(), Ops.size(),
316 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
317 Ops.data(), Ops.size(), Context, TD);
320 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
321 /// using the specified TargetData. If successful, the constant result is
322 /// result is returned, if not, null is returned.
323 Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
324 LLVMContext *Context,
325 const TargetData *TD) {
326 SmallVector<Constant*, 8> Ops;
327 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
328 Ops.push_back(cast<Constant>(*i));
331 return ConstantFoldCompareInstOperands(CE->getPredicate(),
332 Ops.data(), Ops.size(),
335 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
336 Ops.data(), Ops.size(), Context, TD);
339 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
340 /// specified opcode and operands. If successful, the constant result is
341 /// returned, if not, null is returned. Note that this function can fail when
342 /// attempting to fold instructions like loads and stores, which have no
343 /// constant expression form.
345 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
346 Constant* const* Ops, unsigned NumOps,
347 LLVMContext *Context,
348 const TargetData *TD) {
349 // Handle easy binops first.
350 if (Instruction::isBinaryOp(Opcode)) {
351 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
352 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
356 return Context->getConstantExpr(Opcode, Ops[0], Ops[1]);
361 case Instruction::Call:
362 if (Function *F = dyn_cast<Function>(Ops[0]))
363 if (canConstantFoldCallTo(F))
364 return ConstantFoldCall(F, Ops+1, NumOps-1);
366 case Instruction::ICmp:
367 case Instruction::FCmp:
368 assert(0 &&"This function is invalid for compares: no predicate specified");
369 case Instruction::PtrToInt:
370 // If the input is a inttoptr, eliminate the pair. This requires knowing
371 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
373 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
374 Constant *Input = CE->getOperand(0);
375 unsigned InWidth = Input->getType()->getScalarSizeInBits();
376 if (TD->getPointerSizeInBits() < InWidth) {
378 Context->getConstantInt(APInt::getLowBitsSet(InWidth,
379 TD->getPointerSizeInBits()));
380 Input = Context->getConstantExprAnd(Input, Mask);
382 // Do a zext or trunc to get to the dest size.
383 return Context->getConstantExprIntegerCast(Input, DestTy, false);
386 return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
387 case Instruction::IntToPtr:
388 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
389 // the int size is >= the ptr size. This requires knowing the width of a
390 // pointer, so it can't be done in ConstantExpr::getCast.
391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
393 TD->getPointerSizeInBits() <=
394 CE->getType()->getScalarSizeInBits()) {
395 if (CE->getOpcode() == Instruction::PtrToInt) {
396 Constant *Input = CE->getOperand(0);
397 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
398 return C ? C : Context->getConstantExprBitCast(Input, DestTy);
400 // If there's a constant offset added to the integer value before
401 // it is casted back to a pointer, see if the expression can be
402 // converted into a GEP.
403 if (CE->getOpcode() == Instruction::Add)
404 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
405 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
406 if (R->getOpcode() == Instruction::PtrToInt)
407 if (GlobalVariable *GV =
408 dyn_cast<GlobalVariable>(R->getOperand(0))) {
409 const PointerType *GVTy = cast<PointerType>(GV->getType());
410 if (const ArrayType *AT =
411 dyn_cast<ArrayType>(GVTy->getElementType())) {
412 const Type *ElTy = AT->getElementType();
413 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
414 APInt PSA(L->getValue().getBitWidth(), AllocSize);
415 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
416 L->getValue().urem(PSA) == 0) {
417 APInt ElemIdx = L->getValue().udiv(PSA);
418 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
419 AT->getNumElements()))) {
420 Constant *Index[] = {
421 Context->getNullValue(CE->getType()),
422 Context->getConstantInt(ElemIdx)
425 Context->getConstantExprGetElementPtr(GV, &Index[0], 2);
432 return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
433 case Instruction::Trunc:
434 case Instruction::ZExt:
435 case Instruction::SExt:
436 case Instruction::FPTrunc:
437 case Instruction::FPExt:
438 case Instruction::UIToFP:
439 case Instruction::SIToFP:
440 case Instruction::FPToUI:
441 case Instruction::FPToSI:
442 return Context->getConstantExprCast(Opcode, Ops[0], DestTy);
443 case Instruction::BitCast:
445 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
447 return Context->getConstantExprBitCast(Ops[0], DestTy);
448 case Instruction::Select:
449 return Context->getConstantExprSelect(Ops[0], Ops[1], Ops[2]);
450 case Instruction::ExtractElement:
451 return Context->getConstantExprExtractElement(Ops[0], Ops[1]);
452 case Instruction::InsertElement:
453 return Context->getConstantExprInsertElement(Ops[0], Ops[1], Ops[2]);
454 case Instruction::ShuffleVector:
455 return Context->getConstantExprShuffleVector(Ops[0], Ops[1], Ops[2]);
456 case Instruction::GetElementPtr:
457 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
460 return Context->getConstantExprGetElementPtr(Ops[0], Ops+1, NumOps-1);
464 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
465 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
466 /// returns a constant expression of the specified operands.
468 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
469 Constant*const * Ops,
471 LLVMContext *Context,
472 const TargetData *TD) {
473 // fold: icmp (inttoptr x), null -> icmp x, 0
474 // fold: icmp (ptrtoint x), 0 -> icmp x, null
475 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
476 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
478 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
479 // around to know if bit truncation is happening.
480 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
481 if (TD && Ops[1]->isNullValue()) {
482 const Type *IntPtrTy = TD->getIntPtrType();
483 if (CE0->getOpcode() == Instruction::IntToPtr) {
484 // Convert the integer value to the right size to ensure we get the
485 // proper extension or truncation.
486 Constant *C = Context->getConstantExprIntegerCast(CE0->getOperand(0),
488 Constant *NewOps[] = { C, Context->getNullValue(C->getType()) };
489 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
493 // Only do this transformation if the int is intptrty in size, otherwise
494 // there is a truncation or extension that we aren't modeling.
495 if (CE0->getOpcode() == Instruction::PtrToInt &&
496 CE0->getType() == IntPtrTy) {
497 Constant *C = CE0->getOperand(0);
498 Constant *NewOps[] = { C, Context->getNullValue(C->getType()) };
500 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
505 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
506 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
507 const Type *IntPtrTy = TD->getIntPtrType();
509 if (CE0->getOpcode() == Instruction::IntToPtr) {
510 // Convert the integer value to the right size to ensure we get the
511 // proper extension or truncation.
512 Constant *C0 = Context->getConstantExprIntegerCast(CE0->getOperand(0),
514 Constant *C1 = Context->getConstantExprIntegerCast(CE1->getOperand(0),
516 Constant *NewOps[] = { C0, C1 };
517 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
521 // Only do this transformation if the int is intptrty in size, otherwise
522 // there is a truncation or extension that we aren't modeling.
523 if ((CE0->getOpcode() == Instruction::PtrToInt &&
524 CE0->getType() == IntPtrTy &&
525 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
526 Constant *NewOps[] = {
527 CE0->getOperand(0), CE1->getOperand(0)
529 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
535 return Context->getConstantExprCompare(Predicate, Ops[0], Ops[1]);
539 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
540 /// getelementptr constantexpr, return the constant value being addressed by the
541 /// constant expression, or null if something is funny and we can't decide.
542 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
544 LLVMContext *Context) {
545 if (CE->getOperand(1) != Context->getNullValue(CE->getOperand(1)->getType()))
546 return 0; // Do not allow stepping over the value!
548 // Loop over all of the operands, tracking down which value we are
550 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
551 for (++I; I != E; ++I)
552 if (const StructType *STy = dyn_cast<StructType>(*I)) {
553 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
554 assert(CU->getZExtValue() < STy->getNumElements() &&
555 "Struct index out of range!");
556 unsigned El = (unsigned)CU->getZExtValue();
557 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
558 C = CS->getOperand(El);
559 } else if (isa<ConstantAggregateZero>(C)) {
560 C = Context->getNullValue(STy->getElementType(El));
561 } else if (isa<UndefValue>(C)) {
562 C = Context->getUndef(STy->getElementType(El));
566 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
567 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
568 if (CI->getZExtValue() >= ATy->getNumElements())
570 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
571 C = CA->getOperand(CI->getZExtValue());
572 else if (isa<ConstantAggregateZero>(C))
573 C = Context->getNullValue(ATy->getElementType());
574 else if (isa<UndefValue>(C))
575 C = Context->getUndef(ATy->getElementType());
578 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
579 if (CI->getZExtValue() >= PTy->getNumElements())
581 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
582 C = CP->getOperand(CI->getZExtValue());
583 else if (isa<ConstantAggregateZero>(C))
584 C = Context->getNullValue(PTy->getElementType());
585 else if (isa<UndefValue>(C))
586 C = Context->getUndef(PTy->getElementType());
599 //===----------------------------------------------------------------------===//
600 // Constant Folding for Calls
603 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
604 /// the specified function.
606 llvm::canConstantFoldCallTo(const Function *F) {
607 switch (F->getIntrinsicID()) {
608 case Intrinsic::sqrt:
609 case Intrinsic::powi:
610 case Intrinsic::bswap:
611 case Intrinsic::ctpop:
612 case Intrinsic::ctlz:
613 case Intrinsic::cttz:
618 if (!F->hasName()) return false;
619 const char *Str = F->getNameStart();
620 unsigned Len = F->getNameLen();
622 // In these cases, the check of the length is required. We don't want to
623 // return true for a name like "cos\0blah" which strcmp would return equal to
624 // "cos", but has length 8.
626 default: return false;
629 return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
630 !strcmp(Str, "atan");
632 return !strcmp(Str, "atan2");
636 return !strcmp(Str, "cos");
638 return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
639 !strcmp(Str, "cosh");
643 return !strcmp(Str, "exp");
647 return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
649 return !strcmp(Str, "floor");
653 if (Len == 3 && !strcmp(Str, "log"))
655 if (Len == 5 && !strcmp(Str, "log10"))
659 if (Len == 3 && !strcmp(Str, "pow"))
664 return !strcmp(Str, "sin");
666 return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
667 !strcmp(Str, "sinf");
669 return !strcmp(Str, "sqrtf");
672 if (Len == 3 && !strcmp(Str, "tan"))
674 else if (Len == 4 && !strcmp(Str, "tanh"))
680 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
681 const Type *Ty, LLVMContext *Context) {
689 if (Ty == Type::FloatTy)
690 return Context->getConstantFP(APFloat((float)V));
691 if (Ty == Type::DoubleTy)
692 return Context->getConstantFP(APFloat(V));
693 assert(0 && "Can only constant fold float/double");
694 return 0; // dummy return to suppress warning
697 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
700 LLVMContext *Context) {
708 if (Ty == Type::FloatTy)
709 return Context->getConstantFP(APFloat((float)V));
710 if (Ty == Type::DoubleTy)
711 return Context->getConstantFP(APFloat(V));
712 assert(0 && "Can only constant fold float/double");
713 return 0; // dummy return to suppress warning
716 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
717 /// with the specified arguments, returning null if unsuccessful.
720 llvm::ConstantFoldCall(Function *F,
721 Constant* const* Operands, unsigned NumOperands) {
722 if (!F->hasName()) return 0;
723 LLVMContext *Context = F->getContext();
724 const char *Str = F->getNameStart();
725 unsigned Len = F->getNameLen();
727 const Type *Ty = F->getReturnType();
728 if (NumOperands == 1) {
729 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
730 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
732 /// Currently APFloat versions of these functions do not exist, so we use
733 /// the host native double versions. Float versions are not called
734 /// directly but for all these it is true (float)(f((double)arg)) ==
735 /// f(arg). Long double not supported yet.
736 double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
737 Op->getValueAPF().convertToDouble();
740 if (Len == 4 && !strcmp(Str, "acos"))
741 return ConstantFoldFP(acos, V, Ty, Context);
742 else if (Len == 4 && !strcmp(Str, "asin"))
743 return ConstantFoldFP(asin, V, Ty, Context);
744 else if (Len == 4 && !strcmp(Str, "atan"))
745 return ConstantFoldFP(atan, V, Ty, Context);
748 if (Len == 4 && !strcmp(Str, "ceil"))
749 return ConstantFoldFP(ceil, V, Ty, Context);
750 else if (Len == 3 && !strcmp(Str, "cos"))
751 return ConstantFoldFP(cos, V, Ty, Context);
752 else if (Len == 4 && !strcmp(Str, "cosh"))
753 return ConstantFoldFP(cosh, V, Ty, Context);
754 else if (Len == 4 && !strcmp(Str, "cosf"))
755 return ConstantFoldFP(cos, V, Ty, Context);
758 if (Len == 3 && !strcmp(Str, "exp"))
759 return ConstantFoldFP(exp, V, Ty, Context);
762 if (Len == 4 && !strcmp(Str, "fabs"))
763 return ConstantFoldFP(fabs, V, Ty, Context);
764 else if (Len == 5 && !strcmp(Str, "floor"))
765 return ConstantFoldFP(floor, V, Ty, Context);
768 if (Len == 3 && !strcmp(Str, "log") && V > 0)
769 return ConstantFoldFP(log, V, Ty, Context);
770 else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
771 return ConstantFoldFP(log10, V, Ty, Context);
772 else if (!strcmp(Str, "llvm.sqrt.f32") ||
773 !strcmp(Str, "llvm.sqrt.f64")) {
775 return ConstantFoldFP(sqrt, V, Ty, Context);
777 return Context->getNullValue(Ty);
781 if (Len == 3 && !strcmp(Str, "sin"))
782 return ConstantFoldFP(sin, V, Ty, Context);
783 else if (Len == 4 && !strcmp(Str, "sinh"))
784 return ConstantFoldFP(sinh, V, Ty, Context);
785 else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
786 return ConstantFoldFP(sqrt, V, Ty, Context);
787 else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
788 return ConstantFoldFP(sqrt, V, Ty, Context);
789 else if (Len == 4 && !strcmp(Str, "sinf"))
790 return ConstantFoldFP(sin, V, Ty, Context);
793 if (Len == 3 && !strcmp(Str, "tan"))
794 return ConstantFoldFP(tan, V, Ty, Context);
795 else if (Len == 4 && !strcmp(Str, "tanh"))
796 return ConstantFoldFP(tanh, V, Ty, Context);
801 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
802 if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
803 return Context->getConstantInt(Op->getValue().byteSwap());
804 else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
805 return Context->getConstantInt(Ty, Op->getValue().countPopulation());
806 else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
807 return Context->getConstantInt(Ty, Op->getValue().countTrailingZeros());
808 else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
809 return Context->getConstantInt(Ty, Op->getValue().countLeadingZeros());
811 } else if (NumOperands == 2) {
812 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
813 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
815 double Op1V = Ty==Type::FloatTy ?
816 (double)Op1->getValueAPF().convertToFloat():
817 Op1->getValueAPF().convertToDouble();
818 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
819 double Op2V = Ty==Type::FloatTy ?
820 (double)Op2->getValueAPF().convertToFloat():
821 Op2->getValueAPF().convertToDouble();
823 if (Len == 3 && !strcmp(Str, "pow")) {
824 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
825 } else if (Len == 4 && !strcmp(Str, "fmod")) {
826 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
827 } else if (Len == 5 && !strcmp(Str, "atan2")) {
828 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
830 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
831 if (!strcmp(Str, "llvm.powi.f32")) {
832 return Context->getConstantFP(APFloat((float)std::pow((float)Op1V,
833 (int)Op2C->getZExtValue())));
834 } else if (!strcmp(Str, "llvm.powi.f64")) {
835 return Context->getConstantFP(APFloat((double)std::pow((double)Op1V,
836 (int)Op2C->getZExtValue())));