ConstantFolding.cpp revision 76e2e4a2bc78a0ca2617e3b336081e29cb00d749
1//===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
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"
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"
26#include <cerrno>
27#include <cmath>
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
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.
58    if (!cast<PointerType>(CE->getOperand(0)->getType())
59                 ->getElementType()->isSized())
60      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
75        Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
76      } else {
77        const SequentialType *SQT = cast<SequentialType>(*GTI);
78        Offset += TD.getABITypeSize(SQT->getElementType())*CI->getSExtValue();
79      }
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.
121static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
122                                         const Type *ResultTy,
123                                         const TargetData *TD) {
124  Constant *Ptr = Ops[0];
125  if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
126    return 0;
127
128  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;
139  }
140
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);
151}
152
153/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
154/// targetdata.  Return 0 if unfoldable.
155static Constant *FoldBitCast(Constant *C, const Type *DestTy,
156                             const TargetData &TD) {
157  // If this is a bitcast from constant vector -> vector, fold it.
158  if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
159    if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
160      // If the element types match, VMCore can fold it.
161      unsigned NumDstElt = DestVTy->getNumElements();
162      unsigned NumSrcElt = CV->getNumOperands();
163      if (NumDstElt == NumSrcElt)
164        return 0;
165
166      const Type *SrcEltTy = CV->getType()->getElementType();
167      const Type *DstEltTy = DestVTy->getElementType();
168
169      // Otherwise, we're changing the number of elements in a vector, which
170      // requires endianness information to do the right thing.  For example,
171      //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
172      // folds to (little endian):
173      //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
174      // and to (big endian):
175      //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
176
177      // First thing is first.  We only want to think about integer here, so if
178      // we have something in FP form, recast it as integer.
179      if (DstEltTy->isFloatingPoint()) {
180        // Fold to an vector of integers with same size as our FP type.
181        unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
182        const Type *DestIVTy = VectorType::get(IntegerType::get(FPWidth),
183                                               NumDstElt);
184        // Recursively handle this integer conversion, if possible.
185        C = FoldBitCast(C, DestIVTy, TD);
186        if (!C) return 0;
187
188        // Finally, VMCore can handle this now that #elts line up.
189        return ConstantExpr::getBitCast(C, DestTy);
190      }
191
192      // Okay, we know the destination is integer, if the input is FP, convert
193      // it to integer first.
194      if (SrcEltTy->isFloatingPoint()) {
195        unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
196        const Type *SrcIVTy = VectorType::get(IntegerType::get(FPWidth),
197                                              NumSrcElt);
198        // Ask VMCore to do the conversion now that #elts line up.
199        C = ConstantExpr::getBitCast(C, SrcIVTy);
200        CV = dyn_cast<ConstantVector>(C);
201        if (!CV) return 0;  // If VMCore wasn't able to fold it, bail out.
202      }
203
204      // Now we know that the input and output vectors are both integer vectors
205      // of the same size, and that their #elements is not the same.  Do the
206      // conversion here, which depends on whether the input or output has
207      // more elements.
208      bool isLittleEndian = TD.isLittleEndian();
209
210      SmallVector<Constant*, 32> Result;
211      if (NumDstElt < NumSrcElt) {
212        // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
213        Constant *Zero = Constant::getNullValue(DstEltTy);
214        unsigned Ratio = NumSrcElt/NumDstElt;
215        unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
216        unsigned SrcElt = 0;
217        for (unsigned i = 0; i != NumDstElt; ++i) {
218          // Build each element of the result.
219          Constant *Elt = Zero;
220          unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
221          for (unsigned j = 0; j != Ratio; ++j) {
222            Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
223            if (!Src) return 0;  // Reject constantexpr elements.
224
225            // Zero extend the element to the right size.
226            Src = ConstantExpr::getZExt(Src, Elt->getType());
227
228            // Shift it to the right place, depending on endianness.
229            Src = ConstantExpr::getShl(Src,
230                                    ConstantInt::get(Src->getType(), ShiftAmt));
231            ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
232
233            // Mix it in.
234            Elt = ConstantExpr::getOr(Elt, Src);
235          }
236          Result.push_back(Elt);
237        }
238      } else {
239        // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
240        unsigned Ratio = NumDstElt/NumSrcElt;
241        unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
242
243        // Loop over each source value, expanding into multiple results.
244        for (unsigned i = 0; i != NumSrcElt; ++i) {
245          Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
246          if (!Src) return 0;  // Reject constantexpr elements.
247
248          unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
249          for (unsigned j = 0; j != Ratio; ++j) {
250            // Shift the piece of the value into the right place, depending on
251            // endianness.
252            Constant *Elt = ConstantExpr::getLShr(Src,
253                                ConstantInt::get(Src->getType(), ShiftAmt));
254            ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
255
256            // Truncate and remember this piece.
257            Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
258          }
259        }
260      }
261
262      return ConstantVector::get(&Result[0], Result.size());
263    }
264  }
265
266  return 0;
267}
268
269
270//===----------------------------------------------------------------------===//
271// Constant Folding public APIs
272//===----------------------------------------------------------------------===//
273
274
275/// ConstantFoldInstruction - Attempt to constant fold the specified
276/// instruction.  If successful, the constant result is returned, if not, null
277/// is returned.  Note that this function can only fail when attempting to fold
278/// instructions like loads and stores, which have no constant expression form.
279///
280Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
281  if (PHINode *PN = dyn_cast<PHINode>(I)) {
282    if (PN->getNumIncomingValues() == 0)
283      return Constant::getNullValue(PN->getType());
284
285    Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
286    if (Result == 0) return 0;
287
288    // Handle PHI nodes specially here...
289    for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
290      if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
291        return 0;   // Not all the same incoming constants...
292
293    // If we reach here, all incoming values are the same constant.
294    return Result;
295  }
296
297  // Scan the operand list, checking to see if they are all constants, if so,
298  // hand off to ConstantFoldInstOperands.
299  SmallVector<Constant*, 8> Ops;
300  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
301    if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
302      Ops.push_back(Op);
303    else
304      return 0;  // All operands not constant!
305
306  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
307    return ConstantFoldCompareInstOperands(CI->getPredicate(),
308                                           &Ops[0], Ops.size(), TD);
309  else
310    return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
311                                    &Ops[0], Ops.size(), TD);
312}
313
314/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
315/// specified opcode and operands.  If successful, the constant result is
316/// returned, if not, null is returned.  Note that this function can fail when
317/// attempting to fold instructions like loads and stores, which have no
318/// constant expression form.
319///
320Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
321                                         Constant* const* Ops, unsigned NumOps,
322                                         const TargetData *TD) {
323  // Handle easy binops first.
324  if (Instruction::isBinaryOp(Opcode)) {
325    if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
326      if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
327        return C;
328
329    return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
330  }
331
332  switch (Opcode) {
333  default: return 0;
334  case Instruction::Call:
335    if (Function *F = dyn_cast<Function>(Ops[0]))
336      if (canConstantFoldCallTo(F))
337        return ConstantFoldCall(F, Ops+1, NumOps-1);
338    return 0;
339  case Instruction::ICmp:
340  case Instruction::FCmp:
341    assert(0 &&"This function is invalid for compares: no predicate specified");
342  case Instruction::PtrToInt:
343    // If the input is a inttoptr, eliminate the pair.  This requires knowing
344    // the width of a pointer, so it can't be done in ConstantExpr::getCast.
345    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
346      if (TD && CE->getOpcode() == Instruction::IntToPtr) {
347        Constant *Input = CE->getOperand(0);
348        unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
349        Constant *Mask =
350          ConstantInt::get(APInt::getLowBitsSet(InWidth,
351                                                TD->getPointerSizeInBits()));
352        Input = ConstantExpr::getAnd(Input, Mask);
353        // Do a zext or trunc to get to the dest size.
354        return ConstantExpr::getIntegerCast(Input, DestTy, false);
355      }
356    }
357    return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
358  case Instruction::IntToPtr:
359  case Instruction::Trunc:
360  case Instruction::ZExt:
361  case Instruction::SExt:
362  case Instruction::FPTrunc:
363  case Instruction::FPExt:
364  case Instruction::UIToFP:
365  case Instruction::SIToFP:
366  case Instruction::FPToUI:
367  case Instruction::FPToSI:
368      return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
369  case Instruction::BitCast:
370    if (TD)
371      if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD))
372        return C;
373    return ConstantExpr::getBitCast(Ops[0], DestTy);
374  case Instruction::Select:
375    return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
376  case Instruction::ExtractElement:
377    return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
378  case Instruction::InsertElement:
379    return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
380  case Instruction::ShuffleVector:
381    return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
382  case Instruction::GetElementPtr:
383    if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
384      return C;
385
386    return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
387  }
388}
389
390/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
391/// instruction (icmp/fcmp) with the specified operands.  If it fails, it
392/// returns a constant expression of the specified operands.
393///
394Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
395                                                Constant*const * Ops,
396                                                unsigned NumOps,
397                                                const TargetData *TD) {
398  // fold: icmp (inttoptr x), null         -> icmp x, 0
399  // fold: icmp (ptrtoint x), 0            -> icmp x, null
400  // fold: icmp (inttoptr x), (inttoptr y) -> icmp x, y
401  // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
402  //
403  // ConstantExpr::getCompare cannot do this, because it doesn't have TD
404  // around to know if bit truncation is happening.
405  if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
406    if (TD && Ops[1]->isNullValue()) {
407      const Type *IntPtrTy = TD->getIntPtrType();
408      if (CE0->getOpcode() == Instruction::IntToPtr) {
409        // Convert the integer value to the right size to ensure we get the
410        // proper extension or truncation.
411        Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
412                                                   IntPtrTy, false);
413        Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
414        return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
415      }
416
417      // Only do this transformation if the int is intptrty in size, otherwise
418      // there is a truncation or extension that we aren't modeling.
419      if (CE0->getOpcode() == Instruction::PtrToInt &&
420          CE0->getType() == IntPtrTy) {
421        Constant *C = CE0->getOperand(0);
422        Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
423        // FIXME!
424        return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
425      }
426    }
427
428    if (TD && isa<ConstantExpr>(Ops[1]) &&
429        cast<ConstantExpr>(Ops[1])->getOpcode() == CE0->getOpcode()) {
430      const Type *IntPtrTy = TD->getIntPtrType();
431      // Only do this transformation if the int is intptrty in size, otherwise
432      // there is a truncation or extension that we aren't modeling.
433      if ((CE0->getOpcode() == Instruction::IntToPtr &&
434           CE0->getOperand(0)->getType() == IntPtrTy &&
435           Ops[1]->getOperand(0)->getType() == IntPtrTy) ||
436          (CE0->getOpcode() == Instruction::PtrToInt &&
437           CE0->getType() == IntPtrTy &&
438           CE0->getOperand(0)->getType() == Ops[1]->getOperand(0)->getType())) {
439        Constant *NewOps[] = {
440          CE0->getOperand(0), cast<ConstantExpr>(Ops[1])->getOperand(0)
441        };
442        return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
443      }
444    }
445  }
446  return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
447}
448
449
450/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
451/// getelementptr constantexpr, return the constant value being addressed by the
452/// constant expression, or null if something is funny and we can't decide.
453Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
454                                                       ConstantExpr *CE) {
455  if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
456    return 0;  // Do not allow stepping over the value!
457
458  // Loop over all of the operands, tracking down which value we are
459  // addressing...
460  gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
461  for (++I; I != E; ++I)
462    if (const StructType *STy = dyn_cast<StructType>(*I)) {
463      ConstantInt *CU = cast<ConstantInt>(I.getOperand());
464      assert(CU->getZExtValue() < STy->getNumElements() &&
465             "Struct index out of range!");
466      unsigned El = (unsigned)CU->getZExtValue();
467      if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
468        C = CS->getOperand(El);
469      } else if (isa<ConstantAggregateZero>(C)) {
470        C = Constant::getNullValue(STy->getElementType(El));
471      } else if (isa<UndefValue>(C)) {
472        C = UndefValue::get(STy->getElementType(El));
473      } else {
474        return 0;
475      }
476    } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
477      if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
478        if (CI->getZExtValue() >= ATy->getNumElements())
479         return 0;
480        if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
481          C = CA->getOperand(CI->getZExtValue());
482        else if (isa<ConstantAggregateZero>(C))
483          C = Constant::getNullValue(ATy->getElementType());
484        else if (isa<UndefValue>(C))
485          C = UndefValue::get(ATy->getElementType());
486        else
487          return 0;
488      } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
489        if (CI->getZExtValue() >= PTy->getNumElements())
490          return 0;
491        if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
492          C = CP->getOperand(CI->getZExtValue());
493        else if (isa<ConstantAggregateZero>(C))
494          C = Constant::getNullValue(PTy->getElementType());
495        else if (isa<UndefValue>(C))
496          C = UndefValue::get(PTy->getElementType());
497        else
498          return 0;
499      } else {
500        return 0;
501      }
502    } else {
503      return 0;
504    }
505  return C;
506}
507
508
509//===----------------------------------------------------------------------===//
510//  Constant Folding for Calls
511//
512
513/// canConstantFoldCallTo - Return true if its even possible to fold a call to
514/// the specified function.
515bool
516llvm::canConstantFoldCallTo(const Function *F) {
517  switch (F->getIntrinsicID()) {
518  case Intrinsic::sqrt:
519  case Intrinsic::powi:
520  case Intrinsic::bswap:
521  case Intrinsic::ctpop:
522  case Intrinsic::ctlz:
523  case Intrinsic::cttz:
524    return true;
525  default: break;
526  }
527
528  const ValueName *NameVal = F->getValueName();
529  if (NameVal == 0) return false;
530  const char *Str = NameVal->getKeyData();
531  unsigned Len = NameVal->getKeyLength();
532
533  // In these cases, the check of the length is required.  We don't want to
534  // return true for a name like "cos\0blah" which strcmp would return equal to
535  // "cos", but has length 8.
536  switch (Str[0]) {
537  default: return false;
538  case 'a':
539    if (Len == 4)
540      return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
541             !strcmp(Str, "atan");
542    else if (Len == 5)
543      return !strcmp(Str, "atan2");
544    return false;
545  case 'c':
546    if (Len == 3)
547      return !strcmp(Str, "cos");
548    else if (Len == 4)
549      return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
550             !strcmp(Str, "cosh");
551    return false;
552  case 'e':
553    if (Len == 3)
554      return !strcmp(Str, "exp");
555    return false;
556  case 'f':
557    if (Len == 4)
558      return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
559    else if (Len == 5)
560      return !strcmp(Str, "floor");
561    return false;
562    break;
563  case 'l':
564    if (Len == 3 && !strcmp(Str, "log"))
565      return true;
566    if (Len == 5 && !strcmp(Str, "log10"))
567      return true;
568    return false;
569  case 'p':
570    if (Len == 3 && !strcmp(Str, "pow"))
571      return true;
572    return false;
573  case 's':
574    if (Len == 3)
575      return !strcmp(Str, "sin");
576    if (Len == 4)
577      return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
578             !strcmp(Str, "sinf");
579    if (Len == 5)
580      return !strcmp(Str, "sqrtf");
581    return false;
582  case 't':
583    if (Len == 3 && !strcmp(Str, "tan"))
584      return true;
585    else if (Len == 4 && !strcmp(Str, "tanh"))
586      return true;
587    return false;
588  }
589}
590
591static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
592                                const Type *Ty) {
593  errno = 0;
594  V = NativeFP(V);
595  if (errno != 0) {
596    errno = 0;
597    return 0;
598  }
599
600  if (Ty == Type::FloatTy)
601    return ConstantFP::get(APFloat((float)V));
602  if (Ty == Type::DoubleTy)
603    return ConstantFP::get(APFloat(V));
604  assert(0 && "Can only constant fold float/double");
605}
606
607static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
608                                      double V, double W,
609                                      const Type *Ty) {
610  errno = 0;
611  V = NativeFP(V, W);
612  if (errno != 0) {
613    errno = 0;
614    return 0;
615  }
616
617  if (Ty == Type::FloatTy)
618    return ConstantFP::get(APFloat((float)V));
619  if (Ty == Type::DoubleTy)
620    return ConstantFP::get(APFloat(V));
621  assert(0 && "Can only constant fold float/double");
622}
623
624/// ConstantFoldCall - Attempt to constant fold a call to the specified function
625/// with the specified arguments, returning null if unsuccessful.
626
627Constant *
628llvm::ConstantFoldCall(Function *F,
629                       Constant* const* Operands, unsigned NumOperands) {
630  const ValueName *NameVal = F->getValueName();
631  if (NameVal == 0) return 0;
632  const char *Str = NameVal->getKeyData();
633  unsigned Len = NameVal->getKeyLength();
634
635  const Type *Ty = F->getReturnType();
636  if (NumOperands == 1) {
637    if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
638      if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
639        return 0;
640      /// Currently APFloat versions of these functions do not exist, so we use
641      /// the host native double versions.  Float versions are not called
642      /// directly but for all these it is true (float)(f((double)arg)) ==
643      /// f(arg).  Long double not supported yet.
644      double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
645                                     Op->getValueAPF().convertToDouble();
646      switch (Str[0]) {
647      case 'a':
648        if (Len == 4 && !strcmp(Str, "acos"))
649          return ConstantFoldFP(acos, V, Ty);
650        else if (Len == 4 && !strcmp(Str, "asin"))
651          return ConstantFoldFP(asin, V, Ty);
652        else if (Len == 4 && !strcmp(Str, "atan"))
653          return ConstantFoldFP(atan, V, Ty);
654        break;
655      case 'c':
656        if (Len == 4 && !strcmp(Str, "ceil"))
657          return ConstantFoldFP(ceil, V, Ty);
658        else if (Len == 3 && !strcmp(Str, "cos"))
659          return ConstantFoldFP(cos, V, Ty);
660        else if (Len == 4 && !strcmp(Str, "cosh"))
661          return ConstantFoldFP(cosh, V, Ty);
662        else if (Len == 4 && !strcmp(Str, "cosf"))
663          return ConstantFoldFP(cos, V, Ty);
664        break;
665      case 'e':
666        if (Len == 3 && !strcmp(Str, "exp"))
667          return ConstantFoldFP(exp, V, Ty);
668        break;
669      case 'f':
670        if (Len == 4 && !strcmp(Str, "fabs"))
671          return ConstantFoldFP(fabs, V, Ty);
672        else if (Len == 5 && !strcmp(Str, "floor"))
673          return ConstantFoldFP(floor, V, Ty);
674        break;
675      case 'l':
676        if (Len == 3 && !strcmp(Str, "log") && V > 0)
677          return ConstantFoldFP(log, V, Ty);
678        else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
679          return ConstantFoldFP(log10, V, Ty);
680        else if (!strcmp(Str, "llvm.sqrt.f32") ||
681                 !strcmp(Str, "llvm.sqrt.f64")) {
682          if (V >= -0.0)
683            return ConstantFoldFP(sqrt, V, Ty);
684          else // Undefined
685            return Constant::getNullValue(Ty);
686        }
687        break;
688      case 's':
689        if (Len == 3 && !strcmp(Str, "sin"))
690          return ConstantFoldFP(sin, V, Ty);
691        else if (Len == 4 && !strcmp(Str, "sinh"))
692          return ConstantFoldFP(sinh, V, Ty);
693        else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
694          return ConstantFoldFP(sqrt, V, Ty);
695        else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
696          return ConstantFoldFP(sqrt, V, Ty);
697        else if (Len == 4 && !strcmp(Str, "sinf"))
698          return ConstantFoldFP(sin, V, Ty);
699        break;
700      case 't':
701        if (Len == 3 && !strcmp(Str, "tan"))
702          return ConstantFoldFP(tan, V, Ty);
703        else if (Len == 4 && !strcmp(Str, "tanh"))
704          return ConstantFoldFP(tanh, V, Ty);
705        break;
706      default:
707        break;
708      }
709    } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
710      if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
711        return ConstantInt::get(Op->getValue().byteSwap());
712      else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
713        return ConstantInt::get(Ty, Op->getValue().countPopulation());
714      else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
715        return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
716      else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
717        return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
718    }
719  } else if (NumOperands == 2) {
720    if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
721      if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
722        return 0;
723      double Op1V = Ty==Type::FloatTy ?
724                      (double)Op1->getValueAPF().convertToFloat():
725                      Op1->getValueAPF().convertToDouble();
726      if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
727        double Op2V = Ty==Type::FloatTy ?
728                      (double)Op2->getValueAPF().convertToFloat():
729                      Op2->getValueAPF().convertToDouble();
730
731        if (Len == 3 && !strcmp(Str, "pow")) {
732          return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
733        } else if (Len == 4 && !strcmp(Str, "fmod")) {
734          return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
735        } else if (Len == 5 && !strcmp(Str, "atan2")) {
736          return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
737        }
738      } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
739        if (!strcmp(Str, "llvm.powi.f32")) {
740          return ConstantFP::get(APFloat((float)std::pow((float)Op1V,
741                                                 (int)Op2C->getZExtValue())));
742        } else if (!strcmp(Str, "llvm.powi.f64")) {
743          return ConstantFP::get(APFloat((double)std::pow((double)Op1V,
744                                                 (int)Op2C->getZExtValue())));
745        }
746      }
747    }
748  }
749  return 0;
750}
751
752