LLVM  mainline
ConstantFold.cpp
Go to the documentation of this file.
00001 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements folding of constants for LLVM.  This implements the
00011 // (internal) ConstantFold.h interface, which is used by the
00012 // ConstantExpr::get* methods to automatically fold constants when possible.
00013 //
00014 // The current constant folding implementation is implemented in two pieces: the
00015 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
00016 // a dependence in IR on Target.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "ConstantFold.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/Function.h"
00025 #include "llvm/IR/GetElementPtrTypeIterator.h"
00026 #include "llvm/IR/GlobalAlias.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/Operator.h"
00030 #include "llvm/IR/PatternMatch.h"
00031 #include "llvm/Support/Compiler.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/ManagedStatic.h"
00034 #include "llvm/Support/MathExtras.h"
00035 #include <limits>
00036 using namespace llvm;
00037 using namespace llvm::PatternMatch;
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                ConstantFold*Instruction Implementations
00041 //===----------------------------------------------------------------------===//
00042 
00043 /// BitCastConstantVector - Convert the specified vector Constant node to the
00044 /// specified vector type.  At this point, we know that the elements of the
00045 /// input vector constant are all simple integer or FP values.
00046 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
00047 
00048   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
00049   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
00050 
00051   // If this cast changes element count then we can't handle it here:
00052   // doing so requires endianness information.  This should be handled by
00053   // Analysis/ConstantFolding.cpp
00054   unsigned NumElts = DstTy->getNumElements();
00055   if (NumElts != CV->getType()->getVectorNumElements())
00056     return nullptr;
00057   
00058   Type *DstEltTy = DstTy->getElementType();
00059 
00060   SmallVector<Constant*, 16> Result;
00061   Type *Ty = IntegerType::get(CV->getContext(), 32);
00062   for (unsigned i = 0; i != NumElts; ++i) {
00063     Constant *C =
00064       ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
00065     C = ConstantExpr::getBitCast(C, DstEltTy);
00066     Result.push_back(C);
00067   }
00068 
00069   return ConstantVector::get(Result);
00070 }
00071 
00072 /// This function determines which opcode to use to fold two constant cast 
00073 /// expressions together. It uses CastInst::isEliminableCastPair to determine
00074 /// the opcode. Consequently its just a wrapper around that function.
00075 /// @brief Determine if it is valid to fold a cast of a cast
00076 static unsigned
00077 foldConstantCastPair(
00078   unsigned opc,          ///< opcode of the second cast constant expression
00079   ConstantExpr *Op,      ///< the first cast constant expression
00080   Type *DstTy            ///< destination type of the first cast
00081 ) {
00082   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
00083   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
00084   assert(CastInst::isCast(opc) && "Invalid cast opcode");
00085 
00086   // The the types and opcodes for the two Cast constant expressions
00087   Type *SrcTy = Op->getOperand(0)->getType();
00088   Type *MidTy = Op->getType();
00089   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
00090   Instruction::CastOps secondOp = Instruction::CastOps(opc);
00091 
00092   // Assume that pointers are never more than 64 bits wide, and only use this
00093   // for the middle type. Otherwise we could end up folding away illegal
00094   // bitcasts between address spaces with different sizes.
00095   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
00096 
00097   // Let CastInst::isEliminableCastPair do the heavy lifting.
00098   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
00099                                         nullptr, FakeIntPtrTy, nullptr);
00100 }
00101 
00102 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
00103   Type *SrcTy = V->getType();
00104   if (SrcTy == DestTy)
00105     return V; // no-op cast
00106 
00107   // Check to see if we are casting a pointer to an aggregate to a pointer to
00108   // the first element.  If so, return the appropriate GEP instruction.
00109   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
00110     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
00111       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
00112           && DPTy->getElementType()->isSized()) {
00113         SmallVector<Value*, 8> IdxList;
00114         Value *Zero =
00115           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
00116         IdxList.push_back(Zero);
00117         Type *ElTy = PTy->getElementType();
00118         while (ElTy != DPTy->getElementType()) {
00119           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
00120             if (STy->getNumElements() == 0) break;
00121             ElTy = STy->getElementType(0);
00122             IdxList.push_back(Zero);
00123           } else if (SequentialType *STy = 
00124                      dyn_cast<SequentialType>(ElTy)) {
00125             if (ElTy->isPointerTy()) break;  // Can't index into pointers!
00126             ElTy = STy->getElementType();
00127             IdxList.push_back(Zero);
00128           } else {
00129             break;
00130           }
00131         }
00132 
00133         if (ElTy == DPTy->getElementType())
00134           // This GEP is inbounds because all indices are zero.
00135           return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
00136       }
00137 
00138   // Handle casts from one vector constant to another.  We know that the src 
00139   // and dest type have the same size (otherwise its an illegal cast).
00140   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
00141     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
00142       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
00143              "Not cast between same sized vectors!");
00144       SrcTy = nullptr;
00145       // First, check for null.  Undef is already handled.
00146       if (isa<ConstantAggregateZero>(V))
00147         return Constant::getNullValue(DestTy);
00148 
00149       // Handle ConstantVector and ConstantAggregateVector.
00150       return BitCastConstantVector(V, DestPTy);
00151     }
00152 
00153     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
00154     // This allows for other simplifications (although some of them
00155     // can only be handled by Analysis/ConstantFolding.cpp).
00156     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
00157       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
00158   }
00159 
00160   // Finally, implement bitcast folding now.   The code below doesn't handle
00161   // bitcast right.
00162   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
00163     return ConstantPointerNull::get(cast<PointerType>(DestTy));
00164 
00165   // Handle integral constant input.
00166   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00167     if (DestTy->isIntegerTy())
00168       // Integral -> Integral. This is a no-op because the bit widths must
00169       // be the same. Consequently, we just fold to V.
00170       return V;
00171 
00172     // See note below regarding the PPC_FP128 restriction.
00173     if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
00174       return ConstantFP::get(DestTy->getContext(),
00175                              APFloat(DestTy->getFltSemantics(),
00176                                      CI->getValue()));
00177 
00178     // Otherwise, can't fold this (vector?)
00179     return nullptr;
00180   }
00181 
00182   // Handle ConstantFP input: FP -> Integral.
00183   if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
00184     // PPC_FP128 is really the sum of two consecutive doubles, where the first
00185     // double is always stored first in memory, regardless of the target
00186     // endianness. The memory layout of i128, however, depends on the target
00187     // endianness, and so we can't fold this without target endianness
00188     // information. This should instead be handled by
00189     // Analysis/ConstantFolding.cpp
00190     if (FP->getType()->isPPC_FP128Ty())
00191       return nullptr;
00192 
00193     return ConstantInt::get(FP->getContext(),
00194                             FP->getValueAPF().bitcastToAPInt());
00195   }
00196 
00197   return nullptr;
00198 }
00199 
00200 
00201 /// ExtractConstantBytes - V is an integer constant which only has a subset of
00202 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
00203 /// first byte used, counting from the least significant byte) and ByteSize,
00204 /// which is the number of bytes used.
00205 ///
00206 /// This function analyzes the specified constant to see if the specified byte
00207 /// range can be returned as a simplified constant.  If so, the constant is
00208 /// returned, otherwise null is returned.
00209 /// 
00210 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
00211                                       unsigned ByteSize) {
00212   assert(C->getType()->isIntegerTy() &&
00213          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
00214          "Non-byte sized integer input");
00215   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
00216   assert(ByteSize && "Must be accessing some piece");
00217   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
00218   assert(ByteSize != CSize && "Should not extract everything");
00219   
00220   // Constant Integers are simple.
00221   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
00222     APInt V = CI->getValue();
00223     if (ByteStart)
00224       V = V.lshr(ByteStart*8);
00225     V = V.trunc(ByteSize*8);
00226     return ConstantInt::get(CI->getContext(), V);
00227   }
00228   
00229   // In the input is a constant expr, we might be able to recursively simplify.
00230   // If not, we definitely can't do anything.
00231   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00232   if (!CE) return nullptr;
00233 
00234   switch (CE->getOpcode()) {
00235   default: return nullptr;
00236   case Instruction::Or: {
00237     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
00238     if (!RHS)
00239       return nullptr;
00240     
00241     // X | -1 -> -1.
00242     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
00243       if (RHSC->isAllOnesValue())
00244         return RHSC;
00245     
00246     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
00247     if (!LHS)
00248       return nullptr;
00249     return ConstantExpr::getOr(LHS, RHS);
00250   }
00251   case Instruction::And: {
00252     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
00253     if (!RHS)
00254       return nullptr;
00255     
00256     // X & 0 -> 0.
00257     if (RHS->isNullValue())
00258       return RHS;
00259     
00260     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
00261     if (!LHS)
00262       return nullptr;
00263     return ConstantExpr::getAnd(LHS, RHS);
00264   }
00265   case Instruction::LShr: {
00266     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
00267     if (!Amt)
00268       return nullptr;
00269     unsigned ShAmt = Amt->getZExtValue();
00270     // Cannot analyze non-byte shifts.
00271     if ((ShAmt & 7) != 0)
00272       return nullptr;
00273     ShAmt >>= 3;
00274     
00275     // If the extract is known to be all zeros, return zero.
00276     if (ByteStart >= CSize-ShAmt)
00277       return Constant::getNullValue(IntegerType::get(CE->getContext(),
00278                                                      ByteSize*8));
00279     // If the extract is known to be fully in the input, extract it.
00280     if (ByteStart+ByteSize+ShAmt <= CSize)
00281       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
00282     
00283     // TODO: Handle the 'partially zero' case.
00284     return nullptr;
00285   }
00286     
00287   case Instruction::Shl: {
00288     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
00289     if (!Amt)
00290       return nullptr;
00291     unsigned ShAmt = Amt->getZExtValue();
00292     // Cannot analyze non-byte shifts.
00293     if ((ShAmt & 7) != 0)
00294       return nullptr;
00295     ShAmt >>= 3;
00296     
00297     // If the extract is known to be all zeros, return zero.
00298     if (ByteStart+ByteSize <= ShAmt)
00299       return Constant::getNullValue(IntegerType::get(CE->getContext(),
00300                                                      ByteSize*8));
00301     // If the extract is known to be fully in the input, extract it.
00302     if (ByteStart >= ShAmt)
00303       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
00304     
00305     // TODO: Handle the 'partially zero' case.
00306     return nullptr;
00307   }
00308       
00309   case Instruction::ZExt: {
00310     unsigned SrcBitSize =
00311       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
00312     
00313     // If extracting something that is completely zero, return 0.
00314     if (ByteStart*8 >= SrcBitSize)
00315       return Constant::getNullValue(IntegerType::get(CE->getContext(),
00316                                                      ByteSize*8));
00317 
00318     // If exactly extracting the input, return it.
00319     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
00320       return CE->getOperand(0);
00321     
00322     // If extracting something completely in the input, if if the input is a
00323     // multiple of 8 bits, recurse.
00324     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
00325       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
00326       
00327     // Otherwise, if extracting a subset of the input, which is not multiple of
00328     // 8 bits, do a shift and trunc to get the bits.
00329     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
00330       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
00331       Constant *Res = CE->getOperand(0);
00332       if (ByteStart)
00333         Res = ConstantExpr::getLShr(Res, 
00334                                  ConstantInt::get(Res->getType(), ByteStart*8));
00335       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
00336                                                           ByteSize*8));
00337     }
00338     
00339     // TODO: Handle the 'partially zero' case.
00340     return nullptr;
00341   }
00342   }
00343 }
00344 
00345 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
00346 /// on Ty, with any known factors factored out. If Folded is false,
00347 /// return null if no factoring was possible, to avoid endlessly
00348 /// bouncing an unfoldable expression back into the top-level folder.
00349 ///
00350 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
00351                                  bool Folded) {
00352   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00353     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
00354     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
00355     return ConstantExpr::getNUWMul(E, N);
00356   }
00357 
00358   if (StructType *STy = dyn_cast<StructType>(Ty))
00359     if (!STy->isPacked()) {
00360       unsigned NumElems = STy->getNumElements();
00361       // An empty struct has size zero.
00362       if (NumElems == 0)
00363         return ConstantExpr::getNullValue(DestTy);
00364       // Check for a struct with all members having the same size.
00365       Constant *MemberSize =
00366         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
00367       bool AllSame = true;
00368       for (unsigned i = 1; i != NumElems; ++i)
00369         if (MemberSize !=
00370             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
00371           AllSame = false;
00372           break;
00373         }
00374       if (AllSame) {
00375         Constant *N = ConstantInt::get(DestTy, NumElems);
00376         return ConstantExpr::getNUWMul(MemberSize, N);
00377       }
00378     }
00379 
00380   // Pointer size doesn't depend on the pointee type, so canonicalize them
00381   // to an arbitrary pointee.
00382   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
00383     if (!PTy->getElementType()->isIntegerTy(1))
00384       return
00385         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
00386                                          PTy->getAddressSpace()),
00387                         DestTy, true);
00388 
00389   // If there's no interesting folding happening, bail so that we don't create
00390   // a constant that looks like it needs folding but really doesn't.
00391   if (!Folded)
00392     return nullptr;
00393 
00394   // Base case: Get a regular sizeof expression.
00395   Constant *C = ConstantExpr::getSizeOf(Ty);
00396   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00397                                                     DestTy, false),
00398                             C, DestTy);
00399   return C;
00400 }
00401 
00402 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
00403 /// on Ty, with any known factors factored out. If Folded is false,
00404 /// return null if no factoring was possible, to avoid endlessly
00405 /// bouncing an unfoldable expression back into the top-level folder.
00406 ///
00407 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
00408                                   bool Folded) {
00409   // The alignment of an array is equal to the alignment of the
00410   // array element. Note that this is not always true for vectors.
00411   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00412     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
00413     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00414                                                       DestTy,
00415                                                       false),
00416                               C, DestTy);
00417     return C;
00418   }
00419 
00420   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00421     // Packed structs always have an alignment of 1.
00422     if (STy->isPacked())
00423       return ConstantInt::get(DestTy, 1);
00424 
00425     // Otherwise, struct alignment is the maximum alignment of any member.
00426     // Without target data, we can't compare much, but we can check to see
00427     // if all the members have the same alignment.
00428     unsigned NumElems = STy->getNumElements();
00429     // An empty struct has minimal alignment.
00430     if (NumElems == 0)
00431       return ConstantInt::get(DestTy, 1);
00432     // Check for a struct with all members having the same alignment.
00433     Constant *MemberAlign =
00434       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
00435     bool AllSame = true;
00436     for (unsigned i = 1; i != NumElems; ++i)
00437       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
00438         AllSame = false;
00439         break;
00440       }
00441     if (AllSame)
00442       return MemberAlign;
00443   }
00444 
00445   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
00446   // to an arbitrary pointee.
00447   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
00448     if (!PTy->getElementType()->isIntegerTy(1))
00449       return
00450         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
00451                                                            1),
00452                                           PTy->getAddressSpace()),
00453                          DestTy, true);
00454 
00455   // If there's no interesting folding happening, bail so that we don't create
00456   // a constant that looks like it needs folding but really doesn't.
00457   if (!Folded)
00458     return nullptr;
00459 
00460   // Base case: Get a regular alignof expression.
00461   Constant *C = ConstantExpr::getAlignOf(Ty);
00462   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00463                                                     DestTy, false),
00464                             C, DestTy);
00465   return C;
00466 }
00467 
00468 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
00469 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
00470 /// return null if no factoring was possible, to avoid endlessly
00471 /// bouncing an unfoldable expression back into the top-level folder.
00472 ///
00473 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
00474                                    Type *DestTy,
00475                                    bool Folded) {
00476   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00477     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
00478                                                                 DestTy, false),
00479                                         FieldNo, DestTy);
00480     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
00481     return ConstantExpr::getNUWMul(E, N);
00482   }
00483 
00484   if (StructType *STy = dyn_cast<StructType>(Ty))
00485     if (!STy->isPacked()) {
00486       unsigned NumElems = STy->getNumElements();
00487       // An empty struct has no members.
00488       if (NumElems == 0)
00489         return nullptr;
00490       // Check for a struct with all members having the same size.
00491       Constant *MemberSize =
00492         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
00493       bool AllSame = true;
00494       for (unsigned i = 1; i != NumElems; ++i)
00495         if (MemberSize !=
00496             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
00497           AllSame = false;
00498           break;
00499         }
00500       if (AllSame) {
00501         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
00502                                                                     false,
00503                                                                     DestTy,
00504                                                                     false),
00505                                             FieldNo, DestTy);
00506         return ConstantExpr::getNUWMul(MemberSize, N);
00507       }
00508     }
00509 
00510   // If there's no interesting folding happening, bail so that we don't create
00511   // a constant that looks like it needs folding but really doesn't.
00512   if (!Folded)
00513     return nullptr;
00514 
00515   // Base case: Get a regular offsetof expression.
00516   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
00517   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00518                                                     DestTy, false),
00519                             C, DestTy);
00520   return C;
00521 }
00522 
00523 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
00524                                             Type *DestTy) {
00525   if (isa<UndefValue>(V)) {
00526     // zext(undef) = 0, because the top bits will be zero.
00527     // sext(undef) = 0, because the top bits will all be the same.
00528     // [us]itofp(undef) = 0, because the result value is bounded.
00529     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
00530         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
00531       return Constant::getNullValue(DestTy);
00532     return UndefValue::get(DestTy);
00533   }
00534 
00535   if (V->isNullValue() && !DestTy->isX86_MMXTy())
00536     return Constant::getNullValue(DestTy);
00537 
00538   // If the cast operand is a constant expression, there's a few things we can
00539   // do to try to simplify it.
00540   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00541     if (CE->isCast()) {
00542       // Try hard to fold cast of cast because they are often eliminable.
00543       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
00544         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
00545     } else if (CE->getOpcode() == Instruction::GetElementPtr &&
00546                // Do not fold addrspacecast (gep 0, .., 0). It might make the
00547                // addrspacecast uncanonicalized.
00548                opc != Instruction::AddrSpaceCast) {
00549       // If all of the indexes in the GEP are null values, there is no pointer
00550       // adjustment going on.  We might as well cast the source pointer.
00551       bool isAllNull = true;
00552       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
00553         if (!CE->getOperand(i)->isNullValue()) {
00554           isAllNull = false;
00555           break;
00556         }
00557       if (isAllNull)
00558         // This is casting one pointer type to another, always BitCast
00559         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
00560     }
00561   }
00562 
00563   // If the cast operand is a constant vector, perform the cast by
00564   // operating on each element. In the cast of bitcasts, the element
00565   // count may be mismatched; don't attempt to handle that here.
00566   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
00567       DestTy->isVectorTy() &&
00568       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
00569     SmallVector<Constant*, 16> res;
00570     VectorType *DestVecTy = cast<VectorType>(DestTy);
00571     Type *DstEltTy = DestVecTy->getElementType();
00572     Type *Ty = IntegerType::get(V->getContext(), 32);
00573     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
00574       Constant *C =
00575         ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
00576       res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
00577     }
00578     return ConstantVector::get(res);
00579   }
00580 
00581   // We actually have to do a cast now. Perform the cast according to the
00582   // opcode specified.
00583   switch (opc) {
00584   default:
00585     llvm_unreachable("Failed to cast constant expression");
00586   case Instruction::FPTrunc:
00587   case Instruction::FPExt:
00588     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
00589       bool ignored;
00590       APFloat Val = FPC->getValueAPF();
00591       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
00592                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
00593                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
00594                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
00595                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
00596                   DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
00597                   APFloat::Bogus,
00598                   APFloat::rmNearestTiesToEven, &ignored);
00599       return ConstantFP::get(V->getContext(), Val);
00600     }
00601     return nullptr; // Can't fold.
00602   case Instruction::FPToUI: 
00603   case Instruction::FPToSI:
00604     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
00605       const APFloat &V = FPC->getValueAPF();
00606       bool ignored;
00607       uint64_t x[2]; 
00608       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00609       if (APFloat::opInvalidOp ==
00610           V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
00611                              APFloat::rmTowardZero, &ignored)) {
00612         // Undefined behavior invoked - the destination type can't represent
00613         // the input constant.
00614         return UndefValue::get(DestTy);
00615       }
00616       APInt Val(DestBitWidth, x);
00617       return ConstantInt::get(FPC->getContext(), Val);
00618     }
00619     return nullptr; // Can't fold.
00620   case Instruction::IntToPtr:   //always treated as unsigned
00621     if (V->isNullValue())       // Is it an integral null value?
00622       return ConstantPointerNull::get(cast<PointerType>(DestTy));
00623     return nullptr;                   // Other pointer types cannot be casted
00624   case Instruction::PtrToInt:   // always treated as unsigned
00625     // Is it a null pointer value?
00626     if (V->isNullValue())
00627       return ConstantInt::get(DestTy, 0);
00628     // If this is a sizeof-like expression, pull out multiplications by
00629     // known factors to expose them to subsequent folding. If it's an
00630     // alignof-like expression, factor out known factors.
00631     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00632       if (CE->getOpcode() == Instruction::GetElementPtr &&
00633           CE->getOperand(0)->isNullValue()) {
00634         Type *Ty =
00635           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
00636         if (CE->getNumOperands() == 2) {
00637           // Handle a sizeof-like expression.
00638           Constant *Idx = CE->getOperand(1);
00639           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
00640           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
00641             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
00642                                                                 DestTy, false),
00643                                         Idx, DestTy);
00644             return ConstantExpr::getMul(C, Idx);
00645           }
00646         } else if (CE->getNumOperands() == 3 &&
00647                    CE->getOperand(1)->isNullValue()) {
00648           // Handle an alignof-like expression.
00649           if (StructType *STy = dyn_cast<StructType>(Ty))
00650             if (!STy->isPacked()) {
00651               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
00652               if (CI->isOne() &&
00653                   STy->getNumElements() == 2 &&
00654                   STy->getElementType(0)->isIntegerTy(1)) {
00655                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
00656               }
00657             }
00658           // Handle an offsetof-like expression.
00659           if (Ty->isStructTy() || Ty->isArrayTy()) {
00660             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
00661                                                 DestTy, false))
00662               return C;
00663           }
00664         }
00665       }
00666     // Other pointer types cannot be casted
00667     return nullptr;
00668   case Instruction::UIToFP:
00669   case Instruction::SIToFP:
00670     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00671       APInt api = CI->getValue();
00672       APFloat apf(DestTy->getFltSemantics(),
00673                   APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
00674       if (APFloat::opOverflow &
00675           apf.convertFromAPInt(api, opc==Instruction::SIToFP,
00676                               APFloat::rmNearestTiesToEven)) {
00677         // Undefined behavior invoked - the destination type can't represent
00678         // the input constant.
00679         return UndefValue::get(DestTy);
00680       }
00681       return ConstantFP::get(V->getContext(), apf);
00682     }
00683     return nullptr;
00684   case Instruction::ZExt:
00685     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00686       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00687       return ConstantInt::get(V->getContext(),
00688                               CI->getValue().zext(BitWidth));
00689     }
00690     return nullptr;
00691   case Instruction::SExt:
00692     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00693       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00694       return ConstantInt::get(V->getContext(),
00695                               CI->getValue().sext(BitWidth));
00696     }
00697     return nullptr;
00698   case Instruction::Trunc: {
00699     if (V->getType()->isVectorTy())
00700       return nullptr;
00701 
00702     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00703     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00704       return ConstantInt::get(V->getContext(),
00705                               CI->getValue().trunc(DestBitWidth));
00706     }
00707     
00708     // The input must be a constantexpr.  See if we can simplify this based on
00709     // the bytes we are demanding.  Only do this if the source and dest are an
00710     // even multiple of a byte.
00711     if ((DestBitWidth & 7) == 0 &&
00712         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
00713       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
00714         return Res;
00715       
00716     return nullptr;
00717   }
00718   case Instruction::BitCast:
00719     return FoldBitCast(V, DestTy);
00720   case Instruction::AddrSpaceCast:
00721     return nullptr;
00722   }
00723 }
00724 
00725 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
00726                                               Constant *V1, Constant *V2) {
00727   // Check for i1 and vector true/false conditions.
00728   if (Cond->isNullValue()) return V2;
00729   if (Cond->isAllOnesValue()) return V1;
00730 
00731   // If the condition is a vector constant, fold the result elementwise.
00732   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
00733     SmallVector<Constant*, 16> Result;
00734     Type *Ty = IntegerType::get(CondV->getContext(), 32);
00735     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
00736       Constant *V;
00737       Constant *V1Element = ConstantExpr::getExtractElement(V1,
00738                                                     ConstantInt::get(Ty, i));
00739       Constant *V2Element = ConstantExpr::getExtractElement(V2,
00740                                                     ConstantInt::get(Ty, i));
00741       Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
00742       if (V1Element == V2Element) {
00743         V = V1Element;
00744       } else if (isa<UndefValue>(Cond)) {
00745         V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
00746       } else {
00747         if (!isa<ConstantInt>(Cond)) break;
00748         V = Cond->isNullValue() ? V2Element : V1Element;
00749       }
00750       Result.push_back(V);
00751     }
00752     
00753     // If we were able to build the vector, return it.
00754     if (Result.size() == V1->getType()->getVectorNumElements())
00755       return ConstantVector::get(Result);
00756   }
00757 
00758   if (isa<UndefValue>(Cond)) {
00759     if (isa<UndefValue>(V1)) return V1;
00760     return V2;
00761   }
00762   if (isa<UndefValue>(V1)) return V2;
00763   if (isa<UndefValue>(V2)) return V1;
00764   if (V1 == V2) return V1;
00765 
00766   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
00767     if (TrueVal->getOpcode() == Instruction::Select)
00768       if (TrueVal->getOperand(0) == Cond)
00769         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
00770   }
00771   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
00772     if (FalseVal->getOpcode() == Instruction::Select)
00773       if (FalseVal->getOperand(0) == Cond)
00774         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
00775   }
00776 
00777   return nullptr;
00778 }
00779 
00780 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
00781                                                       Constant *Idx) {
00782   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
00783     return UndefValue::get(Val->getType()->getVectorElementType());
00784   if (Val->isNullValue())  // ee(zero, x) -> zero
00785     return Constant::getNullValue(Val->getType()->getVectorElementType());
00786   // ee({w,x,y,z}, undef) -> undef
00787   if (isa<UndefValue>(Idx))
00788     return UndefValue::get(Val->getType()->getVectorElementType());
00789 
00790   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
00791     uint64_t Index = CIdx->getZExtValue();
00792     // ee({w,x,y,z}, wrong_value) -> undef
00793     if (Index >= Val->getType()->getVectorNumElements())
00794       return UndefValue::get(Val->getType()->getVectorElementType());
00795     return Val->getAggregateElement(Index);
00796   }
00797   return nullptr;
00798 }
00799 
00800 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
00801                                                      Constant *Elt,
00802                                                      Constant *Idx) {
00803   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
00804   if (!CIdx) return nullptr;
00805   const APInt &IdxVal = CIdx->getValue();
00806   
00807   SmallVector<Constant*, 16> Result;
00808   Type *Ty = IntegerType::get(Val->getContext(), 32);
00809   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
00810     if (i == IdxVal) {
00811       Result.push_back(Elt);
00812       continue;
00813     }
00814     
00815     Constant *C =
00816       ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
00817     Result.push_back(C);
00818   }
00819   
00820   return ConstantVector::get(Result);
00821 }
00822 
00823 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
00824                                                      Constant *V2,
00825                                                      Constant *Mask) {
00826   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
00827   Type *EltTy = V1->getType()->getVectorElementType();
00828 
00829   // Undefined shuffle mask -> undefined value.
00830   if (isa<UndefValue>(Mask))
00831     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
00832 
00833   // Don't break the bitcode reader hack.
00834   if (isa<ConstantExpr>(Mask)) return nullptr;
00835   
00836   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
00837 
00838   // Loop over the shuffle mask, evaluating each element.
00839   SmallVector<Constant*, 32> Result;
00840   for (unsigned i = 0; i != MaskNumElts; ++i) {
00841     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
00842     if (Elt == -1) {
00843       Result.push_back(UndefValue::get(EltTy));
00844       continue;
00845     }
00846     Constant *InElt;
00847     if (unsigned(Elt) >= SrcNumElts*2)
00848       InElt = UndefValue::get(EltTy);
00849     else if (unsigned(Elt) >= SrcNumElts) {
00850       Type *Ty = IntegerType::get(V2->getContext(), 32);
00851       InElt =
00852         ConstantExpr::getExtractElement(V2,
00853                                         ConstantInt::get(Ty, Elt - SrcNumElts));
00854     } else {
00855       Type *Ty = IntegerType::get(V1->getContext(), 32);
00856       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
00857     }
00858     Result.push_back(InElt);
00859   }
00860 
00861   return ConstantVector::get(Result);
00862 }
00863 
00864 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
00865                                                     ArrayRef<unsigned> Idxs) {
00866   // Base case: no indices, so return the entire value.
00867   if (Idxs.empty())
00868     return Agg;
00869 
00870   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
00871     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
00872 
00873   return nullptr;
00874 }
00875 
00876 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
00877                                                    Constant *Val,
00878                                                    ArrayRef<unsigned> Idxs) {
00879   // Base case: no indices, so replace the entire value.
00880   if (Idxs.empty())
00881     return Val;
00882 
00883   unsigned NumElts;
00884   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
00885     NumElts = ST->getNumElements();
00886   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
00887     NumElts = AT->getNumElements();
00888   else
00889     NumElts = Agg->getType()->getVectorNumElements();
00890 
00891   SmallVector<Constant*, 32> Result;
00892   for (unsigned i = 0; i != NumElts; ++i) {
00893     Constant *C = Agg->getAggregateElement(i);
00894     if (!C) return nullptr;
00895 
00896     if (Idxs[0] == i)
00897       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
00898     
00899     Result.push_back(C);
00900   }
00901   
00902   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
00903     return ConstantStruct::get(ST, Result);
00904   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
00905     return ConstantArray::get(AT, Result);
00906   return ConstantVector::get(Result);
00907 }
00908 
00909 
00910 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
00911                                               Constant *C1, Constant *C2) {
00912   // Handle UndefValue up front.
00913   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
00914     switch (Opcode) {
00915     case Instruction::Xor:
00916       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00917         // Handle undef ^ undef -> 0 special case. This is a common
00918         // idiom (misuse).
00919         return Constant::getNullValue(C1->getType());
00920       // Fallthrough
00921     case Instruction::Add:
00922     case Instruction::Sub:
00923       return UndefValue::get(C1->getType());
00924     case Instruction::And:
00925       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
00926         return C1;
00927       return Constant::getNullValue(C1->getType());   // undef & X -> 0
00928     case Instruction::Mul: {
00929       // undef * undef -> undef
00930       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00931         return C1;
00932       const APInt *CV;
00933       // X * undef -> undef   if X is odd
00934       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
00935         if ((*CV)[0])
00936           return UndefValue::get(C1->getType());
00937 
00938       // X * undef -> 0       otherwise
00939       return Constant::getNullValue(C1->getType());
00940     }
00941     case Instruction::SDiv:
00942     case Instruction::UDiv:
00943       // X / undef -> undef
00944       if (match(C1, m_Zero()))
00945         return C2;
00946       // undef / 0 -> undef
00947       // undef / 1 -> undef
00948       if (match(C2, m_Zero()) || match(C2, m_One()))
00949         return C1;
00950       // undef / X -> 0       otherwise
00951       return Constant::getNullValue(C1->getType());
00952     case Instruction::URem:
00953     case Instruction::SRem:
00954       // X % undef -> undef
00955       if (match(C2, m_Undef()))
00956         return C2;
00957       // undef % 0 -> undef
00958       if (match(C2, m_Zero()))
00959         return C1;
00960       // undef % X -> 0       otherwise
00961       return Constant::getNullValue(C1->getType());
00962     case Instruction::Or:                          // X | undef -> -1
00963       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
00964         return C1;
00965       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
00966     case Instruction::LShr:
00967       // X >>l undef -> undef
00968       if (isa<UndefValue>(C2))
00969         return C2;
00970       // undef >>l 0 -> undef
00971       if (match(C2, m_Zero()))
00972         return C1;
00973       // undef >>l X -> 0
00974       return Constant::getNullValue(C1->getType());
00975     case Instruction::AShr:
00976       // X >>a undef -> undef
00977       if (isa<UndefValue>(C2))
00978         return C2;
00979       // undef >>a 0 -> undef
00980       if (match(C2, m_Zero()))
00981         return C1;
00982       // TODO: undef >>a X -> undef if the shift is exact
00983       // undef >>a X -> 0
00984       return Constant::getNullValue(C1->getType());
00985     case Instruction::Shl:
00986       // X << undef -> undef
00987       if (isa<UndefValue>(C2))
00988         return C2;
00989       // undef << 0 -> undef
00990       if (match(C2, m_Zero()))
00991         return C1;
00992       // undef << X -> 0
00993       return Constant::getNullValue(C1->getType());
00994     }
00995   }
00996 
00997   // Handle simplifications when the RHS is a constant int.
00998   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
00999     switch (Opcode) {
01000     case Instruction::Add:
01001       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
01002       break;
01003     case Instruction::Sub:
01004       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
01005       break;
01006     case Instruction::Mul:
01007       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
01008       if (CI2->equalsInt(1))
01009         return C1;                                              // X * 1 == X
01010       break;
01011     case Instruction::UDiv:
01012     case Instruction::SDiv:
01013       if (CI2->equalsInt(1))
01014         return C1;                                            // X / 1 == X
01015       if (CI2->equalsInt(0))
01016         return UndefValue::get(CI2->getType());               // X / 0 == undef
01017       break;
01018     case Instruction::URem:
01019     case Instruction::SRem:
01020       if (CI2->equalsInt(1))
01021         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
01022       if (CI2->equalsInt(0))
01023         return UndefValue::get(CI2->getType());               // X % 0 == undef
01024       break;
01025     case Instruction::And:
01026       if (CI2->isZero()) return C2;                           // X & 0 == 0
01027       if (CI2->isAllOnesValue())
01028         return C1;                                            // X & -1 == X
01029 
01030       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01031         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
01032         if (CE1->getOpcode() == Instruction::ZExt) {
01033           unsigned DstWidth = CI2->getType()->getBitWidth();
01034           unsigned SrcWidth =
01035             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
01036           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
01037           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
01038             return C1;
01039         }
01040 
01041         // If and'ing the address of a global with a constant, fold it.
01042         if (CE1->getOpcode() == Instruction::PtrToInt && 
01043             isa<GlobalValue>(CE1->getOperand(0))) {
01044           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
01045 
01046           // Functions are at least 4-byte aligned.
01047           unsigned GVAlign = GV->getAlignment();
01048           if (isa<Function>(GV))
01049             GVAlign = std::max(GVAlign, 4U);
01050 
01051           if (GVAlign > 1) {
01052             unsigned DstWidth = CI2->getType()->getBitWidth();
01053             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
01054             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
01055 
01056             // If checking bits we know are clear, return zero.
01057             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
01058               return Constant::getNullValue(CI2->getType());
01059           }
01060         }
01061       }
01062       break;
01063     case Instruction::Or:
01064       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
01065       if (CI2->isAllOnesValue())
01066         return C2;                         // X | -1 == -1
01067       break;
01068     case Instruction::Xor:
01069       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
01070 
01071       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01072         switch (CE1->getOpcode()) {
01073         default: break;
01074         case Instruction::ICmp:
01075         case Instruction::FCmp:
01076           // cmp pred ^ true -> cmp !pred
01077           assert(CI2->equalsInt(1));
01078           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
01079           pred = CmpInst::getInversePredicate(pred);
01080           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
01081                                           CE1->getOperand(1));
01082         }
01083       }
01084       break;
01085     case Instruction::AShr:
01086       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
01087       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
01088         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
01089           return ConstantExpr::getLShr(C1, C2);
01090       break;
01091     }
01092   } else if (isa<ConstantInt>(C1)) {
01093     // If C1 is a ConstantInt and C2 is not, swap the operands.
01094     if (Instruction::isCommutative(Opcode))
01095       return ConstantExpr::get(Opcode, C2, C1);
01096   }
01097 
01098   // At this point we know neither constant is an UndefValue.
01099   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
01100     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
01101       const APInt &C1V = CI1->getValue();
01102       const APInt &C2V = CI2->getValue();
01103       switch (Opcode) {
01104       default:
01105         break;
01106       case Instruction::Add:     
01107         return ConstantInt::get(CI1->getContext(), C1V + C2V);
01108       case Instruction::Sub:     
01109         return ConstantInt::get(CI1->getContext(), C1V - C2V);
01110       case Instruction::Mul:     
01111         return ConstantInt::get(CI1->getContext(), C1V * C2V);
01112       case Instruction::UDiv:
01113         assert(!CI2->isNullValue() && "Div by zero handled above");
01114         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
01115       case Instruction::SDiv:
01116         assert(!CI2->isNullValue() && "Div by zero handled above");
01117         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
01118           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
01119         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
01120       case Instruction::URem:
01121         assert(!CI2->isNullValue() && "Div by zero handled above");
01122         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
01123       case Instruction::SRem:
01124         assert(!CI2->isNullValue() && "Div by zero handled above");
01125         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
01126           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
01127         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
01128       case Instruction::And:
01129         return ConstantInt::get(CI1->getContext(), C1V & C2V);
01130       case Instruction::Or:
01131         return ConstantInt::get(CI1->getContext(), C1V | C2V);
01132       case Instruction::Xor:
01133         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
01134       case Instruction::Shl:
01135         if (C2V.ult(C1V.getBitWidth()))
01136           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
01137         return UndefValue::get(C1->getType()); // too big shift is undef
01138       case Instruction::LShr:
01139         if (C2V.ult(C1V.getBitWidth()))
01140           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
01141         return UndefValue::get(C1->getType()); // too big shift is undef
01142       case Instruction::AShr:
01143         if (C2V.ult(C1V.getBitWidth()))
01144           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
01145         return UndefValue::get(C1->getType()); // too big shift is undef
01146       }
01147     }
01148 
01149     switch (Opcode) {
01150     case Instruction::SDiv:
01151     case Instruction::UDiv:
01152     case Instruction::URem:
01153     case Instruction::SRem:
01154     case Instruction::LShr:
01155     case Instruction::AShr:
01156     case Instruction::Shl:
01157       if (CI1->equalsInt(0)) return C1;
01158       break;
01159     default:
01160       break;
01161     }
01162   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
01163     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
01164       APFloat C1V = CFP1->getValueAPF();
01165       APFloat C2V = CFP2->getValueAPF();
01166       APFloat C3V = C1V;  // copy for modification
01167       switch (Opcode) {
01168       default:                   
01169         break;
01170       case Instruction::FAdd:
01171         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
01172         return ConstantFP::get(C1->getContext(), C3V);
01173       case Instruction::FSub:
01174         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
01175         return ConstantFP::get(C1->getContext(), C3V);
01176       case Instruction::FMul:
01177         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
01178         return ConstantFP::get(C1->getContext(), C3V);
01179       case Instruction::FDiv:
01180         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
01181         return ConstantFP::get(C1->getContext(), C3V);
01182       case Instruction::FRem:
01183         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
01184         return ConstantFP::get(C1->getContext(), C3V);
01185       }
01186     }
01187   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
01188     // Perform elementwise folding.
01189     SmallVector<Constant*, 16> Result;
01190     Type *Ty = IntegerType::get(VTy->getContext(), 32);
01191     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
01192       Constant *LHS =
01193         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
01194       Constant *RHS =
01195         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
01196       
01197       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
01198     }
01199     
01200     return ConstantVector::get(Result);
01201   }
01202 
01203   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01204     // There are many possible foldings we could do here.  We should probably
01205     // at least fold add of a pointer with an integer into the appropriate
01206     // getelementptr.  This will improve alias analysis a bit.
01207 
01208     // Given ((a + b) + c), if (b + c) folds to something interesting, return
01209     // (a + (b + c)).
01210     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
01211       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
01212       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
01213         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
01214     }
01215   } else if (isa<ConstantExpr>(C2)) {
01216     // If C2 is a constant expr and C1 isn't, flop them around and fold the
01217     // other way if possible.
01218     if (Instruction::isCommutative(Opcode))
01219       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
01220   }
01221 
01222   // i1 can be simplified in many cases.
01223   if (C1->getType()->isIntegerTy(1)) {
01224     switch (Opcode) {
01225     case Instruction::Add:
01226     case Instruction::Sub:
01227       return ConstantExpr::getXor(C1, C2);
01228     case Instruction::Mul:
01229       return ConstantExpr::getAnd(C1, C2);
01230     case Instruction::Shl:
01231     case Instruction::LShr:
01232     case Instruction::AShr:
01233       // We can assume that C2 == 0.  If it were one the result would be
01234       // undefined because the shift value is as large as the bitwidth.
01235       return C1;
01236     case Instruction::SDiv:
01237     case Instruction::UDiv:
01238       // We can assume that C2 == 1.  If it were zero the result would be
01239       // undefined through division by zero.
01240       return C1;
01241     case Instruction::URem:
01242     case Instruction::SRem:
01243       // We can assume that C2 == 1.  If it were zero the result would be
01244       // undefined through division by zero.
01245       return ConstantInt::getFalse(C1->getContext());
01246     default:
01247       break;
01248     }
01249   }
01250 
01251   // We don't know how to fold this.
01252   return nullptr;
01253 }
01254 
01255 /// isZeroSizedType - This type is zero sized if its an array or structure of
01256 /// zero sized types.  The only leaf zero sized type is an empty structure.
01257 static bool isMaybeZeroSizedType(Type *Ty) {
01258   if (StructType *STy = dyn_cast<StructType>(Ty)) {
01259     if (STy->isOpaque()) return true;  // Can't say.
01260 
01261     // If all of elements have zero size, this does too.
01262     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
01263       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
01264     return true;
01265 
01266   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
01267     return isMaybeZeroSizedType(ATy->getElementType());
01268   }
01269   return false;
01270 }
01271 
01272 /// IdxCompare - Compare the two constants as though they were getelementptr
01273 /// indices.  This allows coersion of the types to be the same thing.
01274 ///
01275 /// If the two constants are the "same" (after coersion), return 0.  If the
01276 /// first is less than the second, return -1, if the second is less than the
01277 /// first, return 1.  If the constants are not integral, return -2.
01278 ///
01279 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
01280   if (C1 == C2) return 0;
01281 
01282   // Ok, we found a different index.  If they are not ConstantInt, we can't do
01283   // anything with them.
01284   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
01285     return -2; // don't know!
01286 
01287   // We cannot compare the indices if they don't fit in an int64_t.
01288   if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
01289       cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
01290     return -2; // don't know!
01291 
01292   // Ok, we have two differing integer indices.  Sign extend them to be the same
01293   // type.
01294   int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
01295   int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
01296 
01297   if (C1Val == C2Val) return 0;  // They are equal
01298 
01299   // If the type being indexed over is really just a zero sized type, there is
01300   // no pointer difference being made here.
01301   if (isMaybeZeroSizedType(ElTy))
01302     return -2; // dunno.
01303 
01304   // If they are really different, now that they are the same type, then we
01305   // found a difference!
01306   if (C1Val < C2Val)
01307     return -1;
01308   else
01309     return 1;
01310 }
01311 
01312 /// evaluateFCmpRelation - This function determines if there is anything we can
01313 /// decide about the two constants provided.  This doesn't need to handle simple
01314 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
01315 /// If we can determine that the two constants have a particular relation to 
01316 /// each other, we should return the corresponding FCmpInst predicate, 
01317 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
01318 /// ConstantFoldCompareInstruction.
01319 ///
01320 /// To simplify this code we canonicalize the relation so that the first
01321 /// operand is always the most "complex" of the two.  We consider ConstantFP
01322 /// to be the simplest, and ConstantExprs to be the most complex.
01323 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
01324   assert(V1->getType() == V2->getType() &&
01325          "Cannot compare values of different types!");
01326 
01327   // Handle degenerate case quickly
01328   if (V1 == V2) return FCmpInst::FCMP_OEQ;
01329 
01330   if (!isa<ConstantExpr>(V1)) {
01331     if (!isa<ConstantExpr>(V2)) {
01332       // Simple case, use the standard constant folder.
01333       ConstantInt *R = nullptr;
01334       R = dyn_cast<ConstantInt>(
01335                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
01336       if (R && !R->isZero()) 
01337         return FCmpInst::FCMP_OEQ;
01338       R = dyn_cast<ConstantInt>(
01339                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
01340       if (R && !R->isZero()) 
01341         return FCmpInst::FCMP_OLT;
01342       R = dyn_cast<ConstantInt>(
01343                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
01344       if (R && !R->isZero()) 
01345         return FCmpInst::FCMP_OGT;
01346 
01347       // Nothing more we can do
01348       return FCmpInst::BAD_FCMP_PREDICATE;
01349     }
01350 
01351     // If the first operand is simple and second is ConstantExpr, swap operands.
01352     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
01353     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
01354       return FCmpInst::getSwappedPredicate(SwappedRelation);
01355   } else {
01356     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01357     // constantexpr or a simple constant.
01358     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01359     switch (CE1->getOpcode()) {
01360     case Instruction::FPTrunc:
01361     case Instruction::FPExt:
01362     case Instruction::UIToFP:
01363     case Instruction::SIToFP:
01364       // We might be able to do something with these but we don't right now.
01365       break;
01366     default:
01367       break;
01368     }
01369   }
01370   // There are MANY other foldings that we could perform here.  They will
01371   // probably be added on demand, as they seem needed.
01372   return FCmpInst::BAD_FCMP_PREDICATE;
01373 }
01374 
01375 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
01376                                                       const GlobalValue *GV2) {
01377   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
01378     if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
01379       return true;
01380     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
01381       Type *Ty = GVar->getType()->getPointerElementType();
01382       // A global with opaque type might end up being zero sized.
01383       if (!Ty->isSized())
01384         return true;
01385       // A global with an empty type might lie at the address of any other
01386       // global.
01387       if (Ty->isEmptyTy())
01388         return true;
01389     }
01390     return false;
01391   };
01392   // Don't try to decide equality of aliases.
01393   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
01394     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
01395       return ICmpInst::ICMP_NE;
01396   return ICmpInst::BAD_ICMP_PREDICATE;
01397 }
01398 
01399 /// evaluateICmpRelation - This function determines if there is anything we can
01400 /// decide about the two constants provided.  This doesn't need to handle simple
01401 /// things like integer comparisons, but should instead handle ConstantExprs
01402 /// and GlobalValues.  If we can determine that the two constants have a
01403 /// particular relation to each other, we should return the corresponding ICmp
01404 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
01405 ///
01406 /// To simplify this code we canonicalize the relation so that the first
01407 /// operand is always the most "complex" of the two.  We consider simple
01408 /// constants (like ConstantInt) to be the simplest, followed by
01409 /// GlobalValues, followed by ConstantExpr's (the most complex).
01410 ///
01411 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
01412                                                 bool isSigned) {
01413   assert(V1->getType() == V2->getType() &&
01414          "Cannot compare different types of values!");
01415   if (V1 == V2) return ICmpInst::ICMP_EQ;
01416 
01417   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
01418       !isa<BlockAddress>(V1)) {
01419     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
01420         !isa<BlockAddress>(V2)) {
01421       // We distilled this down to a simple case, use the standard constant
01422       // folder.
01423       ConstantInt *R = nullptr;
01424       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
01425       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01426       if (R && !R->isZero()) 
01427         return pred;
01428       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01429       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01430       if (R && !R->isZero())
01431         return pred;
01432       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01433       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01434       if (R && !R->isZero())
01435         return pred;
01436 
01437       // If we couldn't figure it out, bail.
01438       return ICmpInst::BAD_ICMP_PREDICATE;
01439     }
01440 
01441     // If the first operand is simple, swap operands.
01442     ICmpInst::Predicate SwappedRelation = 
01443       evaluateICmpRelation(V2, V1, isSigned);
01444     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01445       return ICmpInst::getSwappedPredicate(SwappedRelation);
01446 
01447   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
01448     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01449       ICmpInst::Predicate SwappedRelation = 
01450         evaluateICmpRelation(V2, V1, isSigned);
01451       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01452         return ICmpInst::getSwappedPredicate(SwappedRelation);
01453       return ICmpInst::BAD_ICMP_PREDICATE;
01454     }
01455 
01456     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
01457     // constant (which, since the types must match, means that it's a
01458     // ConstantPointerNull).
01459     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
01460       return areGlobalsPotentiallyEqual(GV, GV2);
01461     } else if (isa<BlockAddress>(V2)) {
01462       return ICmpInst::ICMP_NE; // Globals never equal labels.
01463     } else {
01464       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
01465       // GlobalVals can never be null unless they have external weak linkage.
01466       // We don't try to evaluate aliases here.
01467       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
01468         return ICmpInst::ICMP_NE;
01469     }
01470   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
01471     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01472       ICmpInst::Predicate SwappedRelation = 
01473         evaluateICmpRelation(V2, V1, isSigned);
01474       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01475         return ICmpInst::getSwappedPredicate(SwappedRelation);
01476       return ICmpInst::BAD_ICMP_PREDICATE;
01477     }
01478     
01479     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
01480     // constant (which, since the types must match, means that it is a
01481     // ConstantPointerNull).
01482     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
01483       // Block address in another function can't equal this one, but block
01484       // addresses in the current function might be the same if blocks are
01485       // empty.
01486       if (BA2->getFunction() != BA->getFunction())
01487         return ICmpInst::ICMP_NE;
01488     } else {
01489       // Block addresses aren't null, don't equal the address of globals.
01490       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
01491              "Canonicalization guarantee!");
01492       return ICmpInst::ICMP_NE;
01493     }
01494   } else {
01495     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01496     // constantexpr, a global, block address, or a simple constant.
01497     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01498     Constant *CE1Op0 = CE1->getOperand(0);
01499 
01500     switch (CE1->getOpcode()) {
01501     case Instruction::Trunc:
01502     case Instruction::FPTrunc:
01503     case Instruction::FPExt:
01504     case Instruction::FPToUI:
01505     case Instruction::FPToSI:
01506       break; // We can't evaluate floating point casts or truncations.
01507 
01508     case Instruction::UIToFP:
01509     case Instruction::SIToFP:
01510     case Instruction::BitCast:
01511     case Instruction::ZExt:
01512     case Instruction::SExt:
01513       // If the cast is not actually changing bits, and the second operand is a
01514       // null pointer, do the comparison with the pre-casted value.
01515       if (V2->isNullValue() &&
01516           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
01517         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
01518         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
01519         return evaluateICmpRelation(CE1Op0,
01520                                     Constant::getNullValue(CE1Op0->getType()), 
01521                                     isSigned);
01522       }
01523       break;
01524 
01525     case Instruction::GetElementPtr: {
01526       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
01527       // Ok, since this is a getelementptr, we know that the constant has a
01528       // pointer type.  Check the various cases.
01529       if (isa<ConstantPointerNull>(V2)) {
01530         // If we are comparing a GEP to a null pointer, check to see if the base
01531         // of the GEP equals the null pointer.
01532         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01533           if (GV->hasExternalWeakLinkage())
01534             // Weak linkage GVals could be zero or not. We're comparing that
01535             // to null pointer so its greater-or-equal
01536             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
01537           else 
01538             // If its not weak linkage, the GVal must have a non-zero address
01539             // so the result is greater-than
01540             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01541         } else if (isa<ConstantPointerNull>(CE1Op0)) {
01542           // If we are indexing from a null pointer, check to see if we have any
01543           // non-zero indices.
01544           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
01545             if (!CE1->getOperand(i)->isNullValue())
01546               // Offsetting from null, must not be equal.
01547               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01548           // Only zero indexes from null, must still be zero.
01549           return ICmpInst::ICMP_EQ;
01550         }
01551         // Otherwise, we can't really say if the first operand is null or not.
01552       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
01553         if (isa<ConstantPointerNull>(CE1Op0)) {
01554           if (GV2->hasExternalWeakLinkage())
01555             // Weak linkage GVals could be zero or not. We're comparing it to
01556             // a null pointer, so its less-or-equal
01557             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
01558           else
01559             // If its not weak linkage, the GVal must have a non-zero address
01560             // so the result is less-than
01561             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01562         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01563           if (GV == GV2) {
01564             // If this is a getelementptr of the same global, then it must be
01565             // different.  Because the types must match, the getelementptr could
01566             // only have at most one index, and because we fold getelementptr's
01567             // with a single zero index, it must be nonzero.
01568             assert(CE1->getNumOperands() == 2 &&
01569                    !CE1->getOperand(1)->isNullValue() &&
01570                    "Surprising getelementptr!");
01571             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01572           } else {
01573             if (CE1GEP->hasAllZeroIndices())
01574               return areGlobalsPotentiallyEqual(GV, GV2);
01575             return ICmpInst::BAD_ICMP_PREDICATE;
01576           }
01577         }
01578       } else {
01579         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
01580         Constant *CE2Op0 = CE2->getOperand(0);
01581 
01582         // There are MANY other foldings that we could perform here.  They will
01583         // probably be added on demand, as they seem needed.
01584         switch (CE2->getOpcode()) {
01585         default: break;
01586         case Instruction::GetElementPtr:
01587           // By far the most common case to handle is when the base pointers are
01588           // obviously to the same global.
01589           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
01590             // Don't know relative ordering, but check for inequality.
01591             if (CE1Op0 != CE2Op0) {
01592               GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
01593               if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
01594                 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
01595                                                   cast<GlobalValue>(CE2Op0));
01596               return ICmpInst::BAD_ICMP_PREDICATE;
01597             }
01598             // Ok, we know that both getelementptr instructions are based on the
01599             // same global.  From this, we can precisely determine the relative
01600             // ordering of the resultant pointers.
01601             unsigned i = 1;
01602 
01603             // The logic below assumes that the result of the comparison
01604             // can be determined by finding the first index that differs.
01605             // This doesn't work if there is over-indexing in any
01606             // subsequent indices, so check for that case first.
01607             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
01608                 !CE2->isGEPWithNoNotionalOverIndexing())
01609                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01610 
01611             // Compare all of the operands the GEP's have in common.
01612             gep_type_iterator GTI = gep_type_begin(CE1);
01613             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
01614                  ++i, ++GTI)
01615               switch (IdxCompare(CE1->getOperand(i),
01616                                  CE2->getOperand(i), GTI.getIndexedType())) {
01617               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
01618               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
01619               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
01620               }
01621 
01622             // Ok, we ran out of things they have in common.  If any leftovers
01623             // are non-zero then we have a difference, otherwise we are equal.
01624             for (; i < CE1->getNumOperands(); ++i)
01625               if (!CE1->getOperand(i)->isNullValue()) {
01626                 if (isa<ConstantInt>(CE1->getOperand(i)))
01627                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01628                 else
01629                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01630               }
01631 
01632             for (; i < CE2->getNumOperands(); ++i)
01633               if (!CE2->getOperand(i)->isNullValue()) {
01634                 if (isa<ConstantInt>(CE2->getOperand(i)))
01635                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01636                 else
01637                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01638               }
01639             return ICmpInst::ICMP_EQ;
01640           }
01641         }
01642       }
01643     }
01644     default:
01645       break;
01646     }
01647   }
01648 
01649   return ICmpInst::BAD_ICMP_PREDICATE;
01650 }
01651 
01652 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
01653                                                Constant *C1, Constant *C2) {
01654   Type *ResultTy;
01655   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
01656     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
01657                                VT->getNumElements());
01658   else
01659     ResultTy = Type::getInt1Ty(C1->getContext());
01660 
01661   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
01662   if (pred == FCmpInst::FCMP_FALSE)
01663     return Constant::getNullValue(ResultTy);
01664 
01665   if (pred == FCmpInst::FCMP_TRUE)
01666     return Constant::getAllOnesValue(ResultTy);
01667 
01668   // Handle some degenerate cases first
01669   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
01670     CmpInst::Predicate Predicate = CmpInst::Predicate(pred);
01671     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
01672     // For EQ and NE, we can always pick a value for the undef to make the
01673     // predicate pass or fail, so we can return undef.
01674     // Also, if both operands are undef, we can return undef for int comparison.
01675     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
01676       return UndefValue::get(ResultTy);
01677 
01678     // Otherwise, for integer compare, pick the same value as the non-undef
01679     // operand, and fold it to true or false.
01680     if (isIntegerPredicate)
01681       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
01682 
01683     // Choosing NaN for the undef will always make unordered comparison succeed
01684     // and ordered comparison fails.
01685     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
01686   }
01687 
01688   // icmp eq/ne(null,GV) -> false/true
01689   if (C1->isNullValue()) {
01690     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
01691       // Don't try to evaluate aliases.  External weak GV can be null.
01692       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01693         if (pred == ICmpInst::ICMP_EQ)
01694           return ConstantInt::getFalse(C1->getContext());
01695         else if (pred == ICmpInst::ICMP_NE)
01696           return ConstantInt::getTrue(C1->getContext());
01697       }
01698   // icmp eq/ne(GV,null) -> false/true
01699   } else if (C2->isNullValue()) {
01700     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
01701       // Don't try to evaluate aliases.  External weak GV can be null.
01702       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01703         if (pred == ICmpInst::ICMP_EQ)
01704           return ConstantInt::getFalse(C1->getContext());
01705         else if (pred == ICmpInst::ICMP_NE)
01706           return ConstantInt::getTrue(C1->getContext());
01707       }
01708   }
01709 
01710   // If the comparison is a comparison between two i1's, simplify it.
01711   if (C1->getType()->isIntegerTy(1)) {
01712     switch(pred) {
01713     case ICmpInst::ICMP_EQ:
01714       if (isa<ConstantInt>(C2))
01715         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
01716       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
01717     case ICmpInst::ICMP_NE:
01718       return ConstantExpr::getXor(C1, C2);
01719     default:
01720       break;
01721     }
01722   }
01723 
01724   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
01725     APInt V1 = cast<ConstantInt>(C1)->getValue();
01726     APInt V2 = cast<ConstantInt>(C2)->getValue();
01727     switch (pred) {
01728     default: llvm_unreachable("Invalid ICmp Predicate");
01729     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
01730     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
01731     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
01732     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
01733     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
01734     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
01735     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
01736     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
01737     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
01738     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
01739     }
01740   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
01741     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
01742     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
01743     APFloat::cmpResult R = C1V.compare(C2V);
01744     switch (pred) {
01745     default: llvm_unreachable("Invalid FCmp Predicate");
01746     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
01747     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
01748     case FCmpInst::FCMP_UNO:
01749       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
01750     case FCmpInst::FCMP_ORD:
01751       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
01752     case FCmpInst::FCMP_UEQ:
01753       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01754                                         R==APFloat::cmpEqual);
01755     case FCmpInst::FCMP_OEQ:   
01756       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
01757     case FCmpInst::FCMP_UNE:
01758       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
01759     case FCmpInst::FCMP_ONE:   
01760       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
01761                                         R==APFloat::cmpGreaterThan);
01762     case FCmpInst::FCMP_ULT: 
01763       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01764                                         R==APFloat::cmpLessThan);
01765     case FCmpInst::FCMP_OLT:   
01766       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
01767     case FCmpInst::FCMP_UGT:
01768       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01769                                         R==APFloat::cmpGreaterThan);
01770     case FCmpInst::FCMP_OGT:
01771       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
01772     case FCmpInst::FCMP_ULE:
01773       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
01774     case FCmpInst::FCMP_OLE: 
01775       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
01776                                         R==APFloat::cmpEqual);
01777     case FCmpInst::FCMP_UGE:
01778       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
01779     case FCmpInst::FCMP_OGE: 
01780       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
01781                                         R==APFloat::cmpEqual);
01782     }
01783   } else if (C1->getType()->isVectorTy()) {
01784     // If we can constant fold the comparison of each element, constant fold
01785     // the whole vector comparison.
01786     SmallVector<Constant*, 4> ResElts;
01787     Type *Ty = IntegerType::get(C1->getContext(), 32);
01788     // Compare the elements, producing an i1 result or constant expr.
01789     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
01790       Constant *C1E =
01791         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
01792       Constant *C2E =
01793         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
01794       
01795       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
01796     }
01797     
01798     return ConstantVector::get(ResElts);
01799   }
01800 
01801   if (C1->getType()->isFloatingPointTy() &&
01802       // Only call evaluateFCmpRelation if we have a constant expr to avoid
01803       // infinite recursive loop
01804       (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
01805     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01806     switch (evaluateFCmpRelation(C1, C2)) {
01807     default: llvm_unreachable("Unknown relation!");
01808     case FCmpInst::FCMP_UNO:
01809     case FCmpInst::FCMP_ORD:
01810     case FCmpInst::FCMP_UEQ:
01811     case FCmpInst::FCMP_UNE:
01812     case FCmpInst::FCMP_ULT:
01813     case FCmpInst::FCMP_UGT:
01814     case FCmpInst::FCMP_ULE:
01815     case FCmpInst::FCMP_UGE:
01816     case FCmpInst::FCMP_TRUE:
01817     case FCmpInst::FCMP_FALSE:
01818     case FCmpInst::BAD_FCMP_PREDICATE:
01819       break; // Couldn't determine anything about these constants.
01820     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
01821       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
01822                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
01823                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01824       break;
01825     case FCmpInst::FCMP_OLT: // We know that C1 < C2
01826       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01827                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
01828                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
01829       break;
01830     case FCmpInst::FCMP_OGT: // We know that C1 > C2
01831       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01832                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
01833                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01834       break;
01835     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
01836       // We can only partially decide this relation.
01837       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01838         Result = 0;
01839       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01840         Result = 1;
01841       break;
01842     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
01843       // We can only partially decide this relation.
01844       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01845         Result = 0;
01846       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01847         Result = 1;
01848       break;
01849     case FCmpInst::FCMP_ONE: // We know that C1 != C2
01850       // We can only partially decide this relation.
01851       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
01852         Result = 0;
01853       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
01854         Result = 1;
01855       break;
01856     }
01857 
01858     // If we evaluated the result, return it now.
01859     if (Result != -1)
01860       return ConstantInt::get(ResultTy, Result);
01861 
01862   } else {
01863     // Evaluate the relation between the two constants, per the predicate.
01864     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01865     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
01866     default: llvm_unreachable("Unknown relational!");
01867     case ICmpInst::BAD_ICMP_PREDICATE:
01868       break;  // Couldn't determine anything about these constants.
01869     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
01870       // If we know the constants are equal, we can decide the result of this
01871       // computation precisely.
01872       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
01873       break;
01874     case ICmpInst::ICMP_ULT:
01875       switch (pred) {
01876       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
01877         Result = 1; break;
01878       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
01879         Result = 0; break;
01880       }
01881       break;
01882     case ICmpInst::ICMP_SLT:
01883       switch (pred) {
01884       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
01885         Result = 1; break;
01886       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
01887         Result = 0; break;
01888       }
01889       break;
01890     case ICmpInst::ICMP_UGT:
01891       switch (pred) {
01892       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
01893         Result = 1; break;
01894       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
01895         Result = 0; break;
01896       }
01897       break;
01898     case ICmpInst::ICMP_SGT:
01899       switch (pred) {
01900       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
01901         Result = 1; break;
01902       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
01903         Result = 0; break;
01904       }
01905       break;
01906     case ICmpInst::ICMP_ULE:
01907       if (pred == ICmpInst::ICMP_UGT) Result = 0;
01908       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
01909       break;
01910     case ICmpInst::ICMP_SLE:
01911       if (pred == ICmpInst::ICMP_SGT) Result = 0;
01912       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
01913       break;
01914     case ICmpInst::ICMP_UGE:
01915       if (pred == ICmpInst::ICMP_ULT) Result = 0;
01916       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
01917       break;
01918     case ICmpInst::ICMP_SGE:
01919       if (pred == ICmpInst::ICMP_SLT) Result = 0;
01920       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
01921       break;
01922     case ICmpInst::ICMP_NE:
01923       if (pred == ICmpInst::ICMP_EQ) Result = 0;
01924       if (pred == ICmpInst::ICMP_NE) Result = 1;
01925       break;
01926     }
01927 
01928     // If we evaluated the result, return it now.
01929     if (Result != -1)
01930       return ConstantInt::get(ResultTy, Result);
01931 
01932     // If the right hand side is a bitcast, try using its inverse to simplify
01933     // it by moving it to the left hand side.  We can't do this if it would turn
01934     // a vector compare into a scalar compare or visa versa.
01935     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
01936       Constant *CE2Op0 = CE2->getOperand(0);
01937       if (CE2->getOpcode() == Instruction::BitCast &&
01938           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
01939         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
01940         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
01941       }
01942     }
01943 
01944     // If the left hand side is an extension, try eliminating it.
01945     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01946       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
01947           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
01948         Constant *CE1Op0 = CE1->getOperand(0);
01949         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
01950         if (CE1Inverse == CE1Op0) {
01951           // Check whether we can safely truncate the right hand side.
01952           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
01953           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
01954                                     C2->getType()) == C2)
01955             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
01956         }
01957       }
01958     }
01959 
01960     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
01961         (C1->isNullValue() && !C2->isNullValue())) {
01962       // If C2 is a constant expr and C1 isn't, flip them around and fold the
01963       // other way if possible.
01964       // Also, if C1 is null and C2 isn't, flip them around.
01965       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
01966       return ConstantExpr::getICmp(pred, C2, C1);
01967     }
01968   }
01969   return nullptr;
01970 }
01971 
01972 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
01973 /// is "inbounds".
01974 template<typename IndexTy>
01975 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
01976   // No indices means nothing that could be out of bounds.
01977   if (Idxs.empty()) return true;
01978 
01979   // If the first index is zero, it's in bounds.
01980   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
01981 
01982   // If the first index is one and all the rest are zero, it's in bounds,
01983   // by the one-past-the-end rule.
01984   if (!cast<ConstantInt>(Idxs[0])->isOne())
01985     return false;
01986   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
01987     if (!cast<Constant>(Idxs[i])->isNullValue())
01988       return false;
01989   return true;
01990 }
01991 
01992 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
01993 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
01994                                            const ConstantInt *CI) {
01995   if (const PointerType *PTy = dyn_cast<PointerType>(STy))
01996     // Only handle pointers to sized types, not pointers to functions.
01997     return PTy->getElementType()->isSized();
01998 
01999   uint64_t NumElements = 0;
02000   // Determine the number of elements in our sequential type.
02001   if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
02002     NumElements = ATy->getNumElements();
02003   else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
02004     NumElements = VTy->getNumElements();
02005 
02006   assert((isa<ArrayType>(STy) || NumElements > 0) &&
02007          "didn't expect non-array type to have zero elements!");
02008 
02009   // We cannot bounds check the index if it doesn't fit in an int64_t.
02010   if (CI->getValue().getActiveBits() > 64)
02011     return false;
02012 
02013   // A negative index or an index past the end of our sequential type is
02014   // considered out-of-range.
02015   int64_t IndexVal = CI->getSExtValue();
02016   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
02017     return false;
02018 
02019   // Otherwise, it is in-range.
02020   return true;
02021 }
02022 
02023 template<typename IndexTy>
02024 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
02025                                                bool inBounds,
02026                                                ArrayRef<IndexTy> Idxs) {
02027   if (Idxs.empty()) return C;
02028   Constant *Idx0 = cast<Constant>(Idxs[0]);
02029   if ((Idxs.size() == 1 && Idx0->isNullValue()))
02030     return C;
02031 
02032   if (isa<UndefValue>(C)) {
02033     PointerType *Ptr = cast<PointerType>(C->getType());
02034     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
02035     assert(Ty && "Invalid indices for GEP!");
02036     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
02037   }
02038 
02039   if (C->isNullValue()) {
02040     bool isNull = true;
02041     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
02042       if (!cast<Constant>(Idxs[i])->isNullValue()) {
02043         isNull = false;
02044         break;
02045       }
02046     if (isNull) {
02047       PointerType *Ptr = cast<PointerType>(C->getType());
02048       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
02049       assert(Ty && "Invalid indices for GEP!");
02050       return ConstantPointerNull::get(PointerType::get(Ty,
02051                                                        Ptr->getAddressSpace()));
02052     }
02053   }
02054 
02055   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
02056     // Combine Indices - If the source pointer to this getelementptr instruction
02057     // is a getelementptr instruction, combine the indices of the two
02058     // getelementptr instructions into a single instruction.
02059     //
02060     if (CE->getOpcode() == Instruction::GetElementPtr) {
02061       Type *LastTy = nullptr;
02062       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
02063            I != E; ++I)
02064         LastTy = *I;
02065 
02066       // We cannot combine indices if doing so would take us outside of an
02067       // array or vector.  Doing otherwise could trick us if we evaluated such a
02068       // GEP as part of a load.
02069       //
02070       // e.g. Consider if the original GEP was:
02071       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
02072       //                    i32 0, i32 0, i64 0)
02073       //
02074       // If we then tried to offset it by '8' to get to the third element,
02075       // an i8, we should *not* get:
02076       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
02077       //                    i32 0, i32 0, i64 8)
02078       //
02079       // This GEP tries to index array element '8  which runs out-of-bounds.
02080       // Subsequent evaluation would get confused and produce erroneous results.
02081       //
02082       // The following prohibits such a GEP from being formed by checking to see
02083       // if the index is in-range with respect to an array or vector.
02084       bool PerformFold = false;
02085       if (Idx0->isNullValue())
02086         PerformFold = true;
02087       else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
02088         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
02089           PerformFold = isIndexInRangeOfSequentialType(STy, CI);
02090 
02091       if (PerformFold) {
02092         SmallVector<Value*, 16> NewIndices;
02093         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
02094         NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
02095 
02096         // Add the last index of the source with the first index of the new GEP.
02097         // Make sure to handle the case when they are actually different types.
02098         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
02099         // Otherwise it must be an array.
02100         if (!Idx0->isNullValue()) {
02101           Type *IdxTy = Combined->getType();
02102           if (IdxTy != Idx0->getType()) {
02103             unsigned CommonExtendedWidth =
02104                 std::max(IdxTy->getIntegerBitWidth(),
02105                          Idx0->getType()->getIntegerBitWidth());
02106             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
02107 
02108             Type *CommonTy =
02109                 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
02110             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
02111             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
02112             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
02113           } else {
02114             Combined =
02115               ConstantExpr::get(Instruction::Add, Idx0, Combined);
02116           }
02117         }
02118 
02119         NewIndices.push_back(Combined);
02120         NewIndices.append(Idxs.begin() + 1, Idxs.end());
02121         return
02122           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
02123                                          inBounds &&
02124                                            cast<GEPOperator>(CE)->isInBounds());
02125       }
02126     }
02127 
02128     // Attempt to fold casts to the same type away.  For example, folding:
02129     //
02130     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
02131     //                       i64 0, i64 0)
02132     // into:
02133     //
02134     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
02135     //
02136     // Don't fold if the cast is changing address spaces.
02137     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
02138       PointerType *SrcPtrTy =
02139         dyn_cast<PointerType>(CE->getOperand(0)->getType());
02140       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
02141       if (SrcPtrTy && DstPtrTy) {
02142         ArrayType *SrcArrayTy =
02143           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
02144         ArrayType *DstArrayTy =
02145           dyn_cast<ArrayType>(DstPtrTy->getElementType());
02146         if (SrcArrayTy && DstArrayTy
02147             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
02148             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
02149           return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
02150                                                 Idxs, inBounds);
02151       }
02152     }
02153   }
02154 
02155   // Check to see if any array indices are not within the corresponding
02156   // notional array or vector bounds. If so, try to determine if they can be
02157   // factored out into preceding dimensions.
02158   bool Unknown = false;
02159   SmallVector<Constant *, 8> NewIdxs;
02160   Type *Ty = C->getType();
02161   Type *Prev = nullptr;
02162   for (unsigned i = 0, e = Idxs.size(); i != e;
02163        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
02164     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
02165       if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
02166         if (CI->getSExtValue() > 0 &&
02167             !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
02168           if (isa<SequentialType>(Prev)) {
02169             // It's out of range, but we can factor it into the prior
02170             // dimension.
02171             NewIdxs.resize(Idxs.size());
02172             uint64_t NumElements = 0;
02173             if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
02174               NumElements = ATy->getNumElements();
02175             else
02176               NumElements = cast<VectorType>(Ty)->getNumElements();
02177 
02178             ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
02179             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
02180 
02181             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
02182             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
02183 
02184             unsigned CommonExtendedWidth =
02185                 std::max(PrevIdx->getType()->getIntegerBitWidth(),
02186                          Div->getType()->getIntegerBitWidth());
02187             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
02188 
02189             // Before adding, extend both operands to i64 to avoid
02190             // overflow trouble.
02191             if (!PrevIdx->getType()->isIntegerTy(CommonExtendedWidth))
02192               PrevIdx = ConstantExpr::getSExt(
02193                   PrevIdx,
02194                   Type::getIntNTy(Div->getContext(), CommonExtendedWidth));
02195             if (!Div->getType()->isIntegerTy(CommonExtendedWidth))
02196               Div = ConstantExpr::getSExt(
02197                   Div, Type::getIntNTy(Div->getContext(), CommonExtendedWidth));
02198 
02199             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
02200           } else {
02201             // It's out of range, but the prior dimension is a struct
02202             // so we can't do anything about it.
02203             Unknown = true;
02204           }
02205         }
02206     } else {
02207       // We don't know if it's in range or not.
02208       Unknown = true;
02209     }
02210   }
02211 
02212   // If we did any factoring, start over with the adjusted indices.
02213   if (!NewIdxs.empty()) {
02214     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
02215       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
02216     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
02217   }
02218 
02219   // If all indices are known integers and normalized, we can do a simple
02220   // check for the "inbounds" property.
02221   if (!Unknown && !inBounds)
02222     if (auto *GV = dyn_cast<GlobalVariable>(C))
02223       if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
02224         return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
02225 
02226   return nullptr;
02227 }
02228 
02229 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
02230                                           bool inBounds,
02231                                           ArrayRef<Constant *> Idxs) {
02232   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
02233 }
02234 
02235 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
02236                                           bool inBounds,
02237                                           ArrayRef<Value *> Idxs) {
02238   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
02239 }