Home | History | Annotate | Download | only in IR
      1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements folding of constants for LLVM.  This implements the
     11 // (internal) ConstantFold.h interface, which is used by the
     12 // ConstantExpr::get* methods to automatically fold constants when possible.
     13 //
     14 // The current constant folding implementation is implemented in two pieces: the
     15 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
     16 // a dependence in IR on Target.
     17 //
     18 //===----------------------------------------------------------------------===//
     19 
     20 #include "ConstantFold.h"
     21 #include "llvm/ADT/SmallVector.h"
     22 #include "llvm/IR/Constants.h"
     23 #include "llvm/IR/DerivedTypes.h"
     24 #include "llvm/IR/Function.h"
     25 #include "llvm/IR/GlobalAlias.h"
     26 #include "llvm/IR/GlobalVariable.h"
     27 #include "llvm/IR/Instructions.h"
     28 #include "llvm/IR/Operator.h"
     29 #include "llvm/Support/Compiler.h"
     30 #include "llvm/Support/ErrorHandling.h"
     31 #include "llvm/Support/GetElementPtrTypeIterator.h"
     32 #include "llvm/Support/ManagedStatic.h"
     33 #include "llvm/Support/MathExtras.h"
     34 #include <limits>
     35 using namespace llvm;
     36 
     37 //===----------------------------------------------------------------------===//
     38 //                ConstantFold*Instruction Implementations
     39 //===----------------------------------------------------------------------===//
     40 
     41 /// BitCastConstantVector - Convert the specified vector Constant node to the
     42 /// specified vector type.  At this point, we know that the elements of the
     43 /// input vector constant are all simple integer or FP values.
     44 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
     45 
     46   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
     47   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
     48 
     49   // If this cast changes element count then we can't handle it here:
     50   // doing so requires endianness information.  This should be handled by
     51   // Analysis/ConstantFolding.cpp
     52   unsigned NumElts = DstTy->getNumElements();
     53   if (NumElts != CV->getType()->getVectorNumElements())
     54     return 0;
     55 
     56   Type *DstEltTy = DstTy->getElementType();
     57 
     58   SmallVector<Constant*, 16> Result;
     59   Type *Ty = IntegerType::get(CV->getContext(), 32);
     60   for (unsigned i = 0; i != NumElts; ++i) {
     61     Constant *C =
     62       ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
     63     C = ConstantExpr::getBitCast(C, DstEltTy);
     64     Result.push_back(C);
     65   }
     66 
     67   return ConstantVector::get(Result);
     68 }
     69 
     70 /// This function determines which opcode to use to fold two constant cast
     71 /// expressions together. It uses CastInst::isEliminableCastPair to determine
     72 /// the opcode. Consequently its just a wrapper around that function.
     73 /// @brief Determine if it is valid to fold a cast of a cast
     74 static unsigned
     75 foldConstantCastPair(
     76   unsigned opc,          ///< opcode of the second cast constant expression
     77   ConstantExpr *Op,      ///< the first cast constant expression
     78   Type *DstTy      ///< desintation type of the first cast
     79 ) {
     80   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
     81   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
     82   assert(CastInst::isCast(opc) && "Invalid cast opcode");
     83 
     84   // The the types and opcodes for the two Cast constant expressions
     85   Type *SrcTy = Op->getOperand(0)->getType();
     86   Type *MidTy = Op->getType();
     87   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
     88   Instruction::CastOps secondOp = Instruction::CastOps(opc);
     89 
     90   // Assume that pointers are never more than 64 bits wide.
     91   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
     92 
     93   // Let CastInst::isEliminableCastPair do the heavy lifting.
     94   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
     95                                         FakeIntPtrTy, FakeIntPtrTy,
     96                                         FakeIntPtrTy);
     97 }
     98 
     99 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
    100   Type *SrcTy = V->getType();
    101   if (SrcTy == DestTy)
    102     return V; // no-op cast
    103 
    104   // Check to see if we are casting a pointer to an aggregate to a pointer to
    105   // the first element.  If so, return the appropriate GEP instruction.
    106   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
    107     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
    108       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
    109           && DPTy->getElementType()->isSized()) {
    110         SmallVector<Value*, 8> IdxList;
    111         Value *Zero =
    112           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
    113         IdxList.push_back(Zero);
    114         Type *ElTy = PTy->getElementType();
    115         while (ElTy != DPTy->getElementType()) {
    116           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
    117             if (STy->getNumElements() == 0) break;
    118             ElTy = STy->getElementType(0);
    119             IdxList.push_back(Zero);
    120           } else if (SequentialType *STy =
    121                      dyn_cast<SequentialType>(ElTy)) {
    122             if (ElTy->isPointerTy()) break;  // Can't index into pointers!
    123             ElTy = STy->getElementType();
    124             IdxList.push_back(Zero);
    125           } else {
    126             break;
    127           }
    128         }
    129 
    130         if (ElTy == DPTy->getElementType())
    131           // This GEP is inbounds because all indices are zero.
    132           return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
    133       }
    134 
    135   // Handle casts from one vector constant to another.  We know that the src
    136   // and dest type have the same size (otherwise its an illegal cast).
    137   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
    138     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
    139       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
    140              "Not cast between same sized vectors!");
    141       SrcTy = NULL;
    142       // First, check for null.  Undef is already handled.
    143       if (isa<ConstantAggregateZero>(V))
    144         return Constant::getNullValue(DestTy);
    145 
    146       // Handle ConstantVector and ConstantAggregateVector.
    147       return BitCastConstantVector(V, DestPTy);
    148     }
    149 
    150     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
    151     // This allows for other simplifications (although some of them
    152     // can only be handled by Analysis/ConstantFolding.cpp).
    153     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
    154       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
    155   }
    156 
    157   // Finally, implement bitcast folding now.   The code below doesn't handle
    158   // bitcast right.
    159   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
    160     return ConstantPointerNull::get(cast<PointerType>(DestTy));
    161 
    162   // Handle integral constant input.
    163   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    164     if (DestTy->isIntegerTy())
    165       // Integral -> Integral. This is a no-op because the bit widths must
    166       // be the same. Consequently, we just fold to V.
    167       return V;
    168 
    169     if (DestTy->isFloatingPointTy())
    170       return ConstantFP::get(DestTy->getContext(),
    171                              APFloat(DestTy->getFltSemantics(),
    172                                      CI->getValue()));
    173 
    174     // Otherwise, can't fold this (vector?)
    175     return 0;
    176   }
    177 
    178   // Handle ConstantFP input: FP -> Integral.
    179   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
    180     return ConstantInt::get(FP->getContext(),
    181                             FP->getValueAPF().bitcastToAPInt());
    182 
    183   return 0;
    184 }
    185 
    186 
    187 /// ExtractConstantBytes - V is an integer constant which only has a subset of
    188 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
    189 /// first byte used, counting from the least significant byte) and ByteSize,
    190 /// which is the number of bytes used.
    191 ///
    192 /// This function analyzes the specified constant to see if the specified byte
    193 /// range can be returned as a simplified constant.  If so, the constant is
    194 /// returned, otherwise null is returned.
    195 ///
    196 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
    197                                       unsigned ByteSize) {
    198   assert(C->getType()->isIntegerTy() &&
    199          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
    200          "Non-byte sized integer input");
    201   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
    202   assert(ByteSize && "Must be accessing some piece");
    203   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
    204   assert(ByteSize != CSize && "Should not extract everything");
    205 
    206   // Constant Integers are simple.
    207   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
    208     APInt V = CI->getValue();
    209     if (ByteStart)
    210       V = V.lshr(ByteStart*8);
    211     V = V.trunc(ByteSize*8);
    212     return ConstantInt::get(CI->getContext(), V);
    213   }
    214 
    215   // In the input is a constant expr, we might be able to recursively simplify.
    216   // If not, we definitely can't do anything.
    217   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
    218   if (CE == 0) return 0;
    219 
    220   switch (CE->getOpcode()) {
    221   default: return 0;
    222   case Instruction::Or: {
    223     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
    224     if (RHS == 0)
    225       return 0;
    226 
    227     // X | -1 -> -1.
    228     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
    229       if (RHSC->isAllOnesValue())
    230         return RHSC;
    231 
    232     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
    233     if (LHS == 0)
    234       return 0;
    235     return ConstantExpr::getOr(LHS, RHS);
    236   }
    237   case Instruction::And: {
    238     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
    239     if (RHS == 0)
    240       return 0;
    241 
    242     // X & 0 -> 0.
    243     if (RHS->isNullValue())
    244       return RHS;
    245 
    246     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
    247     if (LHS == 0)
    248       return 0;
    249     return ConstantExpr::getAnd(LHS, RHS);
    250   }
    251   case Instruction::LShr: {
    252     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
    253     if (Amt == 0)
    254       return 0;
    255     unsigned ShAmt = Amt->getZExtValue();
    256     // Cannot analyze non-byte shifts.
    257     if ((ShAmt & 7) != 0)
    258       return 0;
    259     ShAmt >>= 3;
    260 
    261     // If the extract is known to be all zeros, return zero.
    262     if (ByteStart >= CSize-ShAmt)
    263       return Constant::getNullValue(IntegerType::get(CE->getContext(),
    264                                                      ByteSize*8));
    265     // If the extract is known to be fully in the input, extract it.
    266     if (ByteStart+ByteSize+ShAmt <= CSize)
    267       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
    268 
    269     // TODO: Handle the 'partially zero' case.
    270     return 0;
    271   }
    272 
    273   case Instruction::Shl: {
    274     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
    275     if (Amt == 0)
    276       return 0;
    277     unsigned ShAmt = Amt->getZExtValue();
    278     // Cannot analyze non-byte shifts.
    279     if ((ShAmt & 7) != 0)
    280       return 0;
    281     ShAmt >>= 3;
    282 
    283     // If the extract is known to be all zeros, return zero.
    284     if (ByteStart+ByteSize <= ShAmt)
    285       return Constant::getNullValue(IntegerType::get(CE->getContext(),
    286                                                      ByteSize*8));
    287     // If the extract is known to be fully in the input, extract it.
    288     if (ByteStart >= ShAmt)
    289       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
    290 
    291     // TODO: Handle the 'partially zero' case.
    292     return 0;
    293   }
    294 
    295   case Instruction::ZExt: {
    296     unsigned SrcBitSize =
    297       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
    298 
    299     // If extracting something that is completely zero, return 0.
    300     if (ByteStart*8 >= SrcBitSize)
    301       return Constant::getNullValue(IntegerType::get(CE->getContext(),
    302                                                      ByteSize*8));
    303 
    304     // If exactly extracting the input, return it.
    305     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
    306       return CE->getOperand(0);
    307 
    308     // If extracting something completely in the input, if if the input is a
    309     // multiple of 8 bits, recurse.
    310     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
    311       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
    312 
    313     // Otherwise, if extracting a subset of the input, which is not multiple of
    314     // 8 bits, do a shift and trunc to get the bits.
    315     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
    316       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
    317       Constant *Res = CE->getOperand(0);
    318       if (ByteStart)
    319         Res = ConstantExpr::getLShr(Res,
    320                                  ConstantInt::get(Res->getType(), ByteStart*8));
    321       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
    322                                                           ByteSize*8));
    323     }
    324 
    325     // TODO: Handle the 'partially zero' case.
    326     return 0;
    327   }
    328   }
    329 }
    330 
    331 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
    332 /// on Ty, with any known factors factored out. If Folded is false,
    333 /// return null if no factoring was possible, to avoid endlessly
    334 /// bouncing an unfoldable expression back into the top-level folder.
    335 ///
    336 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
    337                                  bool Folded) {
    338   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    339     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
    340     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
    341     return ConstantExpr::getNUWMul(E, N);
    342   }
    343 
    344   if (StructType *STy = dyn_cast<StructType>(Ty))
    345     if (!STy->isPacked()) {
    346       unsigned NumElems = STy->getNumElements();
    347       // An empty struct has size zero.
    348       if (NumElems == 0)
    349         return ConstantExpr::getNullValue(DestTy);
    350       // Check for a struct with all members having the same size.
    351       Constant *MemberSize =
    352         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
    353       bool AllSame = true;
    354       for (unsigned i = 1; i != NumElems; ++i)
    355         if (MemberSize !=
    356             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
    357           AllSame = false;
    358           break;
    359         }
    360       if (AllSame) {
    361         Constant *N = ConstantInt::get(DestTy, NumElems);
    362         return ConstantExpr::getNUWMul(MemberSize, N);
    363       }
    364     }
    365 
    366   // Pointer size doesn't depend on the pointee type, so canonicalize them
    367   // to an arbitrary pointee.
    368   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
    369     if (!PTy->getElementType()->isIntegerTy(1))
    370       return
    371         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
    372                                          PTy->getAddressSpace()),
    373                         DestTy, true);
    374 
    375   // If there's no interesting folding happening, bail so that we don't create
    376   // a constant that looks like it needs folding but really doesn't.
    377   if (!Folded)
    378     return 0;
    379 
    380   // Base case: Get a regular sizeof expression.
    381   Constant *C = ConstantExpr::getSizeOf(Ty);
    382   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    383                                                     DestTy, false),
    384                             C, DestTy);
    385   return C;
    386 }
    387 
    388 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
    389 /// on Ty, with any known factors factored out. If Folded is false,
    390 /// return null if no factoring was possible, to avoid endlessly
    391 /// bouncing an unfoldable expression back into the top-level folder.
    392 ///
    393 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
    394                                   bool Folded) {
    395   // The alignment of an array is equal to the alignment of the
    396   // array element. Note that this is not always true for vectors.
    397   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    398     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
    399     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    400                                                       DestTy,
    401                                                       false),
    402                               C, DestTy);
    403     return C;
    404   }
    405 
    406   if (StructType *STy = dyn_cast<StructType>(Ty)) {
    407     // Packed structs always have an alignment of 1.
    408     if (STy->isPacked())
    409       return ConstantInt::get(DestTy, 1);
    410 
    411     // Otherwise, struct alignment is the maximum alignment of any member.
    412     // Without target data, we can't compare much, but we can check to see
    413     // if all the members have the same alignment.
    414     unsigned NumElems = STy->getNumElements();
    415     // An empty struct has minimal alignment.
    416     if (NumElems == 0)
    417       return ConstantInt::get(DestTy, 1);
    418     // Check for a struct with all members having the same alignment.
    419     Constant *MemberAlign =
    420       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
    421     bool AllSame = true;
    422     for (unsigned i = 1; i != NumElems; ++i)
    423       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
    424         AllSame = false;
    425         break;
    426       }
    427     if (AllSame)
    428       return MemberAlign;
    429   }
    430 
    431   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
    432   // to an arbitrary pointee.
    433   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
    434     if (!PTy->getElementType()->isIntegerTy(1))
    435       return
    436         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
    437                                                            1),
    438                                           PTy->getAddressSpace()),
    439                          DestTy, true);
    440 
    441   // If there's no interesting folding happening, bail so that we don't create
    442   // a constant that looks like it needs folding but really doesn't.
    443   if (!Folded)
    444     return 0;
    445 
    446   // Base case: Get a regular alignof expression.
    447   Constant *C = ConstantExpr::getAlignOf(Ty);
    448   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    449                                                     DestTy, false),
    450                             C, DestTy);
    451   return C;
    452 }
    453 
    454 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
    455 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
    456 /// return null if no factoring was possible, to avoid endlessly
    457 /// bouncing an unfoldable expression back into the top-level folder.
    458 ///
    459 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
    460                                    Type *DestTy,
    461                                    bool Folded) {
    462   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    463     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
    464                                                                 DestTy, false),
    465                                         FieldNo, DestTy);
    466     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
    467     return ConstantExpr::getNUWMul(E, N);
    468   }
    469 
    470   if (StructType *STy = dyn_cast<StructType>(Ty))
    471     if (!STy->isPacked()) {
    472       unsigned NumElems = STy->getNumElements();
    473       // An empty struct has no members.
    474       if (NumElems == 0)
    475         return 0;
    476       // Check for a struct with all members having the same size.
    477       Constant *MemberSize =
    478         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
    479       bool AllSame = true;
    480       for (unsigned i = 1; i != NumElems; ++i)
    481         if (MemberSize !=
    482             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
    483           AllSame = false;
    484           break;
    485         }
    486       if (AllSame) {
    487         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
    488                                                                     false,
    489                                                                     DestTy,
    490                                                                     false),
    491                                             FieldNo, DestTy);
    492         return ConstantExpr::getNUWMul(MemberSize, N);
    493       }
    494     }
    495 
    496   // If there's no interesting folding happening, bail so that we don't create
    497   // a constant that looks like it needs folding but really doesn't.
    498   if (!Folded)
    499     return 0;
    500 
    501   // Base case: Get a regular offsetof expression.
    502   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
    503   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    504                                                     DestTy, false),
    505                             C, DestTy);
    506   return C;
    507 }
    508 
    509 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
    510                                             Type *DestTy) {
    511   if (isa<UndefValue>(V)) {
    512     // zext(undef) = 0, because the top bits will be zero.
    513     // sext(undef) = 0, because the top bits will all be the same.
    514     // [us]itofp(undef) = 0, because the result value is bounded.
    515     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
    516         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
    517       return Constant::getNullValue(DestTy);
    518     return UndefValue::get(DestTy);
    519   }
    520 
    521   if (V->isNullValue() && !DestTy->isX86_MMXTy())
    522     return Constant::getNullValue(DestTy);
    523 
    524   // If the cast operand is a constant expression, there's a few things we can
    525   // do to try to simplify it.
    526   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
    527     if (CE->isCast()) {
    528       // Try hard to fold cast of cast because they are often eliminable.
    529       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
    530         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
    531     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
    532       // If all of the indexes in the GEP are null values, there is no pointer
    533       // adjustment going on.  We might as well cast the source pointer.
    534       bool isAllNull = true;
    535       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
    536         if (!CE->getOperand(i)->isNullValue()) {
    537           isAllNull = false;
    538           break;
    539         }
    540       if (isAllNull)
    541         // This is casting one pointer type to another, always BitCast
    542         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
    543     }
    544   }
    545 
    546   // If the cast operand is a constant vector, perform the cast by
    547   // operating on each element. In the cast of bitcasts, the element
    548   // count may be mismatched; don't attempt to handle that here.
    549   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
    550       DestTy->isVectorTy() &&
    551       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
    552     SmallVector<Constant*, 16> res;
    553     VectorType *DestVecTy = cast<VectorType>(DestTy);
    554     Type *DstEltTy = DestVecTy->getElementType();
    555     Type *Ty = IntegerType::get(V->getContext(), 32);
    556     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
    557       Constant *C =
    558         ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
    559       res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
    560     }
    561     return ConstantVector::get(res);
    562   }
    563 
    564   // We actually have to do a cast now. Perform the cast according to the
    565   // opcode specified.
    566   switch (opc) {
    567   default:
    568     llvm_unreachable("Failed to cast constant expression");
    569   case Instruction::FPTrunc:
    570   case Instruction::FPExt:
    571     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
    572       bool ignored;
    573       APFloat Val = FPC->getValueAPF();
    574       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
    575                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
    576                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
    577                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
    578                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
    579                   DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
    580                   APFloat::Bogus,
    581                   APFloat::rmNearestTiesToEven, &ignored);
    582       return ConstantFP::get(V->getContext(), Val);
    583     }
    584     return 0; // Can't fold.
    585   case Instruction::FPToUI:
    586   case Instruction::FPToSI:
    587     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
    588       const APFloat &V = FPC->getValueAPF();
    589       bool ignored;
    590       uint64_t x[2];
    591       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    592       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
    593                                 APFloat::rmTowardZero, &ignored);
    594       APInt Val(DestBitWidth, x);
    595       return ConstantInt::get(FPC->getContext(), Val);
    596     }
    597     return 0; // Can't fold.
    598   case Instruction::IntToPtr:   //always treated as unsigned
    599     if (V->isNullValue())       // Is it an integral null value?
    600       return ConstantPointerNull::get(cast<PointerType>(DestTy));
    601     return 0;                   // Other pointer types cannot be casted
    602   case Instruction::PtrToInt:   // always treated as unsigned
    603     // Is it a null pointer value?
    604     if (V->isNullValue())
    605       return ConstantInt::get(DestTy, 0);
    606     // If this is a sizeof-like expression, pull out multiplications by
    607     // known factors to expose them to subsequent folding. If it's an
    608     // alignof-like expression, factor out known factors.
    609     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
    610       if (CE->getOpcode() == Instruction::GetElementPtr &&
    611           CE->getOperand(0)->isNullValue()) {
    612         Type *Ty =
    613           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
    614         if (CE->getNumOperands() == 2) {
    615           // Handle a sizeof-like expression.
    616           Constant *Idx = CE->getOperand(1);
    617           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
    618           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
    619             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
    620                                                                 DestTy, false),
    621                                         Idx, DestTy);
    622             return ConstantExpr::getMul(C, Idx);
    623           }
    624         } else if (CE->getNumOperands() == 3 &&
    625                    CE->getOperand(1)->isNullValue()) {
    626           // Handle an alignof-like expression.
    627           if (StructType *STy = dyn_cast<StructType>(Ty))
    628             if (!STy->isPacked()) {
    629               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
    630               if (CI->isOne() &&
    631                   STy->getNumElements() == 2 &&
    632                   STy->getElementType(0)->isIntegerTy(1)) {
    633                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
    634               }
    635             }
    636           // Handle an offsetof-like expression.
    637           if (Ty->isStructTy() || Ty->isArrayTy()) {
    638             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
    639                                                 DestTy, false))
    640               return C;
    641           }
    642         }
    643       }
    644     // Other pointer types cannot be casted
    645     return 0;
    646   case Instruction::UIToFP:
    647   case Instruction::SIToFP:
    648     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    649       APInt api = CI->getValue();
    650       APFloat apf(DestTy->getFltSemantics(),
    651                   APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
    652       (void)apf.convertFromAPInt(api,
    653                                  opc==Instruction::SIToFP,
    654                                  APFloat::rmNearestTiesToEven);
    655       return ConstantFP::get(V->getContext(), apf);
    656     }
    657     return 0;
    658   case Instruction::ZExt:
    659     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    660       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    661       return ConstantInt::get(V->getContext(),
    662                               CI->getValue().zext(BitWidth));
    663     }
    664     return 0;
    665   case Instruction::SExt:
    666     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    667       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    668       return ConstantInt::get(V->getContext(),
    669                               CI->getValue().sext(BitWidth));
    670     }
    671     return 0;
    672   case Instruction::Trunc: {
    673     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    674     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    675       return ConstantInt::get(V->getContext(),
    676                               CI->getValue().trunc(DestBitWidth));
    677     }
    678 
    679     // The input must be a constantexpr.  See if we can simplify this based on
    680     // the bytes we are demanding.  Only do this if the source and dest are an
    681     // even multiple of a byte.
    682     if ((DestBitWidth & 7) == 0 &&
    683         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
    684       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
    685         return Res;
    686 
    687     return 0;
    688   }
    689   case Instruction::BitCast:
    690     return FoldBitCast(V, DestTy);
    691   }
    692 }
    693 
    694 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
    695                                               Constant *V1, Constant *V2) {
    696   // Check for i1 and vector true/false conditions.
    697   if (Cond->isNullValue()) return V2;
    698   if (Cond->isAllOnesValue()) return V1;
    699 
    700   // If the condition is a vector constant, fold the result elementwise.
    701   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
    702     SmallVector<Constant*, 16> Result;
    703     Type *Ty = IntegerType::get(CondV->getContext(), 32);
    704     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
    705       ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
    706       if (Cond == 0) break;
    707 
    708       Constant *V = Cond->isNullValue() ? V2 : V1;
    709       Constant *Res = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
    710       Result.push_back(Res);
    711     }
    712 
    713     // If we were able to build the vector, return it.
    714     if (Result.size() == V1->getType()->getVectorNumElements())
    715       return ConstantVector::get(Result);
    716   }
    717 
    718   if (isa<UndefValue>(Cond)) {
    719     if (isa<UndefValue>(V1)) return V1;
    720     return V2;
    721   }
    722   if (isa<UndefValue>(V1)) return V2;
    723   if (isa<UndefValue>(V2)) return V1;
    724   if (V1 == V2) return V1;
    725 
    726   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
    727     if (TrueVal->getOpcode() == Instruction::Select)
    728       if (TrueVal->getOperand(0) == Cond)
    729         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
    730   }
    731   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
    732     if (FalseVal->getOpcode() == Instruction::Select)
    733       if (FalseVal->getOperand(0) == Cond)
    734         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
    735   }
    736 
    737   return 0;
    738 }
    739 
    740 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
    741                                                       Constant *Idx) {
    742   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
    743     return UndefValue::get(Val->getType()->getVectorElementType());
    744   if (Val->isNullValue())  // ee(zero, x) -> zero
    745     return Constant::getNullValue(Val->getType()->getVectorElementType());
    746   // ee({w,x,y,z}, undef) -> undef
    747   if (isa<UndefValue>(Idx))
    748     return UndefValue::get(Val->getType()->getVectorElementType());
    749 
    750   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
    751     uint64_t Index = CIdx->getZExtValue();
    752     // ee({w,x,y,z}, wrong_value) -> undef
    753     if (Index >= Val->getType()->getVectorNumElements())
    754       return UndefValue::get(Val->getType()->getVectorElementType());
    755     return Val->getAggregateElement(Index);
    756   }
    757   return 0;
    758 }
    759 
    760 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
    761                                                      Constant *Elt,
    762                                                      Constant *Idx) {
    763   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
    764   if (!CIdx) return 0;
    765   const APInt &IdxVal = CIdx->getValue();
    766 
    767   SmallVector<Constant*, 16> Result;
    768   Type *Ty = IntegerType::get(Val->getContext(), 32);
    769   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
    770     if (i == IdxVal) {
    771       Result.push_back(Elt);
    772       continue;
    773     }
    774 
    775     Constant *C =
    776       ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
    777     Result.push_back(C);
    778   }
    779 
    780   return ConstantVector::get(Result);
    781 }
    782 
    783 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
    784                                                      Constant *V2,
    785                                                      Constant *Mask) {
    786   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
    787   Type *EltTy = V1->getType()->getVectorElementType();
    788 
    789   // Undefined shuffle mask -> undefined value.
    790   if (isa<UndefValue>(Mask))
    791     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
    792 
    793   // Don't break the bitcode reader hack.
    794   if (isa<ConstantExpr>(Mask)) return 0;
    795 
    796   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
    797 
    798   // Loop over the shuffle mask, evaluating each element.
    799   SmallVector<Constant*, 32> Result;
    800   for (unsigned i = 0; i != MaskNumElts; ++i) {
    801     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
    802     if (Elt == -1) {
    803       Result.push_back(UndefValue::get(EltTy));
    804       continue;
    805     }
    806     Constant *InElt;
    807     if (unsigned(Elt) >= SrcNumElts*2)
    808       InElt = UndefValue::get(EltTy);
    809     else if (unsigned(Elt) >= SrcNumElts) {
    810       Type *Ty = IntegerType::get(V2->getContext(), 32);
    811       InElt =
    812         ConstantExpr::getExtractElement(V2,
    813                                         ConstantInt::get(Ty, Elt - SrcNumElts));
    814     } else {
    815       Type *Ty = IntegerType::get(V1->getContext(), 32);
    816       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
    817     }
    818     Result.push_back(InElt);
    819   }
    820 
    821   return ConstantVector::get(Result);
    822 }
    823 
    824 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
    825                                                     ArrayRef<unsigned> Idxs) {
    826   // Base case: no indices, so return the entire value.
    827   if (Idxs.empty())
    828     return Agg;
    829 
    830   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
    831     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
    832 
    833   return 0;
    834 }
    835 
    836 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
    837                                                    Constant *Val,
    838                                                    ArrayRef<unsigned> Idxs) {
    839   // Base case: no indices, so replace the entire value.
    840   if (Idxs.empty())
    841     return Val;
    842 
    843   unsigned NumElts;
    844   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
    845     NumElts = ST->getNumElements();
    846   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
    847     NumElts = AT->getNumElements();
    848   else
    849     NumElts = Agg->getType()->getVectorNumElements();
    850 
    851   SmallVector<Constant*, 32> Result;
    852   for (unsigned i = 0; i != NumElts; ++i) {
    853     Constant *C = Agg->getAggregateElement(i);
    854     if (C == 0) return 0;
    855 
    856     if (Idxs[0] == i)
    857       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
    858 
    859     Result.push_back(C);
    860   }
    861 
    862   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
    863     return ConstantStruct::get(ST, Result);
    864   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
    865     return ConstantArray::get(AT, Result);
    866   return ConstantVector::get(Result);
    867 }
    868 
    869 
    870 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
    871                                               Constant *C1, Constant *C2) {
    872   // Handle UndefValue up front.
    873   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
    874     switch (Opcode) {
    875     case Instruction::Xor:
    876       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
    877         // Handle undef ^ undef -> 0 special case. This is a common
    878         // idiom (misuse).
    879         return Constant::getNullValue(C1->getType());
    880       // Fallthrough
    881     case Instruction::Add:
    882     case Instruction::Sub:
    883       return UndefValue::get(C1->getType());
    884     case Instruction::And:
    885       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
    886         return C1;
    887       return Constant::getNullValue(C1->getType());   // undef & X -> 0
    888     case Instruction::Mul: {
    889       ConstantInt *CI;
    890       // X * undef -> undef   if X is odd or undef
    891       if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
    892           ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
    893           (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
    894         return UndefValue::get(C1->getType());
    895 
    896       // X * undef -> 0       otherwise
    897       return Constant::getNullValue(C1->getType());
    898     }
    899     case Instruction::UDiv:
    900     case Instruction::SDiv:
    901       // undef / 1 -> undef
    902       if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
    903         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
    904           if (CI2->isOne())
    905             return C1;
    906       // FALL THROUGH
    907     case Instruction::URem:
    908     case Instruction::SRem:
    909       if (!isa<UndefValue>(C2))                    // undef / X -> 0
    910         return Constant::getNullValue(C1->getType());
    911       return C2;                                   // X / undef -> undef
    912     case Instruction::Or:                          // X | undef -> -1
    913       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
    914         return C1;
    915       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
    916     case Instruction::LShr:
    917       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
    918         return C1;                                  // undef lshr undef -> undef
    919       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
    920                                                     // undef lshr X -> 0
    921     case Instruction::AShr:
    922       if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
    923         return Constant::getAllOnesValue(C1->getType());
    924       else if (isa<UndefValue>(C1))
    925         return C1;                                  // undef ashr undef -> undef
    926       else
    927         return C1;                                  // X ashr undef --> X
    928     case Instruction::Shl:
    929       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
    930         return C1;                                  // undef shl undef -> undef
    931       // undef << X -> 0   or   X << undef -> 0
    932       return Constant::getNullValue(C1->getType());
    933     }
    934   }
    935 
    936   // Handle simplifications when the RHS is a constant int.
    937   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
    938     switch (Opcode) {
    939     case Instruction::Add:
    940       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
    941       break;
    942     case Instruction::Sub:
    943       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
    944       break;
    945     case Instruction::Mul:
    946       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
    947       if (CI2->equalsInt(1))
    948         return C1;                                              // X * 1 == X
    949       break;
    950     case Instruction::UDiv:
    951     case Instruction::SDiv:
    952       if (CI2->equalsInt(1))
    953         return C1;                                            // X / 1 == X
    954       if (CI2->equalsInt(0))
    955         return UndefValue::get(CI2->getType());               // X / 0 == undef
    956       break;
    957     case Instruction::URem:
    958     case Instruction::SRem:
    959       if (CI2->equalsInt(1))
    960         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
    961       if (CI2->equalsInt(0))
    962         return UndefValue::get(CI2->getType());               // X % 0 == undef
    963       break;
    964     case Instruction::And:
    965       if (CI2->isZero()) return C2;                           // X & 0 == 0
    966       if (CI2->isAllOnesValue())
    967         return C1;                                            // X & -1 == X
    968 
    969       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
    970         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
    971         if (CE1->getOpcode() == Instruction::ZExt) {
    972           unsigned DstWidth = CI2->getType()->getBitWidth();
    973           unsigned SrcWidth =
    974             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
    975           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
    976           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
    977             return C1;
    978         }
    979 
    980         // If and'ing the address of a global with a constant, fold it.
    981         if (CE1->getOpcode() == Instruction::PtrToInt &&
    982             isa<GlobalValue>(CE1->getOperand(0))) {
    983           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
    984 
    985           // Functions are at least 4-byte aligned.
    986           unsigned GVAlign = GV->getAlignment();
    987           if (isa<Function>(GV))
    988             GVAlign = std::max(GVAlign, 4U);
    989 
    990           if (GVAlign > 1) {
    991             unsigned DstWidth = CI2->getType()->getBitWidth();
    992             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
    993             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
    994 
    995             // If checking bits we know are clear, return zero.
    996             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
    997               return Constant::getNullValue(CI2->getType());
    998           }
    999         }
   1000       }
   1001       break;
   1002     case Instruction::Or:
   1003       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
   1004       if (CI2->isAllOnesValue())
   1005         return C2;                         // X | -1 == -1
   1006       break;
   1007     case Instruction::Xor:
   1008       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
   1009 
   1010       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
   1011         switch (CE1->getOpcode()) {
   1012         default: break;
   1013         case Instruction::ICmp:
   1014         case Instruction::FCmp:
   1015           // cmp pred ^ true -> cmp !pred
   1016           assert(CI2->equalsInt(1));
   1017           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
   1018           pred = CmpInst::getInversePredicate(pred);
   1019           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
   1020                                           CE1->getOperand(1));
   1021         }
   1022       }
   1023       break;
   1024     case Instruction::AShr:
   1025       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
   1026       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
   1027         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
   1028           return ConstantExpr::getLShr(C1, C2);
   1029       break;
   1030     }
   1031   } else if (isa<ConstantInt>(C1)) {
   1032     // If C1 is a ConstantInt and C2 is not, swap the operands.
   1033     if (Instruction::isCommutative(Opcode))
   1034       return ConstantExpr::get(Opcode, C2, C1);
   1035   }
   1036 
   1037   // At this point we know neither constant is an UndefValue.
   1038   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
   1039     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
   1040       const APInt &C1V = CI1->getValue();
   1041       const APInt &C2V = CI2->getValue();
   1042       switch (Opcode) {
   1043       default:
   1044         break;
   1045       case Instruction::Add:
   1046         return ConstantInt::get(CI1->getContext(), C1V + C2V);
   1047       case Instruction::Sub:
   1048         return ConstantInt::get(CI1->getContext(), C1V - C2V);
   1049       case Instruction::Mul:
   1050         return ConstantInt::get(CI1->getContext(), C1V * C2V);
   1051       case Instruction::UDiv:
   1052         assert(!CI2->isNullValue() && "Div by zero handled above");
   1053         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
   1054       case Instruction::SDiv:
   1055         assert(!CI2->isNullValue() && "Div by zero handled above");
   1056         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
   1057           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
   1058         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
   1059       case Instruction::URem:
   1060         assert(!CI2->isNullValue() && "Div by zero handled above");
   1061         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
   1062       case Instruction::SRem:
   1063         assert(!CI2->isNullValue() && "Div by zero handled above");
   1064         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
   1065           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
   1066         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
   1067       case Instruction::And:
   1068         return ConstantInt::get(CI1->getContext(), C1V & C2V);
   1069       case Instruction::Or:
   1070         return ConstantInt::get(CI1->getContext(), C1V | C2V);
   1071       case Instruction::Xor:
   1072         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
   1073       case Instruction::Shl: {
   1074         uint32_t shiftAmt = C2V.getZExtValue();
   1075         if (shiftAmt < C1V.getBitWidth())
   1076           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
   1077         else
   1078           return UndefValue::get(C1->getType()); // too big shift is undef
   1079       }
   1080       case Instruction::LShr: {
   1081         uint32_t shiftAmt = C2V.getZExtValue();
   1082         if (shiftAmt < C1V.getBitWidth())
   1083           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
   1084         else
   1085           return UndefValue::get(C1->getType()); // too big shift is undef
   1086       }
   1087       case Instruction::AShr: {
   1088         uint32_t shiftAmt = C2V.getZExtValue();
   1089         if (shiftAmt < C1V.getBitWidth())
   1090           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
   1091         else
   1092           return UndefValue::get(C1->getType()); // too big shift is undef
   1093       }
   1094       }
   1095     }
   1096 
   1097     switch (Opcode) {
   1098     case Instruction::SDiv:
   1099     case Instruction::UDiv:
   1100     case Instruction::URem:
   1101     case Instruction::SRem:
   1102     case Instruction::LShr:
   1103     case Instruction::AShr:
   1104     case Instruction::Shl:
   1105       if (CI1->equalsInt(0)) return C1;
   1106       break;
   1107     default:
   1108       break;
   1109     }
   1110   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
   1111     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
   1112       APFloat C1V = CFP1->getValueAPF();
   1113       APFloat C2V = CFP2->getValueAPF();
   1114       APFloat C3V = C1V;  // copy for modification
   1115       switch (Opcode) {
   1116       default:
   1117         break;
   1118       case Instruction::FAdd:
   1119         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
   1120         return ConstantFP::get(C1->getContext(), C3V);
   1121       case Instruction::FSub:
   1122         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
   1123         return ConstantFP::get(C1->getContext(), C3V);
   1124       case Instruction::FMul:
   1125         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
   1126         return ConstantFP::get(C1->getContext(), C3V);
   1127       case Instruction::FDiv:
   1128         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
   1129         return ConstantFP::get(C1->getContext(), C3V);
   1130       case Instruction::FRem:
   1131         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
   1132         return ConstantFP::get(C1->getContext(), C3V);
   1133       }
   1134     }
   1135   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
   1136     // Perform elementwise folding.
   1137     SmallVector<Constant*, 16> Result;
   1138     Type *Ty = IntegerType::get(VTy->getContext(), 32);
   1139     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
   1140       Constant *LHS =
   1141         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
   1142       Constant *RHS =
   1143         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
   1144 
   1145       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
   1146     }
   1147 
   1148     return ConstantVector::get(Result);
   1149   }
   1150 
   1151   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
   1152     // There are many possible foldings we could do here.  We should probably
   1153     // at least fold add of a pointer with an integer into the appropriate
   1154     // getelementptr.  This will improve alias analysis a bit.
   1155 
   1156     // Given ((a + b) + c), if (b + c) folds to something interesting, return
   1157     // (a + (b + c)).
   1158     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
   1159       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
   1160       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
   1161         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
   1162     }
   1163   } else if (isa<ConstantExpr>(C2)) {
   1164     // If C2 is a constant expr and C1 isn't, flop them around and fold the
   1165     // other way if possible.
   1166     if (Instruction::isCommutative(Opcode))
   1167       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
   1168   }
   1169 
   1170   // i1 can be simplified in many cases.
   1171   if (C1->getType()->isIntegerTy(1)) {
   1172     switch (Opcode) {
   1173     case Instruction::Add:
   1174     case Instruction::Sub:
   1175       return ConstantExpr::getXor(C1, C2);
   1176     case Instruction::Mul:
   1177       return ConstantExpr::getAnd(C1, C2);
   1178     case Instruction::Shl:
   1179     case Instruction::LShr:
   1180     case Instruction::AShr:
   1181       // We can assume that C2 == 0.  If it were one the result would be
   1182       // undefined because the shift value is as large as the bitwidth.
   1183       return C1;
   1184     case Instruction::SDiv:
   1185     case Instruction::UDiv:
   1186       // We can assume that C2 == 1.  If it were zero the result would be
   1187       // undefined through division by zero.
   1188       return C1;
   1189     case Instruction::URem:
   1190     case Instruction::SRem:
   1191       // We can assume that C2 == 1.  If it were zero the result would be
   1192       // undefined through division by zero.
   1193       return ConstantInt::getFalse(C1->getContext());
   1194     default:
   1195       break;
   1196     }
   1197   }
   1198 
   1199   // We don't know how to fold this.
   1200   return 0;
   1201 }
   1202 
   1203 /// isZeroSizedType - This type is zero sized if its an array or structure of
   1204 /// zero sized types.  The only leaf zero sized type is an empty structure.
   1205 static bool isMaybeZeroSizedType(Type *Ty) {
   1206   if (StructType *STy = dyn_cast<StructType>(Ty)) {
   1207     if (STy->isOpaque()) return true;  // Can't say.
   1208 
   1209     // If all of elements have zero size, this does too.
   1210     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
   1211       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
   1212     return true;
   1213 
   1214   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
   1215     return isMaybeZeroSizedType(ATy->getElementType());
   1216   }
   1217   return false;
   1218 }
   1219 
   1220 /// IdxCompare - Compare the two constants as though they were getelementptr
   1221 /// indices.  This allows coersion of the types to be the same thing.
   1222 ///
   1223 /// If the two constants are the "same" (after coersion), return 0.  If the
   1224 /// first is less than the second, return -1, if the second is less than the
   1225 /// first, return 1.  If the constants are not integral, return -2.
   1226 ///
   1227 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
   1228   if (C1 == C2) return 0;
   1229 
   1230   // Ok, we found a different index.  If they are not ConstantInt, we can't do
   1231   // anything with them.
   1232   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
   1233     return -2; // don't know!
   1234 
   1235   // Ok, we have two differing integer indices.  Sign extend them to be the same
   1236   // type.  Long is always big enough, so we use it.
   1237   if (!C1->getType()->isIntegerTy(64))
   1238     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
   1239 
   1240   if (!C2->getType()->isIntegerTy(64))
   1241     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
   1242 
   1243   if (C1 == C2) return 0;  // They are equal
   1244 
   1245   // If the type being indexed over is really just a zero sized type, there is
   1246   // no pointer difference being made here.
   1247   if (isMaybeZeroSizedType(ElTy))
   1248     return -2; // dunno.
   1249 
   1250   // If they are really different, now that they are the same type, then we
   1251   // found a difference!
   1252   if (cast<ConstantInt>(C1)->getSExtValue() <
   1253       cast<ConstantInt>(C2)->getSExtValue())
   1254     return -1;
   1255   else
   1256     return 1;
   1257 }
   1258 
   1259 /// evaluateFCmpRelation - This function determines if there is anything we can
   1260 /// decide about the two constants provided.  This doesn't need to handle simple
   1261 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
   1262 /// If we can determine that the two constants have a particular relation to
   1263 /// each other, we should return the corresponding FCmpInst predicate,
   1264 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
   1265 /// ConstantFoldCompareInstruction.
   1266 ///
   1267 /// To simplify this code we canonicalize the relation so that the first
   1268 /// operand is always the most "complex" of the two.  We consider ConstantFP
   1269 /// to be the simplest, and ConstantExprs to be the most complex.
   1270 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
   1271   assert(V1->getType() == V2->getType() &&
   1272          "Cannot compare values of different types!");
   1273 
   1274   // Handle degenerate case quickly
   1275   if (V1 == V2) return FCmpInst::FCMP_OEQ;
   1276 
   1277   if (!isa<ConstantExpr>(V1)) {
   1278     if (!isa<ConstantExpr>(V2)) {
   1279       // We distilled thisUse the standard constant folder for a few cases
   1280       ConstantInt *R = 0;
   1281       R = dyn_cast<ConstantInt>(
   1282                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
   1283       if (R && !R->isZero())
   1284         return FCmpInst::FCMP_OEQ;
   1285       R = dyn_cast<ConstantInt>(
   1286                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
   1287       if (R && !R->isZero())
   1288         return FCmpInst::FCMP_OLT;
   1289       R = dyn_cast<ConstantInt>(
   1290                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
   1291       if (R && !R->isZero())
   1292         return FCmpInst::FCMP_OGT;
   1293 
   1294       // Nothing more we can do
   1295       return FCmpInst::BAD_FCMP_PREDICATE;
   1296     }
   1297 
   1298     // If the first operand is simple and second is ConstantExpr, swap operands.
   1299     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
   1300     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
   1301       return FCmpInst::getSwappedPredicate(SwappedRelation);
   1302   } else {
   1303     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
   1304     // constantexpr or a simple constant.
   1305     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
   1306     switch (CE1->getOpcode()) {
   1307     case Instruction::FPTrunc:
   1308     case Instruction::FPExt:
   1309     case Instruction::UIToFP:
   1310     case Instruction::SIToFP:
   1311       // We might be able to do something with these but we don't right now.
   1312       break;
   1313     default:
   1314       break;
   1315     }
   1316   }
   1317   // There are MANY other foldings that we could perform here.  They will
   1318   // probably be added on demand, as they seem needed.
   1319   return FCmpInst::BAD_FCMP_PREDICATE;
   1320 }
   1321 
   1322 /// evaluateICmpRelation - This function determines if there is anything we can
   1323 /// decide about the two constants provided.  This doesn't need to handle simple
   1324 /// things like integer comparisons, but should instead handle ConstantExprs
   1325 /// and GlobalValues.  If we can determine that the two constants have a
   1326 /// particular relation to each other, we should return the corresponding ICmp
   1327 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
   1328 ///
   1329 /// To simplify this code we canonicalize the relation so that the first
   1330 /// operand is always the most "complex" of the two.  We consider simple
   1331 /// constants (like ConstantInt) to be the simplest, followed by
   1332 /// GlobalValues, followed by ConstantExpr's (the most complex).
   1333 ///
   1334 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
   1335                                                 bool isSigned) {
   1336   assert(V1->getType() == V2->getType() &&
   1337          "Cannot compare different types of values!");
   1338   if (V1 == V2) return ICmpInst::ICMP_EQ;
   1339 
   1340   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
   1341       !isa<BlockAddress>(V1)) {
   1342     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
   1343         !isa<BlockAddress>(V2)) {
   1344       // We distilled this down to a simple case, use the standard constant
   1345       // folder.
   1346       ConstantInt *R = 0;
   1347       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
   1348       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
   1349       if (R && !R->isZero())
   1350         return pred;
   1351       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
   1352       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
   1353       if (R && !R->isZero())
   1354         return pred;
   1355       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1356       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
   1357       if (R && !R->isZero())
   1358         return pred;
   1359 
   1360       // If we couldn't figure it out, bail.
   1361       return ICmpInst::BAD_ICMP_PREDICATE;
   1362     }
   1363 
   1364     // If the first operand is simple, swap operands.
   1365     ICmpInst::Predicate SwappedRelation =
   1366       evaluateICmpRelation(V2, V1, isSigned);
   1367     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
   1368       return ICmpInst::getSwappedPredicate(SwappedRelation);
   1369 
   1370   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
   1371     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
   1372       ICmpInst::Predicate SwappedRelation =
   1373         evaluateICmpRelation(V2, V1, isSigned);
   1374       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
   1375         return ICmpInst::getSwappedPredicate(SwappedRelation);
   1376       return ICmpInst::BAD_ICMP_PREDICATE;
   1377     }
   1378 
   1379     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
   1380     // constant (which, since the types must match, means that it's a
   1381     // ConstantPointerNull).
   1382     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
   1383       // Don't try to decide equality of aliases.
   1384       if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
   1385         if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
   1386           return ICmpInst::ICMP_NE;
   1387     } else if (isa<BlockAddress>(V2)) {
   1388       return ICmpInst::ICMP_NE; // Globals never equal labels.
   1389     } else {
   1390       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
   1391       // GlobalVals can never be null unless they have external weak linkage.
   1392       // We don't try to evaluate aliases here.
   1393       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
   1394         return ICmpInst::ICMP_NE;
   1395     }
   1396   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
   1397     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
   1398       ICmpInst::Predicate SwappedRelation =
   1399         evaluateICmpRelation(V2, V1, isSigned);
   1400       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
   1401         return ICmpInst::getSwappedPredicate(SwappedRelation);
   1402       return ICmpInst::BAD_ICMP_PREDICATE;
   1403     }
   1404 
   1405     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
   1406     // constant (which, since the types must match, means that it is a
   1407     // ConstantPointerNull).
   1408     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
   1409       // Block address in another function can't equal this one, but block
   1410       // addresses in the current function might be the same if blocks are
   1411       // empty.
   1412       if (BA2->getFunction() != BA->getFunction())
   1413         return ICmpInst::ICMP_NE;
   1414     } else {
   1415       // Block addresses aren't null, don't equal the address of globals.
   1416       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
   1417              "Canonicalization guarantee!");
   1418       return ICmpInst::ICMP_NE;
   1419     }
   1420   } else {
   1421     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
   1422     // constantexpr, a global, block address, or a simple constant.
   1423     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
   1424     Constant *CE1Op0 = CE1->getOperand(0);
   1425 
   1426     switch (CE1->getOpcode()) {
   1427     case Instruction::Trunc:
   1428     case Instruction::FPTrunc:
   1429     case Instruction::FPExt:
   1430     case Instruction::FPToUI:
   1431     case Instruction::FPToSI:
   1432       break; // We can't evaluate floating point casts or truncations.
   1433 
   1434     case Instruction::UIToFP:
   1435     case Instruction::SIToFP:
   1436     case Instruction::BitCast:
   1437     case Instruction::ZExt:
   1438     case Instruction::SExt:
   1439       // If the cast is not actually changing bits, and the second operand is a
   1440       // null pointer, do the comparison with the pre-casted value.
   1441       if (V2->isNullValue() &&
   1442           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
   1443         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
   1444         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
   1445         return evaluateICmpRelation(CE1Op0,
   1446                                     Constant::getNullValue(CE1Op0->getType()),
   1447                                     isSigned);
   1448       }
   1449       break;
   1450 
   1451     case Instruction::GetElementPtr:
   1452       // Ok, since this is a getelementptr, we know that the constant has a
   1453       // pointer type.  Check the various cases.
   1454       if (isa<ConstantPointerNull>(V2)) {
   1455         // If we are comparing a GEP to a null pointer, check to see if the base
   1456         // of the GEP equals the null pointer.
   1457         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
   1458           if (GV->hasExternalWeakLinkage())
   1459             // Weak linkage GVals could be zero or not. We're comparing that
   1460             // to null pointer so its greater-or-equal
   1461             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
   1462           else
   1463             // If its not weak linkage, the GVal must have a non-zero address
   1464             // so the result is greater-than
   1465             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1466         } else if (isa<ConstantPointerNull>(CE1Op0)) {
   1467           // If we are indexing from a null pointer, check to see if we have any
   1468           // non-zero indices.
   1469           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
   1470             if (!CE1->getOperand(i)->isNullValue())
   1471               // Offsetting from null, must not be equal.
   1472               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1473           // Only zero indexes from null, must still be zero.
   1474           return ICmpInst::ICMP_EQ;
   1475         }
   1476         // Otherwise, we can't really say if the first operand is null or not.
   1477       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
   1478         if (isa<ConstantPointerNull>(CE1Op0)) {
   1479           if (GV2->hasExternalWeakLinkage())
   1480             // Weak linkage GVals could be zero or not. We're comparing it to
   1481             // a null pointer, so its less-or-equal
   1482             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
   1483           else
   1484             // If its not weak linkage, the GVal must have a non-zero address
   1485             // so the result is less-than
   1486             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
   1487         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
   1488           if (GV == GV2) {
   1489             // If this is a getelementptr of the same global, then it must be
   1490             // different.  Because the types must match, the getelementptr could
   1491             // only have at most one index, and because we fold getelementptr's
   1492             // with a single zero index, it must be nonzero.
   1493             assert(CE1->getNumOperands() == 2 &&
   1494                    !CE1->getOperand(1)->isNullValue() &&
   1495                    "Surprising getelementptr!");
   1496             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1497           } else {
   1498             // If they are different globals, we don't know what the value is.
   1499             return ICmpInst::BAD_ICMP_PREDICATE;
   1500           }
   1501         }
   1502       } else {
   1503         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
   1504         Constant *CE2Op0 = CE2->getOperand(0);
   1505 
   1506         // There are MANY other foldings that we could perform here.  They will
   1507         // probably be added on demand, as they seem needed.
   1508         switch (CE2->getOpcode()) {
   1509         default: break;
   1510         case Instruction::GetElementPtr:
   1511           // By far the most common case to handle is when the base pointers are
   1512           // obviously to the same global.
   1513           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
   1514             if (CE1Op0 != CE2Op0) // Don't know relative ordering.
   1515               return ICmpInst::BAD_ICMP_PREDICATE;
   1516             // Ok, we know that both getelementptr instructions are based on the
   1517             // same global.  From this, we can precisely determine the relative
   1518             // ordering of the resultant pointers.
   1519             unsigned i = 1;
   1520 
   1521             // The logic below assumes that the result of the comparison
   1522             // can be determined by finding the first index that differs.
   1523             // This doesn't work if there is over-indexing in any
   1524             // subsequent indices, so check for that case first.
   1525             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
   1526                 !CE2->isGEPWithNoNotionalOverIndexing())
   1527                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
   1528 
   1529             // Compare all of the operands the GEP's have in common.
   1530             gep_type_iterator GTI = gep_type_begin(CE1);
   1531             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
   1532                  ++i, ++GTI)
   1533               switch (IdxCompare(CE1->getOperand(i),
   1534                                  CE2->getOperand(i), GTI.getIndexedType())) {
   1535               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
   1536               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
   1537               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
   1538               }
   1539 
   1540             // Ok, we ran out of things they have in common.  If any leftovers
   1541             // are non-zero then we have a difference, otherwise we are equal.
   1542             for (; i < CE1->getNumOperands(); ++i)
   1543               if (!CE1->getOperand(i)->isNullValue()) {
   1544                 if (isa<ConstantInt>(CE1->getOperand(i)))
   1545                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1546                 else
   1547                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
   1548               }
   1549 
   1550             for (; i < CE2->getNumOperands(); ++i)
   1551               if (!CE2->getOperand(i)->isNullValue()) {
   1552                 if (isa<ConstantInt>(CE2->getOperand(i)))
   1553                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
   1554                 else
   1555                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
   1556               }
   1557             return ICmpInst::ICMP_EQ;
   1558           }
   1559         }
   1560       }
   1561     default:
   1562       break;
   1563     }
   1564   }
   1565 
   1566   return ICmpInst::BAD_ICMP_PREDICATE;
   1567 }
   1568 
   1569 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
   1570                                                Constant *C1, Constant *C2) {
   1571   Type *ResultTy;
   1572   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
   1573     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
   1574                                VT->getNumElements());
   1575   else
   1576     ResultTy = Type::getInt1Ty(C1->getContext());
   1577 
   1578   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
   1579   if (pred == FCmpInst::FCMP_FALSE)
   1580     return Constant::getNullValue(ResultTy);
   1581 
   1582   if (pred == FCmpInst::FCMP_TRUE)
   1583     return Constant::getAllOnesValue(ResultTy);
   1584 
   1585   // Handle some degenerate cases first
   1586   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
   1587     // For EQ and NE, we can always pick a value for the undef to make the
   1588     // predicate pass or fail, so we can return undef.
   1589     // Also, if both operands are undef, we can return undef.
   1590     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
   1591         (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
   1592       return UndefValue::get(ResultTy);
   1593     // Otherwise, pick the same value as the non-undef operand, and fold
   1594     // it to true or false.
   1595     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
   1596   }
   1597 
   1598   // icmp eq/ne(null,GV) -> false/true
   1599   if (C1->isNullValue()) {
   1600     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
   1601       // Don't try to evaluate aliases.  External weak GV can be null.
   1602       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
   1603         if (pred == ICmpInst::ICMP_EQ)
   1604           return ConstantInt::getFalse(C1->getContext());
   1605         else if (pred == ICmpInst::ICMP_NE)
   1606           return ConstantInt::getTrue(C1->getContext());
   1607       }
   1608   // icmp eq/ne(GV,null) -> false/true
   1609   } else if (C2->isNullValue()) {
   1610     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
   1611       // Don't try to evaluate aliases.  External weak GV can be null.
   1612       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
   1613         if (pred == ICmpInst::ICMP_EQ)
   1614           return ConstantInt::getFalse(C1->getContext());
   1615         else if (pred == ICmpInst::ICMP_NE)
   1616           return ConstantInt::getTrue(C1->getContext());
   1617       }
   1618   }
   1619 
   1620   // If the comparison is a comparison between two i1's, simplify it.
   1621   if (C1->getType()->isIntegerTy(1)) {
   1622     switch(pred) {
   1623     case ICmpInst::ICMP_EQ:
   1624       if (isa<ConstantInt>(C2))
   1625         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
   1626       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
   1627     case ICmpInst::ICMP_NE:
   1628       return ConstantExpr::getXor(C1, C2);
   1629     default:
   1630       break;
   1631     }
   1632   }
   1633 
   1634   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
   1635     APInt V1 = cast<ConstantInt>(C1)->getValue();
   1636     APInt V2 = cast<ConstantInt>(C2)->getValue();
   1637     switch (pred) {
   1638     default: llvm_unreachable("Invalid ICmp Predicate");
   1639     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
   1640     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
   1641     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
   1642     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
   1643     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
   1644     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
   1645     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
   1646     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
   1647     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
   1648     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
   1649     }
   1650   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
   1651     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
   1652     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
   1653     APFloat::cmpResult R = C1V.compare(C2V);
   1654     switch (pred) {
   1655     default: llvm_unreachable("Invalid FCmp Predicate");
   1656     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
   1657     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
   1658     case FCmpInst::FCMP_UNO:
   1659       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
   1660     case FCmpInst::FCMP_ORD:
   1661       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
   1662     case FCmpInst::FCMP_UEQ:
   1663       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
   1664                                         R==APFloat::cmpEqual);
   1665     case FCmpInst::FCMP_OEQ:
   1666       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
   1667     case FCmpInst::FCMP_UNE:
   1668       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
   1669     case FCmpInst::FCMP_ONE:
   1670       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
   1671                                         R==APFloat::cmpGreaterThan);
   1672     case FCmpInst::FCMP_ULT:
   1673       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
   1674                                         R==APFloat::cmpLessThan);
   1675     case FCmpInst::FCMP_OLT:
   1676       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
   1677     case FCmpInst::FCMP_UGT:
   1678       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
   1679                                         R==APFloat::cmpGreaterThan);
   1680     case FCmpInst::FCMP_OGT:
   1681       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
   1682     case FCmpInst::FCMP_ULE:
   1683       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
   1684     case FCmpInst::FCMP_OLE:
   1685       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
   1686                                         R==APFloat::cmpEqual);
   1687     case FCmpInst::FCMP_UGE:
   1688       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
   1689     case FCmpInst::FCMP_OGE:
   1690       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
   1691                                         R==APFloat::cmpEqual);
   1692     }
   1693   } else if (C1->getType()->isVectorTy()) {
   1694     // If we can constant fold the comparison of each element, constant fold
   1695     // the whole vector comparison.
   1696     SmallVector<Constant*, 4> ResElts;
   1697     Type *Ty = IntegerType::get(C1->getContext(), 32);
   1698     // Compare the elements, producing an i1 result or constant expr.
   1699     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
   1700       Constant *C1E =
   1701         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
   1702       Constant *C2E =
   1703         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
   1704 
   1705       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
   1706     }
   1707 
   1708     return ConstantVector::get(ResElts);
   1709   }
   1710 
   1711   if (C1->getType()->isFloatingPointTy()) {
   1712     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
   1713     switch (evaluateFCmpRelation(C1, C2)) {
   1714     default: llvm_unreachable("Unknown relation!");
   1715     case FCmpInst::FCMP_UNO:
   1716     case FCmpInst::FCMP_ORD:
   1717     case FCmpInst::FCMP_UEQ:
   1718     case FCmpInst::FCMP_UNE:
   1719     case FCmpInst::FCMP_ULT:
   1720     case FCmpInst::FCMP_UGT:
   1721     case FCmpInst::FCMP_ULE:
   1722     case FCmpInst::FCMP_UGE:
   1723     case FCmpInst::FCMP_TRUE:
   1724     case FCmpInst::FCMP_FALSE:
   1725     case FCmpInst::BAD_FCMP_PREDICATE:
   1726       break; // Couldn't determine anything about these constants.
   1727     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
   1728       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
   1729                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
   1730                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
   1731       break;
   1732     case FCmpInst::FCMP_OLT: // We know that C1 < C2
   1733       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
   1734                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
   1735                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
   1736       break;
   1737     case FCmpInst::FCMP_OGT: // We know that C1 > C2
   1738       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
   1739                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
   1740                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
   1741       break;
   1742     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
   1743       // We can only partially decide this relation.
   1744       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
   1745         Result = 0;
   1746       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
   1747         Result = 1;
   1748       break;
   1749     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
   1750       // We can only partially decide this relation.
   1751       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
   1752         Result = 0;
   1753       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
   1754         Result = 1;
   1755       break;
   1756     case FCmpInst::FCMP_ONE: // We know that C1 != C2
   1757       // We can only partially decide this relation.
   1758       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
   1759         Result = 0;
   1760       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
   1761         Result = 1;
   1762       break;
   1763     }
   1764 
   1765     // If we evaluated the result, return it now.
   1766     if (Result != -1)
   1767       return ConstantInt::get(ResultTy, Result);
   1768 
   1769   } else {
   1770     // Evaluate the relation between the two constants, per the predicate.
   1771     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
   1772     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
   1773     default: llvm_unreachable("Unknown relational!");
   1774     case ICmpInst::BAD_ICMP_PREDICATE:
   1775       break;  // Couldn't determine anything about these constants.
   1776     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
   1777       // If we know the constants are equal, we can decide the result of this
   1778       // computation precisely.
   1779       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
   1780       break;
   1781     case ICmpInst::ICMP_ULT:
   1782       switch (pred) {
   1783       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
   1784         Result = 1; break;
   1785       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
   1786         Result = 0; break;
   1787       }
   1788       break;
   1789     case ICmpInst::ICMP_SLT:
   1790       switch (pred) {
   1791       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
   1792         Result = 1; break;
   1793       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
   1794         Result = 0; break;
   1795       }
   1796       break;
   1797     case ICmpInst::ICMP_UGT:
   1798       switch (pred) {
   1799       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
   1800         Result = 1; break;
   1801       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
   1802         Result = 0; break;
   1803       }
   1804       break;
   1805     case ICmpInst::ICMP_SGT:
   1806       switch (pred) {
   1807       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
   1808         Result = 1; break;
   1809       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
   1810         Result = 0; break;
   1811       }
   1812       break;
   1813     case ICmpInst::ICMP_ULE:
   1814       if (pred == ICmpInst::ICMP_UGT) Result = 0;
   1815       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
   1816       break;
   1817     case ICmpInst::ICMP_SLE:
   1818       if (pred == ICmpInst::ICMP_SGT) Result = 0;
   1819       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
   1820       break;
   1821     case ICmpInst::ICMP_UGE:
   1822       if (pred == ICmpInst::ICMP_ULT) Result = 0;
   1823       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
   1824       break;
   1825     case ICmpInst::ICMP_SGE:
   1826       if (pred == ICmpInst::ICMP_SLT) Result = 0;
   1827       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
   1828       break;
   1829     case ICmpInst::ICMP_NE:
   1830       if (pred == ICmpInst::ICMP_EQ) Result = 0;
   1831       if (pred == ICmpInst::ICMP_NE) Result = 1;
   1832       break;
   1833     }
   1834 
   1835     // If we evaluated the result, return it now.
   1836     if (Result != -1)
   1837       return ConstantInt::get(ResultTy, Result);
   1838 
   1839     // If the right hand side is a bitcast, try using its inverse to simplify
   1840     // it by moving it to the left hand side.  We can't do this if it would turn
   1841     // a vector compare into a scalar compare or visa versa.
   1842     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
   1843       Constant *CE2Op0 = CE2->getOperand(0);
   1844       if (CE2->getOpcode() == Instruction::BitCast &&
   1845           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
   1846         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
   1847         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
   1848       }
   1849     }
   1850 
   1851     // If the left hand side is an extension, try eliminating it.
   1852     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
   1853       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
   1854           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
   1855         Constant *CE1Op0 = CE1->getOperand(0);
   1856         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
   1857         if (CE1Inverse == CE1Op0) {
   1858           // Check whether we can safely truncate the right hand side.
   1859           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
   1860           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
   1861             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
   1862           }
   1863         }
   1864       }
   1865     }
   1866 
   1867     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
   1868         (C1->isNullValue() && !C2->isNullValue())) {
   1869       // If C2 is a constant expr and C1 isn't, flip them around and fold the
   1870       // other way if possible.
   1871       // Also, if C1 is null and C2 isn't, flip them around.
   1872       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
   1873       return ConstantExpr::getICmp(pred, C2, C1);
   1874     }
   1875   }
   1876   return 0;
   1877 }
   1878 
   1879 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
   1880 /// is "inbounds".
   1881 template<typename IndexTy>
   1882 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
   1883   // No indices means nothing that could be out of bounds.
   1884   if (Idxs.empty()) return true;
   1885 
   1886   // If the first index is zero, it's in bounds.
   1887   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
   1888 
   1889   // If the first index is one and all the rest are zero, it's in bounds,
   1890   // by the one-past-the-end rule.
   1891   if (!cast<ConstantInt>(Idxs[0])->isOne())
   1892     return false;
   1893   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
   1894     if (!cast<Constant>(Idxs[i])->isNullValue())
   1895       return false;
   1896   return true;
   1897 }
   1898 
   1899 template<typename IndexTy>
   1900 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
   1901                                                bool inBounds,
   1902                                                ArrayRef<IndexTy> Idxs) {
   1903   if (Idxs.empty()) return C;
   1904   Constant *Idx0 = cast<Constant>(Idxs[0]);
   1905   if ((Idxs.size() == 1 && Idx0->isNullValue()))
   1906     return C;
   1907 
   1908   if (isa<UndefValue>(C)) {
   1909     PointerType *Ptr = cast<PointerType>(C->getType());
   1910     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
   1911     assert(Ty != 0 && "Invalid indices for GEP!");
   1912     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
   1913   }
   1914 
   1915   if (C->isNullValue()) {
   1916     bool isNull = true;
   1917     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
   1918       if (!cast<Constant>(Idxs[i])->isNullValue()) {
   1919         isNull = false;
   1920         break;
   1921       }
   1922     if (isNull) {
   1923       PointerType *Ptr = cast<PointerType>(C->getType());
   1924       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
   1925       assert(Ty != 0 && "Invalid indices for GEP!");
   1926       return ConstantPointerNull::get(PointerType::get(Ty,
   1927                                                        Ptr->getAddressSpace()));
   1928     }
   1929   }
   1930 
   1931   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
   1932     // Combine Indices - If the source pointer to this getelementptr instruction
   1933     // is a getelementptr instruction, combine the indices of the two
   1934     // getelementptr instructions into a single instruction.
   1935     //
   1936     if (CE->getOpcode() == Instruction::GetElementPtr) {
   1937       Type *LastTy = 0;
   1938       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
   1939            I != E; ++I)
   1940         LastTy = *I;
   1941 
   1942       if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
   1943         SmallVector<Value*, 16> NewIndices;
   1944         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
   1945         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
   1946           NewIndices.push_back(CE->getOperand(i));
   1947 
   1948         // Add the last index of the source with the first index of the new GEP.
   1949         // Make sure to handle the case when they are actually different types.
   1950         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
   1951         // Otherwise it must be an array.
   1952         if (!Idx0->isNullValue()) {
   1953           Type *IdxTy = Combined->getType();
   1954           if (IdxTy != Idx0->getType()) {
   1955             Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
   1956             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
   1957             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
   1958             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
   1959           } else {
   1960             Combined =
   1961               ConstantExpr::get(Instruction::Add, Idx0, Combined);
   1962           }
   1963         }
   1964 
   1965         NewIndices.push_back(Combined);
   1966         NewIndices.append(Idxs.begin() + 1, Idxs.end());
   1967         return
   1968           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
   1969                                          inBounds &&
   1970                                            cast<GEPOperator>(CE)->isInBounds());
   1971       }
   1972     }
   1973 
   1974     // Attempt to fold casts to the same type away.  For example, folding:
   1975     //
   1976     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
   1977     //                       i64 0, i64 0)
   1978     // into:
   1979     //
   1980     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
   1981     //
   1982     // Don't fold if the cast is changing address spaces.
   1983     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
   1984       PointerType *SrcPtrTy =
   1985         dyn_cast<PointerType>(CE->getOperand(0)->getType());
   1986       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
   1987       if (SrcPtrTy && DstPtrTy) {
   1988         ArrayType *SrcArrayTy =
   1989           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
   1990         ArrayType *DstArrayTy =
   1991           dyn_cast<ArrayType>(DstPtrTy->getElementType());
   1992         if (SrcArrayTy && DstArrayTy
   1993             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
   1994             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
   1995           return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
   1996                                                 Idxs, inBounds);
   1997       }
   1998     }
   1999   }
   2000 
   2001   // Check to see if any array indices are not within the corresponding
   2002   // notional array bounds. If so, try to determine if they can be factored
   2003   // out into preceding dimensions.
   2004   bool Unknown = false;
   2005   SmallVector<Constant *, 8> NewIdxs;
   2006   Type *Ty = C->getType();
   2007   Type *Prev = 0;
   2008   for (unsigned i = 0, e = Idxs.size(); i != e;
   2009        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
   2010     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
   2011       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
   2012         if (ATy->getNumElements() <= INT64_MAX &&
   2013             ATy->getNumElements() != 0 &&
   2014             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
   2015           if (isa<SequentialType>(Prev)) {
   2016             // It's out of range, but we can factor it into the prior
   2017             // dimension.
   2018             NewIdxs.resize(Idxs.size());
   2019             ConstantInt *Factor = ConstantInt::get(CI->getType(),
   2020                                                    ATy->getNumElements());
   2021             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
   2022 
   2023             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
   2024             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
   2025 
   2026             // Before adding, extend both operands to i64 to avoid
   2027             // overflow trouble.
   2028             if (!PrevIdx->getType()->isIntegerTy(64))
   2029               PrevIdx = ConstantExpr::getSExt(PrevIdx,
   2030                                            Type::getInt64Ty(Div->getContext()));
   2031             if (!Div->getType()->isIntegerTy(64))
   2032               Div = ConstantExpr::getSExt(Div,
   2033                                           Type::getInt64Ty(Div->getContext()));
   2034 
   2035             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
   2036           } else {
   2037             // It's out of range, but the prior dimension is a struct
   2038             // so we can't do anything about it.
   2039             Unknown = true;
   2040           }
   2041         }
   2042     } else {
   2043       // We don't know if it's in range or not.
   2044       Unknown = true;
   2045     }
   2046   }
   2047 
   2048   // If we did any factoring, start over with the adjusted indices.
   2049   if (!NewIdxs.empty()) {
   2050     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
   2051       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
   2052     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
   2053   }
   2054 
   2055   // If all indices are known integers and normalized, we can do a simple
   2056   // check for the "inbounds" property.
   2057   if (!Unknown && !inBounds &&
   2058       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
   2059     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
   2060 
   2061   return 0;
   2062 }
   2063 
   2064 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
   2065                                           bool inBounds,
   2066                                           ArrayRef<Constant *> Idxs) {
   2067   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
   2068 }
   2069 
   2070 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
   2071                                           bool inBounds,
   2072                                           ArrayRef<Value *> Idxs) {
   2073   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
   2074 }
   2075