1 //===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 #include "llvm/Support/MathExtras.h"
30 //===----------------------------------------------------------------------===//
31 // Constant Folding internal helper functions
32 //===----------------------------------------------------------------------===//
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.
37 static 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))) {
45 // Otherwise, if this isn't a constant expr, bail out.
46 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
47 if (!CE) return false;
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);
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
58 if (!cast<PointerType>(CE->getOperand(0)->getType())
59 ->getElementType()->isSized())
62 // If the base isn't a global+constant, we aren't either.
63 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
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.
73 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
75 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
77 const SequentialType *SQT = cast<SequentialType>(*GTI);
78 Offset += TD.getABITypeSize(SQT->getElementType())*CI->getSExtValue();
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.
92 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
93 Constant *Op1, const TargetData *TD){
96 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
97 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
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;
107 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
108 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
110 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
111 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
115 // TODO: Fold icmp setne/seteq as well.
119 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
120 /// constant expression, do so.
121 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
122 const Type *ResultTy,
123 const TargetData *TD) {
124 Constant *Ptr = Ops[0];
125 if (!cast<PointerType>(Ptr->getType())->getElementType()->isSized())
128 if (TD && Ptr->isNullValue()) {
129 // If this is a constant expr gep that is effectively computing an
130 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
131 bool isFoldableGEP = true;
132 for (unsigned i = 1; i != NumOps; ++i)
133 if (!isa<ConstantInt>(Ops[i])) {
134 isFoldableGEP = false;
138 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
139 (Value**)Ops+1, NumOps-1);
140 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
141 return ConstantExpr::getIntToPtr(C, ResultTy);
149 //===----------------------------------------------------------------------===//
150 // Constant Folding public APIs
151 //===----------------------------------------------------------------------===//
154 /// ConstantFoldInstruction - Attempt to constant fold the specified
155 /// instruction. If successful, the constant result is returned, if not, null
156 /// is returned. Note that this function can only fail when attempting to fold
157 /// instructions like loads and stores, which have no constant expression form.
159 Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
160 if (PHINode *PN = dyn_cast<PHINode>(I)) {
161 if (PN->getNumIncomingValues() == 0)
162 return Constant::getNullValue(PN->getType());
164 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
165 if (Result == 0) return 0;
167 // Handle PHI nodes specially here...
168 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
169 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
170 return 0; // Not all the same incoming constants...
172 // If we reach here, all incoming values are the same constant.
176 // Scan the operand list, checking to see if they are all constants, if so,
177 // hand off to ConstantFoldInstOperands.
178 SmallVector<Constant*, 8> Ops;
179 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
180 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
183 return 0; // All operands not constant!
185 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
186 return ConstantFoldCompareInstOperands(CI->getPredicate(),
187 &Ops[0], Ops.size(), TD);
189 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
190 &Ops[0], Ops.size(), TD);
193 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
194 /// specified opcode and operands. If successful, the constant result is
195 /// returned, if not, null is returned. Note that this function can fail when
196 /// attempting to fold instructions like loads and stores, which have no
197 /// constant expression form.
199 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
200 Constant* const* Ops, unsigned NumOps,
201 const TargetData *TD) {
202 // Handle easy binops first.
203 if (Instruction::isBinaryOp(Opcode)) {
204 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
205 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
208 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
213 case Instruction::Call:
214 if (Function *F = dyn_cast<Function>(Ops[0]))
215 if (canConstantFoldCallTo(F))
216 return ConstantFoldCall(F, Ops+1, NumOps-1);
218 case Instruction::ICmp:
219 case Instruction::FCmp:
220 assert(0 &&"This function is invalid for compares: no predicate specified");
221 case Instruction::PtrToInt:
222 // If the input is a inttoptr, eliminate the pair. This requires knowing
223 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
224 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
225 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
226 Constant *Input = CE->getOperand(0);
227 unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
229 ConstantInt::get(APInt::getLowBitsSet(InWidth,
230 TD->getPointerSizeInBits()));
231 Input = ConstantExpr::getAnd(Input, Mask);
232 // Do a zext or trunc to get to the dest size.
233 return ConstantExpr::getIntegerCast(Input, DestTy, false);
237 case Instruction::IntToPtr:
238 case Instruction::Trunc:
239 case Instruction::ZExt:
240 case Instruction::SExt:
241 case Instruction::FPTrunc:
242 case Instruction::FPExt:
243 case Instruction::UIToFP:
244 case Instruction::SIToFP:
245 case Instruction::FPToUI:
246 case Instruction::FPToSI:
247 case Instruction::BitCast:
248 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
249 case Instruction::Select:
250 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
251 case Instruction::ExtractElement:
252 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
253 case Instruction::InsertElement:
254 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
255 case Instruction::ShuffleVector:
256 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
257 case Instruction::GetElementPtr:
258 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
261 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
265 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
266 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
267 /// returns a constant expression of the specified operands.
269 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
270 Constant*const * Ops,
272 const TargetData *TD) {
273 // fold: icmp (inttoptr x), null -> icmp x, 0
274 // fold: icmp (ptrtoint x), 0 -> icmp x, null
275 // fold: icmp (inttoptr x), (inttoptr y) -> icmp x, y
276 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
278 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
279 // around to know if bit truncation is happening.
280 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
281 if (TD && Ops[1]->isNullValue()) {
282 const Type *IntPtrTy = TD->getIntPtrType();
283 if (CE0->getOpcode() == Instruction::IntToPtr) {
284 // Convert the integer value to the right size to ensure we get the
285 // proper extension or truncation.
286 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
288 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
289 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
292 // Only do this transformation if the int is intptrty in size, otherwise
293 // there is a truncation or extension that we aren't modeling.
294 if (CE0->getOpcode() == Instruction::PtrToInt &&
295 CE0->getType() == IntPtrTy) {
296 Constant *C = CE0->getOperand(0);
297 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
299 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
303 if (TD && isa<ConstantExpr>(Ops[1]) &&
304 cast<ConstantExpr>(Ops[1])->getOpcode() == CE0->getOpcode()) {
305 const Type *IntPtrTy = TD->getIntPtrType();
306 // Only do this transformation if the int is intptrty in size, otherwise
307 // there is a truncation or extension that we aren't modeling.
308 if ((CE0->getOpcode() == Instruction::IntToPtr &&
309 CE0->getOperand(0)->getType() == IntPtrTy &&
310 CE0->getOperand(1)->getType() == IntPtrTy) ||
311 (CE0->getOpcode() == Instruction::PtrToInt &&
312 CE0->getType() == IntPtrTy &&
313 CE0->getOperand(0)->getType() == CE0->getOperand(1)->getType())) {
314 Constant *NewOps[] = {
315 CE0->getOperand(0), cast<ConstantExpr>(Ops[1])->getOperand(0)
317 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
321 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
325 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
326 /// getelementptr constantexpr, return the constant value being addressed by the
327 /// constant expression, or null if something is funny and we can't decide.
328 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
330 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
331 return 0; // Do not allow stepping over the value!
333 // Loop over all of the operands, tracking down which value we are
335 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
336 for (++I; I != E; ++I)
337 if (const StructType *STy = dyn_cast<StructType>(*I)) {
338 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
339 assert(CU->getZExtValue() < STy->getNumElements() &&
340 "Struct index out of range!");
341 unsigned El = (unsigned)CU->getZExtValue();
342 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
343 C = CS->getOperand(El);
344 } else if (isa<ConstantAggregateZero>(C)) {
345 C = Constant::getNullValue(STy->getElementType(El));
346 } else if (isa<UndefValue>(C)) {
347 C = UndefValue::get(STy->getElementType(El));
351 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
352 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
353 if (CI->getZExtValue() >= ATy->getNumElements())
355 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
356 C = CA->getOperand(CI->getZExtValue());
357 else if (isa<ConstantAggregateZero>(C))
358 C = Constant::getNullValue(ATy->getElementType());
359 else if (isa<UndefValue>(C))
360 C = UndefValue::get(ATy->getElementType());
363 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
364 if (CI->getZExtValue() >= PTy->getNumElements())
366 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
367 C = CP->getOperand(CI->getZExtValue());
368 else if (isa<ConstantAggregateZero>(C))
369 C = Constant::getNullValue(PTy->getElementType());
370 else if (isa<UndefValue>(C))
371 C = UndefValue::get(PTy->getElementType());
384 //===----------------------------------------------------------------------===//
385 // Constant Folding for Calls
388 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
389 /// the specified function.
391 llvm::canConstantFoldCallTo(Function *F) {
392 switch (F->getIntrinsicID()) {
393 case Intrinsic::sqrt:
394 case Intrinsic::powi:
395 case Intrinsic::bswap:
396 case Intrinsic::ctpop:
397 case Intrinsic::ctlz:
398 case Intrinsic::cttz:
403 const ValueName *NameVal = F->getValueName();
404 if (NameVal == 0) return false;
405 const char *Str = NameVal->getKeyData();
406 unsigned Len = NameVal->getKeyLength();
408 // In these cases, the check of the length is required. We don't want to
409 // return true for a name like "cos\0blah" which strcmp would return equal to
410 // "cos", but has length 8.
412 default: return false;
415 return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
416 !strcmp(Str, "atan");
418 return !strcmp(Str, "atan2");
422 return !strcmp(Str, "cos");
424 return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
425 !strcmp(Str, "cosh");
429 return !strcmp(Str, "exp");
433 return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
435 return !strcmp(Str, "floor");
439 if (Len == 3 && !strcmp(Str, "log"))
441 if (Len == 5 && !strcmp(Str, "log10"))
445 if (Len == 3 && !strcmp(Str, "pow"))
450 return !strcmp(Str, "sin");
452 return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt");
454 return !strcmp(Str, "sqrtf");
457 if (Len == 3 && !strcmp(Str, "tan"))
459 else if (Len == 4 && !strcmp(Str, "tanh"))
465 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
470 if (Ty==Type::FloatTy)
471 return ConstantFP::get(Ty, APFloat((float)V));
472 else if (Ty==Type::DoubleTy)
473 return ConstantFP::get(Ty, APFloat(V));
481 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
487 if (Ty==Type::FloatTy)
488 return ConstantFP::get(Ty, APFloat((float)V));
489 else if (Ty==Type::DoubleTy)
490 return ConstantFP::get(Ty, APFloat(V));
498 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
499 /// with the specified arguments, returning null if unsuccessful.
502 llvm::ConstantFoldCall(Function *F,
503 Constant* const* Operands, unsigned NumOperands) {
504 const ValueName *NameVal = F->getValueName();
505 if (NameVal == 0) return 0;
506 const char *Str = NameVal->getKeyData();
507 unsigned Len = NameVal->getKeyLength();
509 const Type *Ty = F->getReturnType();
510 if (NumOperands == 1) {
511 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
512 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
514 /// Currently APFloat versions of these functions do not exist, so we use
515 /// the host native double versions. Float versions are not called
516 /// directly but for all these it is true (float)(f((double)arg)) ==
517 /// f(arg). Long double not supported yet.
518 double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
519 Op->getValueAPF().convertToDouble();
522 if (Len == 4 && !strcmp(Str, "acos"))
523 return ConstantFoldFP(acos, V, Ty);
524 else if (Len == 4 && !strcmp(Str, "asin"))
525 return ConstantFoldFP(asin, V, Ty);
526 else if (Len == 4 && !strcmp(Str, "atan"))
527 return ConstantFoldFP(atan, V, Ty);
530 if (Len == 4 && !strcmp(Str, "ceil"))
531 return ConstantFoldFP(ceil, V, Ty);
532 else if (Len == 3 && !strcmp(Str, "cos"))
533 return ConstantFoldFP(cos, V, Ty);
534 else if (Len == 4 && !strcmp(Str, "cosh"))
535 return ConstantFoldFP(cosh, V, Ty);
538 if (Len == 3 && !strcmp(Str, "exp"))
539 return ConstantFoldFP(exp, V, Ty);
542 if (Len == 4 && !strcmp(Str, "fabs"))
543 return ConstantFoldFP(fabs, V, Ty);
544 else if (Len == 5 && !strcmp(Str, "floor"))
545 return ConstantFoldFP(floor, V, Ty);
548 if (Len == 3 && !strcmp(Str, "log") && V > 0)
549 return ConstantFoldFP(log, V, Ty);
550 else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
551 return ConstantFoldFP(log10, V, Ty);
552 else if (!strcmp(Str, "llvm.sqrt.f32") ||
553 !strcmp(Str, "llvm.sqrt.f64")) {
555 return ConstantFoldFP(sqrt, V, Ty);
557 return ConstantFP::get(Ty, Ty==Type::FloatTy ? APFloat(0.0f) :
562 if (Len == 3 && !strcmp(Str, "sin"))
563 return ConstantFoldFP(sin, V, Ty);
564 else if (Len == 4 && !strcmp(Str, "sinh"))
565 return ConstantFoldFP(sinh, V, Ty);
566 else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
567 return ConstantFoldFP(sqrt, V, Ty);
568 else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
569 return ConstantFoldFP(sqrt, V, Ty);
572 if (Len == 3 && !strcmp(Str, "tan"))
573 return ConstantFoldFP(tan, V, Ty);
574 else if (Len == 4 && !strcmp(Str, "tanh"))
575 return ConstantFoldFP(tanh, V, Ty);
580 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
581 if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
582 return ConstantInt::get(Op->getValue().byteSwap());
583 else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
584 return ConstantInt::get(Ty, Op->getValue().countPopulation());
585 else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
586 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
587 else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
588 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
590 } else if (NumOperands == 2) {
591 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
592 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
594 double Op1V = Ty==Type::FloatTy ?
595 (double)Op1->getValueAPF().convertToFloat():
596 Op1->getValueAPF().convertToDouble();
597 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
598 double Op2V = Ty==Type::FloatTy ?
599 (double)Op2->getValueAPF().convertToFloat():
600 Op2->getValueAPF().convertToDouble();
602 if (Len == 3 && !strcmp(Str, "pow")) {
603 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
604 } else if (Len == 4 && !strcmp(Str, "fmod")) {
605 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
606 } else if (Len == 5 && !strcmp(Str, "atan2")) {
607 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
609 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
610 if (!strcmp(Str, "llvm.powi.f32")) {
611 return ConstantFP::get(Ty, APFloat((float)std::pow((float)Op1V,
612 (int)Op2C->getZExtValue())));
613 } else if (!strcmp(Str, "llvm.powi.f64")) {
614 return ConstantFP::get(Ty, APFloat((double)std::pow((double)Op1V,
615 (int)Op2C->getZExtValue())));