ConstantFolding.cpp revision fc6d3a49867cd38954dc40936a88f1907252c6d2
183e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//
3bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//                     The LLVM Compiler Infrastructure
4bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//
54ee451de366474b9c228b4e5fa573795a715216dChris Lattner// This file is distributed under the University of Illinois Open Source
64ee451de366474b9c228b4e5fa573795a715216dChris Lattner// License. See LICENSE.TXT for details.
7bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//
8bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//===----------------------------------------------------------------------===//
9bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//
1083e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman// This file defines routines for folding instructions into constants.
1183e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman//
1283e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman// Also, to supplement the basic VMCore ConstantExpr simplifications,
1383e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman// this file defines some additional folding routines that can make use of
1483e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman// TargetData information. These functions cannot go in VMCore due to library
1583e3c4f9d796a5da223a3ebd5d4ba985c7ecc39dDan Gohman// dependency issues.
16bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//
17bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//===----------------------------------------------------------------------===//
18bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
19bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/Analysis/ConstantFolding.h"
20bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/Constants.h"
21bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/DerivedTypes.h"
225520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner#include "llvm/Function.h"
239a38e3e3991ea443e555d8060f91202a786acdd4Dan Gohman#include "llvm/GlobalVariable.h"
24bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/Instructions.h"
25bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/Intrinsics.h"
26562b84b3aea359d1f918184e355da82bf05eb290Jay Foad#include "llvm/Operator.h"
2762d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner#include "llvm/Analysis/ValueTracking.h"
2862d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner#include "llvm/Target/TargetData.h"
295520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner#include "llvm/ADT/SmallVector.h"
30c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner#include "llvm/ADT/StringMap.h"
31c25e7581b9b8088910da31702d4ca21c4734c6d7Torok Edwin#include "llvm/Support/ErrorHandling.h"
32bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/Support/GetElementPtrTypeIterator.h"
33bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include "llvm/Support/MathExtras.h"
3483471853b1d5a9efe6b9e7565c457fc901f84926Rafael Espindola#include "llvm/Support/FEnv.h"
35bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell#include <cerrno>
3697af751deb9b26fd42fbcee082da9ccc4ded5b45Jeff Cohen#include <cmath>
37bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswellusing namespace llvm;
38bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
3903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner//===----------------------------------------------------------------------===//
4003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner// Constant Folding internal helper functions
4103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner//===----------------------------------------------------------------------===//
4203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
436333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
446333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner/// TargetData.  This always returns a non-null constant, but it may be a
456333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner/// ConstantExpr if unfoldable.
466333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattnerstatic Constant *FoldBitCast(Constant *C, const Type *DestTy,
476333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner                             const TargetData &TD) {
486333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
4993798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  // This only handles casts to vectors currently.
506333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  const VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
516333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  if (DestVTy == 0)
526333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    return ConstantExpr::getBitCast(C, DestTy);
536333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
5493798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
5593798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  // vector so the code below can handle it uniformly.
5693798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
5793798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner    Constant *Ops = C; // don't take the address of C!
582ca5c8644e6c35b3a7910a576ed89cddb7b82c3bChris Lattner    return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
5993798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  }
6093798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner
6193798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  // If this is a bitcast from constant vector -> vector, fold it.
6293798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  ConstantVector *CV = dyn_cast<ConstantVector>(C);
6393798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner  if (CV == 0)
6493798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner    return ConstantExpr::getBitCast(C, DestTy);
6593798daa3ecbfb29624052d3e54d2404ab65897aChris Lattner
666333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // If the element types match, VMCore can fold it.
676333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  unsigned NumDstElt = DestVTy->getNumElements();
686333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  unsigned NumSrcElt = CV->getNumOperands();
696333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  if (NumDstElt == NumSrcElt)
706333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    return ConstantExpr::getBitCast(C, DestTy);
716333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
726333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  const Type *SrcEltTy = CV->getType()->getElementType();
736333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  const Type *DstEltTy = DestVTy->getElementType();
746333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
756333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // Otherwise, we're changing the number of elements in a vector, which
766333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // requires endianness information to do the right thing.  For example,
776333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
786333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // folds to (little endian):
796333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
806333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // and to (big endian):
816333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
826333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
836333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // First thing is first.  We only want to think about integer here, so if
846333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // we have something in FP form, recast it as integer.
85b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  if (DstEltTy->isFloatingPointTy()) {
866333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Fold to an vector of integers with same size as our FP type.
876333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
886333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    const Type *DestIVTy =
896333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
906333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Recursively handle this integer conversion, if possible.
916333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    C = FoldBitCast(C, DestIVTy, TD);
926333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    if (!C) return ConstantExpr::getBitCast(C, DestTy);
936333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
946333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Finally, VMCore can handle this now that #elts line up.
956333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    return ConstantExpr::getBitCast(C, DestTy);
966333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  }
976333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
986333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // Okay, we know the destination is integer, if the input is FP, convert
996333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // it to integer first.
100b0bc6c361da9009e8414efde317d9bbff755f6c0Duncan Sands  if (SrcEltTy->isFloatingPointTy()) {
1016333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
1026333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    const Type *SrcIVTy =
1036333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
1046333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Ask VMCore to do the conversion now that #elts line up.
1056333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    C = ConstantExpr::getBitCast(C, SrcIVTy);
1066333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    CV = dyn_cast<ConstantVector>(C);
1076333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    if (!CV)  // If VMCore wasn't able to fold it, bail out.
1086333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      return C;
1096333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  }
1106333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1116333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // Now we know that the input and output vectors are both integer vectors
1126333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // of the same size, and that their #elements is not the same.  Do the
1136333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // conversion here, which depends on whether the input or output has
1146333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  // more elements.
1156333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  bool isLittleEndian = TD.isLittleEndian();
1166333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1176333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  SmallVector<Constant*, 32> Result;
1186333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  if (NumDstElt < NumSrcElt) {
1196333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
1206333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    Constant *Zero = Constant::getNullValue(DstEltTy);
1216333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned Ratio = NumSrcElt/NumDstElt;
1226333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
1236333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned SrcElt = 0;
1246333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    for (unsigned i = 0; i != NumDstElt; ++i) {
1256333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      // Build each element of the result.
1266333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      Constant *Elt = Zero;
1276333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
1286333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      for (unsigned j = 0; j != Ratio; ++j) {
1296333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
1306333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        if (!Src)  // Reject constantexpr elements.
1316333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner          return ConstantExpr::getBitCast(C, DestTy);
1326333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1336333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        // Zero extend the element to the right size.
1346333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        Src = ConstantExpr::getZExt(Src, Elt->getType());
1356333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1366333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        // Shift it to the right place, depending on endianness.
1376333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        Src = ConstantExpr::getShl(Src,
1386333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner                                   ConstantInt::get(Src->getType(), ShiftAmt));
1396333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
1406333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1416333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        // Mix it in.
1426333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        Elt = ConstantExpr::getOr(Elt, Src);
1436333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      }
1446333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      Result.push_back(Elt);
1456333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    }
1466333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  } else {
1476333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
1486333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned Ratio = NumDstElt/NumSrcElt;
1496333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
1506333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1516333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    // Loop over each source value, expanding into multiple results.
1526333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    for (unsigned i = 0; i != NumSrcElt; ++i) {
1536333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
1546333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      if (!Src)  // Reject constantexpr elements.
1556333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        return ConstantExpr::getBitCast(C, DestTy);
1566333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1576333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
1586333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      for (unsigned j = 0; j != Ratio; ++j) {
1596333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        // Shift the piece of the value into the right place, depending on
1606333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        // endianness.
1616333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        Constant *Elt = ConstantExpr::getLShr(Src,
1626333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner                                    ConstantInt::get(Src->getType(), ShiftAmt));
1636333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
1646333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1656333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        // Truncate and remember this piece.
1666333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner        Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
1676333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      }
1686333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    }
1696333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner  }
1706333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1712ca5c8644e6c35b3a7910a576ed89cddb7b82c3bChris Lattner  return ConstantVector::get(Result);
1726333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner}
1736333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
1746333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner
17503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
17603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// from a global, return the global and the constant.  Because of
17703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// constantexprs, this function is recursive.
17803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattnerstatic bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
17903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner                                       int64_t &Offset, const TargetData &TD) {
18003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // Trivial case, constant is the global.
18103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  if ((GV = dyn_cast<GlobalValue>(C))) {
18203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    Offset = 0;
18303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    return true;
18403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  }
18503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
18603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // Otherwise, if this isn't a constant expr, bail out.
18703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
18803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  if (!CE) return false;
18903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
19003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // Look through ptr->int and ptr->ptr casts.
19103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  if (CE->getOpcode() == Instruction::PtrToInt ||
19203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      CE->getOpcode() == Instruction::BitCast)
19303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
19403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
19503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
19603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  if (CE->getOpcode() == Instruction::GetElementPtr) {
19703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    // Cannot compute this if the element type of the pointer is missing size
19803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    // info.
199f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner    if (!cast<PointerType>(CE->getOperand(0)->getType())
200f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner                 ->getElementType()->isSized())
20103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      return false;
20203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
20303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    // If the base isn't a global+constant, we aren't either.
20403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
20503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      return false;
20603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
20703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    // Otherwise, add any offset that our operands provide.
20803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    gep_type_iterator GTI = gep_type_begin(CE);
209de2d74b213844b17eb5327fba27f21e699d3af66Gabor Greif    for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
210785c6af9797fcf551feef70f2ecb5cd075b6e3c4Gabor Greif         i != e; ++i, ++GTI) {
211de2d74b213844b17eb5327fba27f21e699d3af66Gabor Greif      ConstantInt *CI = dyn_cast<ConstantInt>(*i);
21203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      if (!CI) return false;  // Index isn't a simple constant?
213e368b460a206fafa0d31d5d059b1779b94f7df8cDan Gohman      if (CI->isZero()) continue;  // Not adding anything.
21403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
21503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
21603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner        // N = N + Offset
217b1919e2f08ecb37140af676fd2916f8d5ed7df3dChris Lattner        Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
21803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      } else {
219ca5183d445954a9b2a570d6bbba1bc2b00ad6442Jeff Cohen        const SequentialType *SQT = cast<SequentialType>(*GTI);
220777d2306b36816a53bc1ae1244c0dc7d998ae691Duncan Sands        Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
22103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      }
22203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    }
22303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    return true;
22403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  }
22503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
22603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  return false;
22703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner}
22803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
229fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner/// ReadDataFromGlobal - Recursive helper to read bits out of global.  C is the
230fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner/// constant being copied out of. ByteOffset is an offset into C.  CurPtr is the
231fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner/// pointer to copy results into and BytesLeft is the number of bytes left in
232fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner/// the CurPtr buffer.  TD is the target data.
233fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattnerstatic bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
234fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                               unsigned char *CurPtr, unsigned BytesLeft,
235fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                               const TargetData &TD) {
236fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
237fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner         "Out of range access");
238fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
239c7b1382e351249774be63bd73839e8a0671635e1Chris Lattner  // If this element is zero or undefined, we can just return since *CurPtr is
240c7b1382e351249774be63bd73839e8a0671635e1Chris Lattner  // zero initialized.
241fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
242fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return true;
243fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
244fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
245fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    if (CI->getBitWidth() > 64 ||
246fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        (CI->getBitWidth() & 7) != 0)
247fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      return false;
248fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
249fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t Val = CI->getZExtValue();
250fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    unsigned IntBytes = unsigned(CI->getBitWidth()/8);
251fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
252fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
253c7b1382e351249774be63bd73839e8a0671635e1Chris Lattner      CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
254fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      ++ByteOffset;
255fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    }
256fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return true;
257fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  }
258fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
259fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
260fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    if (CFP->getType()->isDoubleTy()) {
2616333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
262fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
263fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    }
264fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    if (CFP->getType()->isFloatTy()){
2656333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
266fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
267fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    }
268c7b1382e351249774be63bd73839e8a0671635e1Chris Lattner    return false;
269fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  }
270fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
271fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
272fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    const StructLayout *SL = TD.getStructLayout(CS->getType());
273fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    unsigned Index = SL->getElementContainingOffset(ByteOffset);
274fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t CurEltOffset = SL->getElementOffset(Index);
275fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    ByteOffset -= CurEltOffset;
276fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
277fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    while (1) {
278fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      // If the element access is to the element itself and not to tail padding,
279fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      // read the bytes from the element.
280fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
281fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
282fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (ByteOffset < EltSize &&
283fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner          !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
284fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                              BytesLeft, TD))
285fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return false;
286fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
287fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      ++Index;
288fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
289fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      // Check to see if we read from the last struct element, if so we're done.
290fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (Index == CS->getType()->getNumElements())
291fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return true;
292fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
293fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      // If we read all of the bytes we needed from this element we're done.
294fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      uint64_t NextEltOffset = SL->getElementOffset(Index);
295fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
296fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
297fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return true;
298fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
299fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      // Move to the next element of the struct.
300c5af649758ac8c6ffb896d7d5c570640a9fa1deeChris Lattner      CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
301fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
302fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      ByteOffset = 0;
303fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      CurEltOffset = NextEltOffset;
304fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    }
305fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    // not reached.
306fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  }
307fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
308fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
309fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t EltSize = TD.getTypeAllocSize(CA->getType()->getElementType());
310fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t Index = ByteOffset / EltSize;
311fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t Offset = ByteOffset - Index * EltSize;
312fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    for (; Index != CA->getType()->getNumElements(); ++Index) {
313fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
314fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                              BytesLeft, TD))
315fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return false;
316fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (EltSize >= BytesLeft)
317fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return true;
318fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
319fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      Offset = 0;
320fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      BytesLeft -= EltSize;
321fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      CurPtr += EltSize;
322fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    }
323fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return true;
324fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  }
325fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
326fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
327fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t EltSize = TD.getTypeAllocSize(CV->getType()->getElementType());
328fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t Index = ByteOffset / EltSize;
329fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    uint64_t Offset = ByteOffset - Index * EltSize;
330fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    for (; Index != CV->getType()->getNumElements(); ++Index) {
331fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
332fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                              BytesLeft, TD))
333fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return false;
334fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      if (EltSize >= BytesLeft)
335fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        return true;
336fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
337fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      Offset = 0;
338fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      BytesLeft -= EltSize;
339fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      CurPtr += EltSize;
340fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    }
341fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return true;
342fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  }
343fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
3446475d9434ff3e981160f85d3f1aa07c9e0ace6f2Anders Carlsson  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
3455d43ff4e7ea30eaf5a1c417f0ec528900f5c83f2Anders Carlsson    if (CE->getOpcode() == Instruction::IntToPtr &&
3465d43ff4e7ea30eaf5a1c417f0ec528900f5c83f2Anders Carlsson        CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext()))
3476475d9434ff3e981160f85d3f1aa07c9e0ace6f2Anders Carlsson        return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
3486475d9434ff3e981160f85d3f1aa07c9e0ace6f2Anders Carlsson                                  BytesLeft, TD);
3496475d9434ff3e981160f85d3f1aa07c9e0ace6f2Anders Carlsson  }
3506475d9434ff3e981160f85d3f1aa07c9e0ace6f2Anders Carlsson
351fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // Otherwise, unknown initializer type.
352fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  return false;
353fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner}
354fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
355fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattnerstatic Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
356fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                                                 const TargetData &TD) {
35717f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner  const Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
35817f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner  const IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
359fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
360fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // If this isn't an integer load we can't fold it directly.
361fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (!IntType) {
362fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    // If this is a float/double load, we can try folding it as an int32/64 load
36317f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner    // and then bitcast the result.  This can be useful for union cases.  Note
36417f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner    // that address spaces don't matter here since we're not going to result in
36517f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner    // an actual new load.
366fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    const Type *MapTy;
36717f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner    if (LoadTy->isFloatTy())
368fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      MapTy = Type::getInt32PtrTy(C->getContext());
36917f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner    else if (LoadTy->isDoubleTy())
370fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      MapTy = Type::getInt64PtrTy(C->getContext());
3711df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands    else if (LoadTy->isVectorTy()) {
37217f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner      MapTy = IntegerType::get(C->getContext(),
37317f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner                               TD.getTypeAllocSizeInBits(LoadTy));
37417f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner      MapTy = PointerType::getUnqual(MapTy);
37517f0cd3cc1432231f2bc5601e7e463986a59d817Chris Lattner    } else
376fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      return 0;
377fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
3786333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    C = FoldBitCast(C, MapTy, TD);
379fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
3806333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      return FoldBitCast(Res, LoadTy, TD);
381fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return 0;
382fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  }
383fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
384fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
385739208a790398cf1f9da05149c768371e48781e8Chris Lattner  if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
386fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
387fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  GlobalValue *GVal;
388fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  int64_t Offset;
389fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
390fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return 0;
391fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
392fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
393c7b1382e351249774be63bd73839e8a0671635e1Chris Lattner  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
394fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      !GV->getInitializer()->getType()->isSized())
395fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return 0;
396fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
397fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // If we're loading off the beginning of the global, some bytes may be valid,
398fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // but we don't try to handle this.
399fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (Offset < 0) return 0;
400fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
401fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // If we're not accessing anything in this constant, the result is undefined.
402fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
403fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return UndefValue::get(IntType);
404fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
405739208a790398cf1f9da05149c768371e48781e8Chris Lattner  unsigned char RawBytes[32] = {0};
406fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
407fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner                          BytesLoaded, TD))
408fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return 0;
409fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
410b31189f26297fe30214da3e8d14a4575d5fdd262Chris Lattner  APInt ResultVal = APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1]);
411b31189f26297fe30214da3e8d14a4575d5fdd262Chris Lattner  for (unsigned i = 1; i != BytesLoaded; ++i) {
412739208a790398cf1f9da05149c768371e48781e8Chris Lattner    ResultVal <<= 8;
413ce800511701135ed86845b451693a248c83a7973Dan Gohman    ResultVal |= RawBytes[BytesLoaded-1-i];
414739208a790398cf1f9da05149c768371e48781e8Chris Lattner  }
415fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
416739208a790398cf1f9da05149c768371e48781e8Chris Lattner  return ConstantInt::get(IntType->getContext(), ResultVal);
417fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner}
418fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
419878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
420878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner/// produce if it is constant and determinable.  If this is not determinable,
421878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner/// return null.
422878e4946700824954d7eb7f3ff660353db8e0d17Chris LattnerConstant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
423878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner                                             const TargetData *TD) {
424878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  // First, try the easy cases:
425878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
426878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner    if (GV->isConstant() && GV->hasDefinitiveInitializer())
427878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner      return GV->getInitializer();
428878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner
429e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  // If the loaded value isn't a constant expr, we can't handle it.
430e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
431e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  if (!CE) return 0;
432e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner
433e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  if (CE->getOpcode() == Instruction::GetElementPtr) {
434e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
435e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner      if (GV->isConstant() && GV->hasDefinitiveInitializer())
436e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        if (Constant *V =
437e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner             ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
438e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner          return V;
439e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  }
440e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner
441e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  // Instead of loading constant c string, use corresponding integer value
442e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  // directly if string length is small enough.
443e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  std::string Str;
44444a7a380aa9fbb303f57f4f8269062b7b56be980Chris Lattner  if (TD && GetConstantStringInfo(CE, Str) && !Str.empty()) {
445fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    unsigned StrLen = Str.length();
446e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner    const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
447fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    unsigned NumBits = Ty->getPrimitiveSizeInBits();
448eae2895120500d06bf6de9725efeeff498f60385Chris Lattner    // Replace load with immediate integer if the result is an integer or fp
449eae2895120500d06bf6de9725efeeff498f60385Chris Lattner    // value.
450eae2895120500d06bf6de9725efeeff498f60385Chris Lattner    if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
451490b8f5d64823d998fc12ad3a91ecacd82c1901eChandler Carruth        (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
452fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      APInt StrVal(NumBits, 0);
453fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner      APInt SingleChar(NumBits, 0);
454e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner      if (TD->isLittleEndian()) {
455fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        for (signed i = StrLen-1; i >= 0; i--) {
456e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner          SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
45762d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner          StrVal = (StrVal << 8) | SingleChar;
45862d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner        }
459e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner      } else {
460fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner        for (unsigned i = 0; i < StrLen; i++) {
461e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner          SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
462e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner          StrVal = (StrVal << 8) | SingleChar;
463e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        }
464e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        // Append NULL at the end.
465e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        SingleChar = 0;
466e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        StrVal = (StrVal << 8) | SingleChar;
46762d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner      }
468eae2895120500d06bf6de9725efeeff498f60385Chris Lattner
469eae2895120500d06bf6de9725efeeff498f60385Chris Lattner      Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
470eae2895120500d06bf6de9725efeeff498f60385Chris Lattner      if (Ty->isFloatingPointTy())
471eae2895120500d06bf6de9725efeeff498f60385Chris Lattner        Res = ConstantExpr::getBitCast(Res, Ty);
472eae2895120500d06bf6de9725efeeff498f60385Chris Lattner      return Res;
47362d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner    }
474878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  }
475e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner
476e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  // If this load comes from anywhere in a constant global, and if the global
477e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  // is all undef or zero, we know what it loads.
478bd1801b5553c8be3960255a92738464e0010b6f6Dan Gohman  if (GlobalVariable *GV =
479bd1801b5553c8be3960255a92738464e0010b6f6Dan Gohman        dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
480e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner    if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
481e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner      const Type *ResTy = cast<PointerType>(C->getType())->getElementType();
482e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner      if (GV->getInitializer()->isNullValue())
483e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        return Constant::getNullValue(ResTy);
484e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner      if (isa<UndefValue>(GV->getInitializer()))
485e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner        return UndefValue::get(ResTy);
486e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner    }
487e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner  }
488e00c43fc35d64b2ee8d2b4692c02375d2d7b4aa4Chris Lattner
489fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // Try hard to fold loads from bitcasted strange and non-type-safe things.  We
490fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // currently don't do any of this for big endian systems.  It can be
491fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  // generalized in the future if someone is interested.
492fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner  if (TD && TD->isLittleEndian())
493fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner    return FoldReinterpretLoadFromConstPtr(CE, *TD);
494878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  return 0;
495878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner}
496878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner
497878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattnerstatic Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
498878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  if (LI->isVolatile()) return 0;
499878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner
500878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
501878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner    return ConstantFoldLoadFromConstPtr(C, TD);
502fe8c7c807c6f815561bc2bdddfd330b05dbdfc93Chris Lattner
503878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  return 0;
504878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner}
50503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
50603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
50767e3566d8f6875e9c92d224f493023408a66227eNick Lewycky/// Attempt to symbolically evaluate the result of a binary operator merging
50803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// these together.  If target data info is available, it is provided as TD,
50903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// otherwise TD is null.
51003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattnerstatic Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
5117b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                           Constant *Op1, const TargetData *TD){
51203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // SROA
51303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
51403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
51503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
51603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // bits.
51703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
51803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
51903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // If the constant expr is something like &A[123] - &A[4].f, fold this into a
52003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // constant.  This happens frequently when iterating over a global array.
52103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  if (Opc == Instruction::Sub && TD) {
52203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    GlobalValue *GV1, *GV2;
52303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    int64_t Offs1, Offs2;
52403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
52503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
52603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
52703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner          GV1 == GV2) {
52803dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner        // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
529eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson        return ConstantInt::get(Op0->getType(), Offs1-Offs2);
53003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      }
53103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  }
53203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
53303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  return 0;
53403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner}
53503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
5364f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman/// CastGEPIndices - If array indices are not pointer-sized integers,
5374f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman/// explicitly cast them so that they aren't implicitly casted by the
5384f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman/// getelementptr.
5394f8eea82d8967cffa85b9df6c9255717b059009eDan Gohmanstatic Constant *CastGEPIndices(Constant *const *Ops, unsigned NumOps,
5404f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                const Type *ResultTy,
5414f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                const TargetData *TD) {
5424f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  if (!TD) return 0;
5434f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  const Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
5444f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman
5454f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  bool Any = false;
5464f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  SmallVector<Constant*, 32> NewIdxs;
5474f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  for (unsigned i = 1; i != NumOps; ++i) {
5484f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman    if ((i == 1 ||
5494f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman         !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
550c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner                                        reinterpret_cast<Value *const *>(Ops+1),
5514f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                                            i-1))) &&
5524f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman        Ops[i]->getType() != IntPtrTy) {
5534f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      Any = true;
5544f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
5554f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                                                      true,
5564f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                                                      IntPtrTy,
5574f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                                                      true),
5584f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman                                              Ops[i], IntPtrTy));
5594f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman    } else
5604f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      NewIdxs.push_back(Ops[i]);
5614f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  }
5624f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  if (!Any) return 0;
5634f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman
5644f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  Constant *C =
5654f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman    ConstantExpr::getGetElementPtr(Ops[0], &NewIdxs[0], NewIdxs.size());
5664f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
5674f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman    if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
5684f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      C = Folded;
5694f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman  return C;
5704f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman}
5714f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman
57203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
57303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner/// constant expression, do so.
5747b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattnerstatic Constant *SymbolicallyEvaluateGEP(Constant *const *Ops, unsigned NumOps,
57503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner                                         const Type *ResultTy,
57603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner                                         const TargetData *TD) {
57703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  Constant *Ptr = Ops[0];
578268e7d7a9446bb89b80472cdb7b9803f16c0191eChris Lattner  if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
57903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    return 0;
580f1cadf28991b2643128bfe38990ff235f2cb1491Chris Lattner
581f1cadf28991b2643128bfe38990ff235f2cb1491Chris Lattner  const Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
582268e7d7a9446bb89b80472cdb7b9803f16c0191eChris Lattner
583268e7d7a9446bb89b80472cdb7b9803f16c0191eChris Lattner  // If this is a constant expr gep that is effectively computing an
584268e7d7a9446bb89b80472cdb7b9803f16c0191eChris Lattner  // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
585268e7d7a9446bb89b80472cdb7b9803f16c0191eChris Lattner  for (unsigned i = 1; i != NumOps; ++i)
5868cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner    if (!isa<ConstantInt>(Ops[i])) {
5878cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner
5888cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner      // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
5898cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner      // "inttoptr (sub (ptrtoint Ptr), V)"
5908cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner      if (NumOps == 2 &&
5918cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner          cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
5928cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner        ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
593156eb0a569a1ebac86ad8438645f690d8a3894c4Chris Lattner        assert((CE == 0 || CE->getType() == IntPtrTy) &&
594f1cadf28991b2643128bfe38990ff235f2cb1491Chris Lattner               "CastGEPIndices didn't canonicalize index types!");
5958cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner        if (CE && CE->getOpcode() == Instruction::Sub &&
596f1cadf28991b2643128bfe38990ff235f2cb1491Chris Lattner            CE->getOperand(0)->isNullValue()) {
5978cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner          Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
5988cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner          Res = ConstantExpr::getSub(Res, CE->getOperand(1));
5998cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner          Res = ConstantExpr::getIntToPtr(Res, ResultTy);
6008cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner          if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
6018cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner            Res = ConstantFoldConstantExpression(ResCE, TD);
6028cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner          return Res;
6038cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner        }
6048cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner      }
605de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman      return 0;
6068cd4efb6a5e51b4e77039c17338f290ca3a8ee92Chris Lattner    }
607268e7d7a9446bb89b80472cdb7b9803f16c0191eChris Lattner
608f1cadf28991b2643128bfe38990ff235f2cb1491Chris Lattner  unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
609cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman  APInt Offset = APInt(BitWidth,
610cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman                       TD->getIndexedOffset(Ptr->getType(),
611cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman                                            (Value**)Ops+1, NumOps-1));
612890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands  Ptr = cast<Constant>(Ptr->stripPointerCasts());
6130891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman
6140891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman  // If this is a GEP of a GEP, fold it all into a single GEP.
6150891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman  while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
6160891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman    SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
617890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands
618890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands    // Do not try the incorporate the sub-GEP if some index is not a number.
619890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands    bool AllConstantInt = true;
620890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands    for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
621890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands      if (!isa<ConstantInt>(NestedOps[i])) {
622890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands        AllConstantInt = false;
623890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands        break;
624890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands      }
625890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands    if (!AllConstantInt)
626890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands      break;
627890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands
6280891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman    Ptr = cast<Constant>(GEP->getOperand(0));
6290891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman    Offset += APInt(BitWidth,
6300891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman                    TD->getIndexedOffset(Ptr->getType(),
6310891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman                                         (Value**)NestedOps.data(),
6320891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman                                         NestedOps.size()));
633890edda7c22dd8525f9fe44085cfd7080e67dfeeDuncan Sands    Ptr = cast<Constant>(Ptr->stripPointerCasts());
6340891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman  }
6350891d752a68a25025ffc3339aab1f0ad3221b0edDan Gohman
636de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  // If the base value for this address is a literal integer value, fold the
637de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  // getelementptr to the resulting integer value casted to the pointer type.
63840b037ef611efc5c43ffc43a911d0eb57e0d444dDan Gohman  APInt BasePtr(BitWidth, 0);
63940b037ef611efc5c43ffc43a911d0eb57e0d444dDan Gohman  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
64040b037ef611efc5c43ffc43a911d0eb57e0d444dDan Gohman    if (CE->getOpcode() == Instruction::IntToPtr)
64140f8f6264d5af2c38e797e0dc59827cd231e8ff7Jay Foad      if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
64240f8f6264d5af2c38e797e0dc59827cd231e8ff7Jay Foad        BasePtr = Base->getValue().zextOrTrunc(BitWidth);
64340b037ef611efc5c43ffc43a911d0eb57e0d444dDan Gohman  if (Ptr->isNullValue() || BasePtr != 0) {
6447b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
645de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman    return ConstantExpr::getIntToPtr(C, ResultTy);
646de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  }
647de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman
648de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  // Otherwise form a regular getelementptr. Recompute the indices so that
649de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  // we eliminate over-indexing of the notional static type array bounds.
650de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  // This makes it easy to determine if the getelementptr is "inbounds".
651de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  // Also, this helps GlobalOpt do SROA on GlobalVariables.
652de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  const Type *Ty = Ptr->getType();
653de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman  SmallVector<Constant*, 32> NewIdxs;
6543d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  do {
655de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman    if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
6561df9859c40492511b8aa4321eb76496005d3b75bDuncan Sands      if (ATy->isPointerTy()) {
657e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner        // The only pointer indexing we'll do is on the first index of the GEP.
658e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner        if (!NewIdxs.empty())
659e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner          break;
660e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner
661e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner        // Only handle pointers to sized types, not pointers to functions.
662e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner        if (!ATy->getElementType()->isSized())
663e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner          return 0;
664e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner      }
665e568fa2d29c58aaedcaa832f805949d5e4371b4bChris Lattner
666de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman      // Determine which element of the array the offset points into.
667cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman      APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
668c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner      const IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
669de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman      if (ElemSize == 0)
670c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        // The element size is 0. This may be [0 x Ty]*, so just use a zero
671e58391073f6e17cd1024f737618a6f6b8d1323ceDuncan Sands        // index for this level and proceed to the next level to see if it can
672e58391073f6e17cd1024f737618a6f6b8d1323ceDuncan Sands        // accommodate the offset.
673c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
674c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner      else {
675c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        // The element size is non-zero divide the offset by the element
676c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        // size (rounding down), to compute the index at this level.
677c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        APInt NewIdx = Offset.udiv(ElemSize);
678c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        Offset -= NewIdx * ElemSize;
679c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner        NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
680c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner      }
681de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman      Ty = ATy->getElementType();
682de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman    } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
683cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman      // Determine which field of the struct the offset points into. The
684cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman      // getZExtValue is at least as safe as the StructLayout API because we
685cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman      // know the offset is within the struct at this point.
686de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman      const StructLayout &SL = *TD->getStructLayout(STy);
687cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman      unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
6887b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner      NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
6897b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                         ElIdx));
690cda9706cb74a65d2feb2175613cb0fe46acc5aa2Dan Gohman      Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
691de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman      Ty = STy->getTypeAtIndex(ElIdx);
692de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman    } else {
6933d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman      // We've reached some non-indexable type.
6943d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman      break;
695de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman    }
6963d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  } while (Ty != cast<PointerType>(ResultTy)->getElementType());
6973d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman
6983d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  // If we haven't used up the entire offset by descending the static
6993d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  // type, then the offset is pointing into the middle of an indivisible
7003d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  // member, so we can't simplify it.
7013d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  if (Offset != 0)
7023d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman    return 0;
703de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman
7043bfbc4587a7e79f08f8c126a9e62c3475fb90f8bDan Gohman  // Create a GEP.
7053bfbc4587a7e79f08f8c126a9e62c3475fb90f8bDan Gohman  Constant *C =
7066e7ad958683f34bf6c014c88fef723e5a2d741beDan Gohman    ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
7076e7ad958683f34bf6c014c88fef723e5a2d741beDan Gohman  assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
7086e7ad958683f34bf6c014c88fef723e5a2d741beDan Gohman         "Computed GetElementPtr has unexpected type!");
7093d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman
7103d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  // If we ended up indexing a member with a type that doesn't match
7114c0d5d5db876b0628bdf6a2174263a1c0a9130e2Dan Gohman  // the type of what the original indices indexed, add a cast.
7123d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  if (Ty != cast<PointerType>(ResultTy)->getElementType())
7136333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner    C = FoldBitCast(C, ResultTy, *TD);
714de0e587e63f71afb2ac53c9880c262089fe798bbDan Gohman
7153d01334e6fa5caba1361d088fabf728c64b23c58Dan Gohman  return C;
71603dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner}
71703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
7181afab9c1e0ae2d145ce01718aa14065393117e70Chris Lattner
71903dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
72003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner//===----------------------------------------------------------------------===//
72103dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner// Constant Folding public APIs
72203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner//===----------------------------------------------------------------------===//
72303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
724b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands/// ConstantFoldInstruction - Try to constant fold the specified instruction.
725b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands/// If successful, the constant result is returned, if not, null is returned.
726b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands/// Note that this fails if not all of the operands are constant.  Otherwise,
727b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands/// this function can only fail when attempting to fold instructions like loads
728b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands/// and stores, which have no constant expression form.
7297b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris LattnerConstant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
730b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands  // Handle PHI nodes quickly here...
7315520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  if (PHINode *PN = dyn_cast<PHINode>(I)) {
732c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands    Constant *CommonValue = 0;
733c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands
734c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
735c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands      Value *Incoming = PN->getIncomingValue(i);
736b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands      // If the incoming value is undef then skip it.  Note that while we could
737b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands      // skip the value if it is equal to the phi node itself we choose not to
738b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands      // because that would break the rule that constant folding only applies if
739b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands      // all operands are constants.
740b9b369fa9983843c4ed77b3a35b6e9b7933955bbDuncan Sands      if (isa<UndefValue>(Incoming))
741c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands        continue;
742c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands      // If the incoming value is not a constant, or is a different constant to
743c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands      // the one we saw previously, then give up.
744c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands      Constant *C = dyn_cast<Constant>(Incoming);
745c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands      if (!C || (CommonValue && C != CommonValue))
746c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands        return 0;
747c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands      CommonValue = C;
748c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands    }
7495520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
750c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands    // If we reach here, all incoming values are the same constant or undef.
751c0362d5c6e0066c741bce056a65d8b4c026de19fDuncan Sands    return CommonValue ? CommonValue : UndefValue::get(PN->getType());
7525520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  }
7535520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
7545520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  // Scan the operand list, checking to see if they are all constants, if so,
7555520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  // hand off to ConstantFoldInstOperands.
7565520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  SmallVector<Constant*, 8> Ops;
757de2d74b213844b17eb5327fba27f21e699d3af66Gabor Greif  for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
758de2d74b213844b17eb5327fba27f21e699d3af66Gabor Greif    if (Constant *Op = dyn_cast<Constant>(*i))
7595520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      Ops.push_back(Op);
7605520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    else
7615520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      return 0;  // All operands not constant!
7625520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
763f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
7648f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner    return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
7658f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner                                           TD);
76658665d47aea69875c433fb039c8f10106abc1ceeChris Lattner
767878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner  if (const LoadInst *LI = dyn_cast<LoadInst>(I))
768878e4946700824954d7eb7f3ff660353db8e0d17Chris Lattner    return ConstantFoldLoadInst(LI, TD);
7693ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel
7703ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel  if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
7713ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel    return ConstantExpr::getInsertValue(
7723ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel                                cast<Constant>(IVI->getAggregateOperand()),
7733ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel                                cast<Constant>(IVI->getInsertedValueOperand()),
774fc6d3a49867cd38954dc40936a88f1907252c6d2Jay Foad                                IVI->getIndices());
7753ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel
7763ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel  if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
7773ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel    return ConstantExpr::getExtractValue(
7783ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel                                    cast<Constant>(EVI->getAggregateOperand()),
779fc6d3a49867cd38954dc40936a88f1907252c6d2Jay Foad                                    EVI->getIndices());
7803ee0af35842999c1781052fe74fdcb19997de950Frits van Bommel
78158665d47aea69875c433fb039c8f10106abc1ceeChris Lattner  return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
7827b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                  Ops.data(), Ops.size(), TD);
7835520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner}
7845520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
7853dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky/// ConstantFoldConstantExpression - Attempt to fold the constant expression
7863dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky/// using the specified TargetData.  If successful, the constant result is
7873dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky/// result is returned, if not, null is returned.
788baf0c67988feec5b7698f89dce499ddb7d0c3c42Dan GohmanConstant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
7893dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky                                               const TargetData *TD) {
7903dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky  SmallVector<Constant*, 8> Ops;
791c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner  for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end();
792c1da204c433459713cbf4c62f0addf458e6b4b9fChris Lattner       i != e; ++i) {
79301b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman    Constant *NewC = cast<Constant>(*i);
79401b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman    // Recursively fold the ConstantExpr's operands.
79501b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman    if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC))
79601b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman      NewC = ConstantFoldConstantExpression(NewCE, TD);
79701b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman    Ops.push_back(NewC);
79801b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman  }
7993dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky
8003dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky  if (CE->isCompare())
8018f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner    return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
8028f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner                                           TD);
80358665d47aea69875c433fb039c8f10106abc1ceeChris Lattner  return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
8047b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                  Ops.data(), Ops.size(), TD);
8053dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky}
8063dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky
8075520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
8085520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// specified opcode and operands.  If successful, the constant result is
8095520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// returned, if not, null is returned.  Note that this function can fail when
8105520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// attempting to fold instructions like loads and stores, which have no
8115520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// constant expression form.
8125520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner///
81301b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
81401b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman/// information, due to only being passed an opcode and operands. Constant
81501b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman/// folding using this function strips this information.
81601b97dd01eec1197d79fceb7229f5ec233994de3Dan Gohman///
817f286f6fd93d569befe6e77c94a947e6e04e95685Chris LattnerConstant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
818f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner                                         Constant* const* Ops, unsigned NumOps,
8195520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner                                         const TargetData *TD) {
82003dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  // Handle easy binops first.
821f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  if (Instruction::isBinaryOp(Opcode)) {
82203dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner    if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
8237b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner      if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
82403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner        return C;
82503dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
826baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
82703dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner  }
8285520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
829f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  switch (Opcode) {
8305520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  default: return 0;
83179fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner  case Instruction::ICmp:
83279fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner  case Instruction::FCmp: assert(0 && "Invalid for compares");
8335520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::Call:
834a6aac4c5bc22bb10c7adb11eee3f82c703af7002Gabor Greif    if (Function *F = dyn_cast<Function>(Ops[NumOps - 1]))
8355520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      if (canConstantFoldCallTo(F))
836a6aac4c5bc22bb10c7adb11eee3f82c703af7002Gabor Greif        return ConstantFoldCall(F, Ops, NumOps - 1);
8375520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    return 0;
838001f7534e0311508cc93831a595785bb177f8a18Chris Lattner  case Instruction::PtrToInt:
839001f7534e0311508cc93831a595785bb177f8a18Chris Lattner    // If the input is a inttoptr, eliminate the pair.  This requires knowing
840001f7534e0311508cc93831a595785bb177f8a18Chris Lattner    // the width of a pointer, so it can't be done in ConstantExpr::getCast.
841001f7534e0311508cc93831a595785bb177f8a18Chris Lattner    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
842001f7534e0311508cc93831a595785bb177f8a18Chris Lattner      if (TD && CE->getOpcode() == Instruction::IntToPtr) {
843001f7534e0311508cc93831a595785bb177f8a18Chris Lattner        Constant *Input = CE->getOperand(0);
8446de29f8d960505421d61c80cdb738e16720b6c0eDan Gohman        unsigned InWidth = Input->getType()->getScalarSizeInBits();
84504aa2c3520c049333ca216fb794d700310c4a33dNick Lewycky        if (TD->getPointerSizeInBits() < InWidth) {
84604aa2c3520c049333ca216fb794d700310c4a33dNick Lewycky          Constant *Mask =
8477b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner            ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
84804aa2c3520c049333ca216fb794d700310c4a33dNick Lewycky                                                  TD->getPointerSizeInBits()));
849baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson          Input = ConstantExpr::getAnd(Input, Mask);
85004aa2c3520c049333ca216fb794d700310c4a33dNick Lewycky        }
851001f7534e0311508cc93831a595785bb177f8a18Chris Lattner        // Do a zext or trunc to get to the dest size.
852baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson        return ConstantExpr::getIntegerCast(Input, DestTy, false);
853001f7534e0311508cc93831a595785bb177f8a18Chris Lattner      }
854001f7534e0311508cc93831a595785bb177f8a18Chris Lattner    }
855baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
856001f7534e0311508cc93831a595785bb177f8a18Chris Lattner  case Instruction::IntToPtr:
85781b06be055e74a3c23a1c8f17ead97f9f76335eeDuncan Sands    // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
85881b06be055e74a3c23a1c8f17ead97f9f76335eeDuncan Sands    // the int size is >= the ptr size.  This requires knowing the width of a
85981b06be055e74a3c23a1c8f17ead97f9f76335eeDuncan Sands    // pointer, so it can't be done in ConstantExpr::getCast.
860b80a2a686fe76496d71397f8bdda394d5718ab01Dan Gohman    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
8619a38e3e3991ea443e555d8060f91202a786acdd4Dan Gohman      if (TD &&
862b80a2a686fe76496d71397f8bdda394d5718ab01Dan Gohman          TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
863b80a2a686fe76496d71397f8bdda394d5718ab01Dan Gohman          CE->getOpcode() == Instruction::PtrToInt)
864b80a2a686fe76496d71397f8bdda394d5718ab01Dan Gohman        return FoldBitCast(CE->getOperand(0), DestTy, *TD);
865b80a2a686fe76496d71397f8bdda394d5718ab01Dan Gohman
866baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
8675520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::Trunc:
8685520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::ZExt:
8695520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::SExt:
8705520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::FPTrunc:
8715520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::FPExt:
8725520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::UIToFP:
8735520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::SIToFP:
8745520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::FPToUI:
8755520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::FPToSI:
876baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson      return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
8775520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::BitCast:
8781afab9c1e0ae2d145ce01718aa14065393117e70Chris Lattner    if (TD)
8796333c3959b7e3e43930ab523f0657791e9eb5d48Chris Lattner      return FoldBitCast(Ops[0], DestTy, *TD);
880baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getBitCast(Ops[0], DestTy);
8815520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::Select:
882baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
8835520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::ExtractElement:
884baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
8855520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::InsertElement:
886baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
8875520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::ShuffleVector:
888baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
8895520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  case Instruction::GetElementPtr:
8904f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman    if (Constant *C = CastGEPIndices(Ops, NumOps, DestTy, TD))
8914f8eea82d8967cffa85b9df6c9255717b059009eDan Gohman      return C;
8927b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
89303dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner      return C;
89403dd25ca964813c8b9fe14479443b9c21fb92c55Chris Lattner
895baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson    return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
8965520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  }
8975520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner}
8985520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
899f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
900f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner/// instruction (icmp/fcmp) with the specified operands.  If it fails, it
901f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner/// returns a constant expression of the specified operands.
902f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner///
903f286f6fd93d569befe6e77c94a947e6e04e95685Chris LattnerConstant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
9048f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner                                                Constant *Ops0, Constant *Ops1,
905f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner                                                const TargetData *TD) {
906f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  // fold: icmp (inttoptr x), null         -> icmp x, 0
907f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  // fold: icmp (ptrtoint x), 0            -> icmp x, null
9083dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky  // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
909f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
910f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  //
911f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  // ConstantExpr::getCompare cannot do this, because it doesn't have TD
912f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  // around to know if bit truncation is happening.
9138f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner  if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
9148f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner    if (TD && Ops1->isNullValue()) {
9157b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner      const Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
916f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      if (CE0->getOpcode() == Instruction::IntToPtr) {
917f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner        // Convert the integer value to the right size to ensure we get the
918f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner        // proper extension or truncation.
919baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson        Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
920f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner                                                   IntPtrTy, false);
9218f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner        Constant *Null = Constant::getNullValue(C->getType());
9228f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner        return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
923f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      }
924f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner
925f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      // Only do this transformation if the int is intptrty in size, otherwise
926f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      // there is a truncation or extension that we aren't modeling.
927f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      if (CE0->getOpcode() == Instruction::PtrToInt &&
928f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner          CE0->getType() == IntPtrTy) {
929f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner        Constant *C = CE0->getOperand(0);
9308f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner        Constant *Null = Constant::getNullValue(C->getType());
9318f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner        return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
932f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      }
933f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner    }
934f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner
9358f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner    if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
9363dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky      if (TD && CE0->getOpcode() == CE1->getOpcode()) {
9377b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner        const Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
9383dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky
9393dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky        if (CE0->getOpcode() == Instruction::IntToPtr) {
9403dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky          // Convert the integer value to the right size to ensure we get the
9413dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky          // proper extension or truncation.
942baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson          Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
9433dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky                                                      IntPtrTy, false);
944baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson          Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
9453dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky                                                      IntPtrTy, false);
9468f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner          return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD);
9473dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky        }
9483dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky
9493dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky        // Only do this transformation if the int is intptrty in size, otherwise
9503dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky        // there is a truncation or extension that we aren't modeling.
9513dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky        if ((CE0->getOpcode() == Instruction::PtrToInt &&
9523dfd7bf5110c47e99fd0fcce96122b90f699ca3aNick Lewycky             CE0->getType() == IntPtrTy &&
9538f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner             CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
9548f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner          return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
9558f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner                                                 CE1->getOperand(0), TD);
956f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner      }
957f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner    }
95879fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner
95979fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner    // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
96079fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner    // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
96179fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner    if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
96279fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner        CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
96379fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner      Constant *LHS =
96479fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner        ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,TD);
96579fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner      Constant *RHS =
96679fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner        ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,TD);
96779fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner      unsigned OpC =
96879fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner        Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
96979fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner      Constant *Ops[] = { LHS, RHS };
97079fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner      return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, 2, TD);
97179fa3cf451a74dd1cec0be2d77d7ea9737dffc69Chris Lattner    }
972f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner  }
9738f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner
9748f73deaa8732a556046bf4ac6207be55972e3b74Chris Lattner  return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
975f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner}
976f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner
977f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattner
9785520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
9795520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// getelementptr constantexpr, return the constant value being addressed by the
9805520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner/// constant expression, or null if something is funny and we can't decide.
9815520732b24a5a321140dd79af70d321c7ff3dec9Chris LattnerConstant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
982c6f69e94fa46f585b59bb9d7ace3224b0e638c95Dan Gohman                                                       ConstantExpr *CE) {
983a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson  if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
9845520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    return 0;  // Do not allow stepping over the value!
9855520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
9865520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  // Loop over all of the operands, tracking down which value we are
9875520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  // addressing...
9885520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
9895520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  for (++I; I != E; ++I)
9905520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    if (const StructType *STy = dyn_cast<StructType>(*I)) {
9915520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      ConstantInt *CU = cast<ConstantInt>(I.getOperand());
9925520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      assert(CU->getZExtValue() < STy->getNumElements() &&
9935520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner             "Struct index out of range!");
9945520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      unsigned El = (unsigned)CU->getZExtValue();
9955520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
9965520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        C = CS->getOperand(El);
9975520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      } else if (isa<ConstantAggregateZero>(C)) {
998a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson        C = Constant::getNullValue(STy->getElementType(El));
9995520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      } else if (isa<UndefValue>(C)) {
10009e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson        C = UndefValue::get(STy->getElementType(El));
10015520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      } else {
10025520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        return 0;
10035520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      }
10045520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
10055520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
10065520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        if (CI->getZExtValue() >= ATy->getNumElements())
10075520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner         return 0;
10085520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
10095520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner          C = CA->getOperand(CI->getZExtValue());
10105520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        else if (isa<ConstantAggregateZero>(C))
1011a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson          C = Constant::getNullValue(ATy->getElementType());
10125520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        else if (isa<UndefValue>(C))
10139e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson          C = UndefValue::get(ATy->getElementType());
10145520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        else
10155520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner          return 0;
101662d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner      } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
101762d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner        if (CI->getZExtValue() >= VTy->getNumElements())
10185520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner          return 0;
10199d6565a5b1fbc4286d6ee638d8f47a3171a9ed7eReid Spencer        if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
10205520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner          C = CP->getOperand(CI->getZExtValue());
10215520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        else if (isa<ConstantAggregateZero>(C))
102262d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner          C = Constant::getNullValue(VTy->getElementType());
10235520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        else if (isa<UndefValue>(C))
102462d327e241f59735eed836e98c8f11ffaa6cf6f8Chris Lattner          C = UndefValue::get(VTy->getElementType());
10255520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        else
10265520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner          return 0;
10275520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      } else {
10285520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner        return 0;
10295520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      }
10305520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    } else {
10315520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner      return 0;
10325520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner    }
10335520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner  return C;
10345520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner}
10355520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
10365520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner
1037bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//===----------------------------------------------------------------------===//
10385520732b24a5a321140dd79af70d321c7ff3dec9Chris Lattner//  Constant Folding for Calls
1039bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell//
1040bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
1041bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell/// canConstantFoldCallTo - Return true if its even possible to fold a call to
1042bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell/// the specified function.
1043bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswellbool
1044fa9b80eb64127b3d9691e18537975635520e51e9Dan Gohmanllvm::canConstantFoldCallTo(const Function *F) {
1045bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  switch (F->getIntrinsicID()) {
10469ab7fb3ba47442d521a5bed09a27a5e8e7a786edDale Johannesen  case Intrinsic::sqrt:
10479ab7fb3ba47442d521a5bed09a27a5e8e7a786edDale Johannesen  case Intrinsic::powi:
1048e9391fd9b52e93717b365bdd05c471101323a4dfReid Spencer  case Intrinsic::bswap:
1049e9391fd9b52e93717b365bdd05c471101323a4dfReid Spencer  case Intrinsic::ctpop:
1050e9391fd9b52e93717b365bdd05c471101323a4dfReid Spencer  case Intrinsic::ctlz:
1051e9391fd9b52e93717b365bdd05c471101323a4dfReid Spencer  case Intrinsic::cttz:
10521614e50d9f6d48a38e4dafb4b1a51fd4b37614f3Evan Phoenix  case Intrinsic::sadd_with_overflow:
10536208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel  case Intrinsic::uadd_with_overflow:
10541614e50d9f6d48a38e4dafb4b1a51fd4b37614f3Evan Phoenix  case Intrinsic::ssub_with_overflow:
10556208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel  case Intrinsic::usub_with_overflow:
1056eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner  case Intrinsic::smul_with_overflow:
10576208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel  case Intrinsic::umul_with_overflow:
1058faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov  case Intrinsic::convert_from_fp16:
1059faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov  case Intrinsic::convert_to_fp16:
106015ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse_cvtss2si:
106115ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse_cvtss2si64:
106215ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse_cvttss2si:
106315ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse_cvttss2si64:
106415ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse2_cvtsd2si:
106515ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse2_cvtsd2si64:
106615ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse2_cvttsd2si:
106715ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  case Intrinsic::x86_sse2_cvttsd2si64:
1068bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell    return true;
106968a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner  default:
107068a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner    return false;
107168a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner  case 0: break;
1072bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  }
1073bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
10746f532a988e5c02fcb271fb65e9e7b83f0147d3f2Chris Lattner  if (!F->hasName()) return false;
1075f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar  StringRef Name = F->getName();
1076c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner
1077c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  // In these cases, the check of the length is required.  We don't want to
1078c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  // return true for a name like "cos\0blah" which strcmp would return equal to
1079c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  // "cos", but has length 8.
1080f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar  switch (Name[0]) {
1081c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  default: return false;
1082c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 'a':
1083f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "acos" || Name == "asin" ||
1084f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar      Name == "atan" || Name == "atan2";
1085c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 'c':
1086f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1087c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 'e':
1088805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner    return Name == "exp" || Name == "exp2";
1089c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 'f':
1090f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "fabs" || Name == "fmod" || Name == "floor";
1091c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 'l':
1092f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "log" || Name == "log10";
1093c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 'p':
1094f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "pow";
1095c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 's':
1096f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1097f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar      Name == "sinf" || Name == "sqrtf";
1098c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner  case 't':
1099f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar    return Name == "tan" || Name == "tanh";
1100bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  }
1101bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell}
1102bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
110372d88ae5447a3929c97e88f4c806213847b5d988Chris Lattnerstatic Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
11047b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                const Type *Ty) {
11053f2f21e640682c604d9322ba0708e122d1fcf5eeDan Gohman  sys::llvm_fenv_clearexcept();
1106bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  V = NativeFP(V);
11073f2f21e640682c604d9322ba0708e122d1fcf5eeDan Gohman  if (sys::llvm_fenv_testexcept()) {
11083f2f21e640682c604d9322ba0708e122d1fcf5eeDan Gohman    sys::llvm_fenv_clearexcept();
1109f19f58a9360927f8ef50b9a029e8efb780d3d8a8Chris Lattner    return 0;
111043421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen  }
1111f19f58a9360927f8ef50b9a029e8efb780d3d8a8Chris Lattner
1112d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner  if (Ty->isFloatTy())
11137b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1114d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner  if (Ty->isDoubleTy())
11157b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    return ConstantFP::get(Ty->getContext(), APFloat(V));
1116c23197a26f34f559ea9797de51e187087c039c42Torok Edwin  llvm_unreachable("Can only constant fold float/double");
111733e456d5f3909e0c7b96e04e5674c25a182da100Gabor Greif  return 0; // dummy return to suppress warning
1118bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell}
1119bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
1120384152444d22d356f7b4090a158da4cbc1f79464Dan Gohmanstatic Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
11217b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                      double V, double W, const Type *Ty) {
11223f2f21e640682c604d9322ba0708e122d1fcf5eeDan Gohman  sys::llvm_fenv_clearexcept();
1123384152444d22d356f7b4090a158da4cbc1f79464Dan Gohman  V = NativeFP(V, W);
11243f2f21e640682c604d9322ba0708e122d1fcf5eeDan Gohman  if (sys::llvm_fenv_testexcept()) {
11253f2f21e640682c604d9322ba0708e122d1fcf5eeDan Gohman    sys::llvm_fenv_clearexcept();
1126f19f58a9360927f8ef50b9a029e8efb780d3d8a8Chris Lattner    return 0;
112743421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen  }
1128f19f58a9360927f8ef50b9a029e8efb780d3d8a8Chris Lattner
1129d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner  if (Ty->isFloatTy())
11307b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1131d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner  if (Ty->isDoubleTy())
11327b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner    return ConstantFP::get(Ty->getContext(), APFloat(V));
1133c23197a26f34f559ea9797de51e187087c039c42Torok Edwin  llvm_unreachable("Can only constant fold float/double");
113433e456d5f3909e0c7b96e04e5674c25a182da100Gabor Greif  return 0; // dummy return to suppress warning
1135384152444d22d356f7b4090a158da4cbc1f79464Dan Gohman}
1136384152444d22d356f7b4090a158da4cbc1f79464Dan Gohman
113715ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
113815ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// conversion of a constant floating point. If roundTowardZero is false, the
113915ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// default IEEE rounding is used (toward nearest, ties to even). This matches
114015ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// the behavior of the non-truncating SSE instructions in the default rounding
114115ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// mode. The desired integer type Ty is used to select how many bits are
114215ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// available for the result. Returns null if the conversion cannot be
114315ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// performed, otherwise returns the Constant value resulting from the
114415ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth/// conversion.
114515ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruthstatic Constant *ConstantFoldConvertToInt(ConstantFP *Op, bool roundTowardZero,
114615ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth                                          const Type *Ty) {
114715ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  assert(Op && "Called with NULL operand");
114815ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  APFloat Val(Op->getValueAPF());
114915ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth
115015ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  // All of these conversion intrinsics form an integer of at most 64bits.
115115ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
115215ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  assert(ResultWidth <= 64 &&
115315ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth         "Can only constant fold conversions to 64 and 32 bit ints");
115415ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth
115515ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  uint64_t UIntVal;
115615ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  bool isExact = false;
115715ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
115815ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth                                              : APFloat::rmNearestTiesToEven;
115915ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
116015ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth                                                  /*isSigned=*/true, mode,
116115ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth                                                  &isExact);
116215ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  if (status != APFloat::opOK && status != APFloat::opInexact)
116315ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth    return 0;
116415ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth  return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
116515ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth}
116615ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth
1167bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell/// ConstantFoldCall - Attempt to constant fold a call to the specified function
1168bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell/// with the specified arguments, returning null if unsuccessful.
1169bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John CriswellConstant *
1170f286f6fd93d569befe6e77c94a947e6e04e95685Chris Lattnerllvm::ConstantFoldCall(Function *F,
117168a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner                       Constant *const *Operands, unsigned NumOperands) {
11726f532a988e5c02fcb271fb65e9e7b83f0147d3f2Chris Lattner  if (!F->hasName()) return 0;
1173f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar  StringRef Name = F->getName();
1174e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner
1175bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  const Type *Ty = F->getReturnType();
117672d88ae5447a3929c97e88f4c806213847b5d988Chris Lattner  if (NumOperands == 1) {
1177bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell    if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1178f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1179faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        APFloat Val(Op->getValueAPF());
1180faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov
1181faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        bool lost = false;
1182faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1183faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov
1184faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1185faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov      }
1186faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov
1187d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner      if (!Ty->isFloatTy() && !Ty->isDoubleTy())
118843421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen        return 0;
11891f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen
11901f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen      /// We only fold functions with finite arguments. Folding NaN and inf is
11911f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen      /// likely to be aborted with an exception anyway, and some host libms
11921f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen      /// have known errors raising exceptions.
11931f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen      if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
11941f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen        return 0;
11951f386c4ce1983c448320aecca8d3cd27d1497867Jakob Stoklund Olesen
119643421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen      /// Currently APFloat versions of these functions do not exist, so we use
119743421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen      /// the host native double versions.  Float versions are not called
119843421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen      /// directly but for all these it is true (float)(f((double)arg)) ==
119943421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen      /// f(arg).  Long double not supported yet.
1200d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner      double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
120143421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen                                     Op->getValueAPF().convertToDouble();
1202f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar      switch (Name[0]) {
1203c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 'a':
1204f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "acos")
12057b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(acos, V, Ty);
1206f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "asin")
12077b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(asin, V, Ty);
1208f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "atan")
12097b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(atan, V, Ty);
1210c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1211c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 'c':
1212f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "ceil")
12137b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(ceil, V, Ty);
1214f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "cos")
12157b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(cos, V, Ty);
1216f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "cosh")
12177b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(cosh, V, Ty);
1218f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "cosf")
12197b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(cos, V, Ty);
1220c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1221c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 'e':
1222f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "exp")
12237b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(exp, V, Ty);
1224805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner
1225805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner        if (Name == "exp2") {
1226805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner          // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1227805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner          // C99 library.
1228805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner          return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1229805fa97a0f5ff61624855da37d4881708fb8f0fbChris Lattner        }
1230c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1231c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 'f':
1232f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "fabs")
12337b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(fabs, V, Ty);
1234f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "floor")
12357b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(floor, V, Ty);
1236c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1237c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 'l':
1238f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "log" && V > 0)
12397b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(log, V, Ty);
1240f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "log10" && V > 0)
12417b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(log10, V, Ty);
1242f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth        else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1243f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth                 (Ty->isFloatTy() || Ty->isDoubleTy())) {
1244c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner          if (V >= -0.0)
12457b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner            return ConstantFoldFP(sqrt, V, Ty);
1246c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner          else // Undefined
1247a7235ea7245028a0723e8ab7fd011386b3900777Owen Anderson            return Constant::getNullValue(Ty);
1248c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        }
1249c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1250c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 's':
1251f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "sin")
12527b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(sin, V, Ty);
1253f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "sinh")
12547b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(sinh, V, Ty);
1255f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "sqrt" && V >= 0)
12567b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(sqrt, V, Ty);
1257f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "sqrtf" && V >= 0)
12587b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(sqrt, V, Ty);
1259f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "sinf")
12607b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(sin, V, Ty);
1261c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1262c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      case 't':
1263f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        if (Name == "tan")
12647b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(tan, V, Ty);
1265f0443c1eb44d737d9bd78962932fc80f74c6113cDaniel Dunbar        else if (Name == "tanh")
12667b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldFP(tanh, V, Ty);
1267c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1268c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner      default:
1269c5f6a1f9d61d74017d90e149728cb3d283e0a0e0Chris Lattner        break;
1270bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell      }
127168a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner      return 0;
127268a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner    }
1273f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth
127468a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner    if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1275f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      switch (F->getIntrinsicID()) {
1276f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      case Intrinsic::bswap:
12777b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner        return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1278f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      case Intrinsic::ctpop:
1279eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson        return ConstantInt::get(Ty, Op->getValue().countPopulation());
1280f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      case Intrinsic::cttz:
1281eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson        return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
1282f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      case Intrinsic::ctlz:
1283eed707b1e6097aac2bb6b3d47271f6300ace7f2eOwen Anderson        return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
1284f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      case Intrinsic::convert_from_fp16: {
1285faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        APFloat Val(Op->getValue());
1286faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov
1287faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        bool lost = false;
1288faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        APFloat::opStatus status =
1289faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov          Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1290faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov
1291faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        // Conversion is always precise.
12928e68c3873549ca31533e2e3e40dda3a43cb79566Jeffrey Yasskin        (void)status;
1293faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        assert(status == APFloat::opOK && !lost &&
1294faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov               "Precision lost during fp16 constfolding");
1295faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov
1296faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov        return ConstantFP::get(F->getContext(), Val);
1297faa75f6e47350f491a44d5e8773acd9457185d51Anton Korobeynikov      }
1298f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      default:
1299f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth        return 0;
1300f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      }
1301bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell    }
1302f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth
130315ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth    if (ConstantVector *Op = dyn_cast<ConstantVector>(Operands[0])) {
130415ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      switch (F->getIntrinsicID()) {
130515ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      default: break;
130615ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse_cvtss2si:
130715ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse_cvtss2si64:
130815ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse2_cvtsd2si:
130915ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse2_cvtsd2si64:
131015ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth        if (ConstantFP *FPOp = dyn_cast<ConstantFP>(Op->getOperand(0)))
131115ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth          return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=*/false, Ty);
131215ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse_cvttss2si:
131315ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse_cvttss2si64:
131415ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse2_cvttsd2si:
131515ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      case Intrinsic::x86_sse2_cvttsd2si64:
131615ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth        if (ConstantFP *FPOp = dyn_cast<ConstantFP>(Op->getOperand(0)))
131715ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth          return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=*/true, Ty);
131815ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth      }
131915ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth    }
132015ed90c859e5df11112c614c83d0d2e786d4c73aChandler Carruth
13219ee7123ab462d97a2b242280e9bf0b47883531cbDan Gohman    if (isa<UndefValue>(Operands[0])) {
1322f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth      if (F->getIntrinsicID() == Intrinsic::bswap)
13239ee7123ab462d97a2b242280e9bf0b47883531cbDan Gohman        return Operands[0];
13249ee7123ab462d97a2b242280e9bf0b47883531cbDan Gohman      return 0;
13259ee7123ab462d97a2b242280e9bf0b47883531cbDan Gohman    }
13269ee7123ab462d97a2b242280e9bf0b47883531cbDan Gohman
132768a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner    return 0;
132868a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner  }
1329f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth
133068a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner  if (NumOperands == 2) {
1331bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell    if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1332d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner      if (!Ty->isFloatTy() && !Ty->isDoubleTy())
13339ab7fb3ba47442d521a5bed09a27a5e8e7a786edDale Johannesen        return 0;
1334d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner      double Op1V = Ty->isFloatTy() ?
1335d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner                      (double)Op1->getValueAPF().convertToFloat() :
133643421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen                      Op1->getValueAPF().convertToDouble();
1337bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell      if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1338d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner        if (Op2->getType() != Op1->getType())
1339d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner          return 0;
1340d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner
1341d0806a1519f3bc450d2dea3e6f22db73fc797e4cChris Lattner        double Op2V = Ty->isFloatTy() ?
134243421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen                      (double)Op2->getValueAPF().convertToFloat():
134343421b3dd70af5b70e71816521f37502c397cc65Dale Johannesen                      Op2->getValueAPF().convertToDouble();
1344bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell
134568a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner        if (Name == "pow")
13467b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
134768a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner        if (Name == "fmod")
13487b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
134968a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner        if (Name == "atan2")
13507b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1351b5282dcf4745be59046f440980a1c0f0a50c9c09Chris Lattner      } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1352f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth        if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
13537b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFP::get(F->getContext(),
13547b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                 APFloat((float)std::pow((float)Op1V,
135502a260aa11a2e1b2c14335274d3c42ca3f3eabc0Chris Lattner                                                 (int)Op2C->getZExtValue())));
1356f4db877cff62340aaf9f29d3994562ae1cee8d72Chandler Carruth        if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
13577b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner          return ConstantFP::get(F->getContext(),
13587b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                 APFloat((double)std::pow((double)Op1V,
13597b550ccfc5a3346c17e0390a59e2d6d19bc52705Chris Lattner                                                   (int)Op2C->getZExtValue())));
1360bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell      }
136168a0603dc5d3d79cd4de2195e950af26c3380cd7Chris Lattner      return 0;
1362bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell    }
1363e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner
1364e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner
1365e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner    if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1366e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner      if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1367e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner        switch (F->getIntrinsicID()) {
1368e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner        default: break;
1369eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner        case Intrinsic::sadd_with_overflow:
1370eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner        case Intrinsic::uadd_with_overflow:
1371eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner        case Intrinsic::ssub_with_overflow:
1372eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner        case Intrinsic::usub_with_overflow:
13736208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel        case Intrinsic::smul_with_overflow:
13746208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel        case Intrinsic::umul_with_overflow: {
1375eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          APInt Res;
1376eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          bool Overflow;
1377eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          switch (F->getIntrinsicID()) {
1378eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          default: assert(0 && "Invalid case");
1379eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          case Intrinsic::sadd_with_overflow:
1380eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1381eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            break;
1382eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          case Intrinsic::uadd_with_overflow:
1383eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1384eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            break;
1385eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          case Intrinsic::ssub_with_overflow:
1386eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1387eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            break;
1388eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          case Intrinsic::usub_with_overflow:
1389eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1390eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            break;
1391eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          case Intrinsic::smul_with_overflow:
1392eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1393eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            break;
13946208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel          case Intrinsic::umul_with_overflow:
13956208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel            Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
13966208610fd602ebdb18bb793152899573d0b2b7abFrits van Bommel            break;
1397eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner          }
1398e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner          Constant *Ops[] = {
1399eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            ConstantInt::get(F->getContext(), Res),
1400eafc5cb80d58cb9447623a557be4d4f55f42fbc3Chris Lattner            ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1401e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner          };
1402b065b06c12dba6001b8140df2744d0c856ef6ea1Chris Lattner          return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
1403e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner        }
1404e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner        }
1405e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner      }
1406e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner
1407e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner      return 0;
1408e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner    }
1409e65cd40ab99c3bd43dc997873e500643d012bbadChris Lattner    return 0;
1410bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  }
1411bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell  return 0;
1412bd9d37026a5c17d9a51371a6a5446bf4761ee7d6John Criswell}
1413