LLVM API Documentation

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 // template-based folder for simple primitive constants like ConstantInt, and
00016 // the special case hackery that we use to symbolically evaluate expressions
00017 // that use ConstantExprs.
00018 //
00019 //===----------------------------------------------------------------------===//
00020 
00021 #include "ConstantFold.h"
00022 #include "llvm/Constants.h"
00023 #include "llvm/Instructions.h"
00024 #include "llvm/DerivedTypes.h"
00025 #include "llvm/Function.h"
00026 #include "llvm/GlobalAlias.h"
00027 #include "llvm/ADT/SmallVector.h"
00028 #include "llvm/Support/Compiler.h"
00029 #include "llvm/Support/GetElementPtrTypeIterator.h"
00030 #include "llvm/Support/ManagedStatic.h"
00031 #include "llvm/Support/MathExtras.h"
00032 #include <limits>
00033 using namespace llvm;
00034 
00035 //===----------------------------------------------------------------------===//
00036 //                ConstantFold*Instruction Implementations
00037 //===----------------------------------------------------------------------===//
00038 
00039 /// BitCastConstantVector - Convert the specified ConstantVector node to the
00040 /// specified vector type.  At this point, we know that the elements of the
00041 /// input vector constant are all simple integer or FP values.
00042 static Constant *BitCastConstantVector(ConstantVector *CV,
00043                                        const VectorType *DstTy) {
00044   // If this cast changes element count then we can't handle it here:
00045   // doing so requires endianness information.  This should be handled by
00046   // Analysis/ConstantFolding.cpp
00047   unsigned NumElts = DstTy->getNumElements();
00048   if (NumElts != CV->getNumOperands())
00049     return 0;
00050   
00051   // Check to verify that all elements of the input are simple.
00052   for (unsigned i = 0; i != NumElts; ++i) {
00053     if (!isa<ConstantInt>(CV->getOperand(i)) &&
00054         !isa<ConstantFP>(CV->getOperand(i)))
00055       return 0;
00056   }
00057 
00058   // Bitcast each element now.
00059   std::vector<Constant*> Result;
00060   const Type *DstEltTy = DstTy->getElementType();
00061   for (unsigned i = 0; i != NumElts; ++i)
00062     Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
00063   return ConstantVector::get(Result);
00064 }
00065 
00066 /// This function determines which opcode to use to fold two constant cast 
00067 /// expressions together. It uses CastInst::isEliminableCastPair to determine
00068 /// the opcode. Consequently its just a wrapper around that function.
00069 /// @brief Determine if it is valid to fold a cast of a cast
00070 static unsigned
00071 foldConstantCastPair(
00072   unsigned opc,          ///< opcode of the second cast constant expression
00073   const ConstantExpr*Op, ///< the first cast constant expression
00074   const Type *DstTy      ///< desintation type of the first cast
00075 ) {
00076   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
00077   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
00078   assert(CastInst::isCast(opc) && "Invalid cast opcode");
00079   
00080   // The the types and opcodes for the two Cast constant expressions
00081   const Type *SrcTy = Op->getOperand(0)->getType();
00082   const Type *MidTy = Op->getType();
00083   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
00084   Instruction::CastOps secondOp = Instruction::CastOps(opc);
00085 
00086   // Let CastInst::isEliminableCastPair do the heavy lifting.
00087   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
00088                                         Type::Int64Ty);
00089 }
00090 
00091 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
00092   const Type *SrcTy = V->getType();
00093   if (SrcTy == DestTy)
00094     return V; // no-op cast
00095   
00096   // Check to see if we are casting a pointer to an aggregate to a pointer to
00097   // the first element.  If so, return the appropriate GEP instruction.
00098   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
00099     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
00100       if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
00101         SmallVector<Value*, 8> IdxList;
00102         IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
00103         const Type *ElTy = PTy->getElementType();
00104         while (ElTy != DPTy->getElementType()) {
00105           if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
00106             if (STy->getNumElements() == 0) break;
00107             ElTy = STy->getElementType(0);
00108             IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
00109           } else if (const SequentialType *STy = 
00110                      dyn_cast<SequentialType>(ElTy)) {
00111             if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
00112             ElTy = STy->getElementType();
00113             IdxList.push_back(IdxList[0]);
00114           } else {
00115             break;
00116           }
00117         }
00118         
00119         if (ElTy == DPTy->getElementType())
00120           return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
00121       }
00122   
00123   // Handle casts from one vector constant to another.  We know that the src 
00124   // and dest type have the same size (otherwise its an illegal cast).
00125   if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
00126     if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
00127       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
00128              "Not cast between same sized vectors!");
00129       SrcTy = NULL;
00130       // First, check for null.  Undef is already handled.
00131       if (isa<ConstantAggregateZero>(V))
00132         return Constant::getNullValue(DestTy);
00133       
00134       if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
00135         return BitCastConstantVector(CV, DestPTy);
00136     }
00137 
00138     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
00139     // This allows for other simplifications (although some of them
00140     // can only be handled by Analysis/ConstantFolding.cpp).
00141     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
00142       return ConstantExpr::getBitCast(ConstantVector::get(&V, 1), DestPTy);
00143   }
00144   
00145   // Finally, implement bitcast folding now.   The code below doesn't handle
00146   // bitcast right.
00147   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
00148     return ConstantPointerNull::get(cast<PointerType>(DestTy));
00149   
00150   // Handle integral constant input.
00151   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00152     if (DestTy->isInteger())
00153       // Integral -> Integral. This is a no-op because the bit widths must
00154       // be the same. Consequently, we just fold to V.
00155       return V;
00156     
00157     if (DestTy->isFloatingPoint()) {
00158       assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) && 
00159              "Unknown FP type!");
00160       return ConstantFP::get(APFloat(CI->getValue()));
00161     }
00162     // Otherwise, can't fold this (vector?)
00163     return 0;
00164   }
00165   
00166   // Handle ConstantFP input.
00167   if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
00168     // FP -> Integral.
00169     if (DestTy == Type::Int32Ty) {
00170       return ConstantInt::get(FP->getValueAPF().bitcastToAPInt());
00171     } else {
00172       assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
00173       return ConstantInt::get(FP->getValueAPF().bitcastToAPInt());
00174     }
00175   }
00176   return 0;
00177 }
00178 
00179 
00180 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
00181                                             const Type *DestTy) {
00182   if (isa<UndefValue>(V)) {
00183     // zext(undef) = 0, because the top bits will be zero.
00184     // sext(undef) = 0, because the top bits will all be the same.
00185     // [us]itofp(undef) = 0, because the result value is bounded.
00186     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
00187         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
00188       return Constant::getNullValue(DestTy);
00189     return UndefValue::get(DestTy);
00190   }
00191   // No compile-time operations on this type yet.
00192   if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
00193     return 0;
00194 
00195   // If the cast operand is a constant expression, there's a few things we can
00196   // do to try to simplify it.
00197   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00198     if (CE->isCast()) {
00199       // Try hard to fold cast of cast because they are often eliminable.
00200       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
00201         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
00202     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
00203       // If all of the indexes in the GEP are null values, there is no pointer
00204       // adjustment going on.  We might as well cast the source pointer.
00205       bool isAllNull = true;
00206       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
00207         if (!CE->getOperand(i)->isNullValue()) {
00208           isAllNull = false;
00209           break;
00210         }
00211       if (isAllNull)
00212         // This is casting one pointer type to another, always BitCast
00213         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
00214     }
00215   }
00216 
00217   // We actually have to do a cast now. Perform the cast according to the
00218   // opcode specified.
00219   switch (opc) {
00220   case Instruction::FPTrunc:
00221   case Instruction::FPExt:
00222     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
00223       bool ignored;
00224       APFloat Val = FPC->getValueAPF();
00225       Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
00226                   DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
00227                   DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
00228                   DestTy == Type::FP128Ty ? APFloat::IEEEquad :
00229                   APFloat::Bogus,
00230                   APFloat::rmNearestTiesToEven, &ignored);
00231       return ConstantFP::get(Val);
00232     }
00233     return 0; // Can't fold.
00234   case Instruction::FPToUI: 
00235   case Instruction::FPToSI:
00236     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
00237       const APFloat &V = FPC->getValueAPF();
00238       bool ignored;
00239       uint64_t x[2]; 
00240       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00241       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
00242                                 APFloat::rmTowardZero, &ignored);
00243       APInt Val(DestBitWidth, 2, x);
00244       return ConstantInt::get(Val);
00245     }
00246     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
00247       std::vector<Constant*> res;
00248       const VectorType *DestVecTy = cast<VectorType>(DestTy);
00249       const Type *DstEltTy = DestVecTy->getElementType();
00250       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
00251         res.push_back(ConstantExpr::getCast(opc, CV->getOperand(i), DstEltTy));
00252       return ConstantVector::get(DestVecTy, res);
00253     }
00254     return 0; // Can't fold.
00255   case Instruction::IntToPtr:   //always treated as unsigned
00256     if (V->isNullValue())       // Is it an integral null value?
00257       return ConstantPointerNull::get(cast<PointerType>(DestTy));
00258     return 0;                   // Other pointer types cannot be casted
00259   case Instruction::PtrToInt:   // always treated as unsigned
00260     if (V->isNullValue())       // is it a null pointer value?
00261       return ConstantInt::get(DestTy, 0);
00262     return 0;                   // Other pointer types cannot be casted
00263   case Instruction::UIToFP:
00264   case Instruction::SIToFP:
00265     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00266       APInt api = CI->getValue();
00267       const uint64_t zero[] = {0, 0};
00268       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
00269                                   2, zero));
00270       (void)apf.convertFromAPInt(api, 
00271                                  opc==Instruction::SIToFP,
00272                                  APFloat::rmNearestTiesToEven);
00273       return ConstantFP::get(apf);
00274     }
00275     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
00276       std::vector<Constant*> res;
00277       const VectorType *DestVecTy = cast<VectorType>(DestTy);
00278       const Type *DstEltTy = DestVecTy->getElementType();
00279       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
00280         res.push_back(ConstantExpr::getCast(opc, CV->getOperand(i), DstEltTy));
00281       return ConstantVector::get(DestVecTy, res);
00282     }
00283     return 0;
00284   case Instruction::ZExt:
00285     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00286       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00287       APInt Result(CI->getValue());
00288       Result.zext(BitWidth);
00289       return ConstantInt::get(Result);
00290     }
00291     return 0;
00292   case Instruction::SExt:
00293     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00294       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00295       APInt Result(CI->getValue());
00296       Result.sext(BitWidth);
00297       return ConstantInt::get(Result);
00298     }
00299     return 0;
00300   case Instruction::Trunc:
00301     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00302       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00303       APInt Result(CI->getValue());
00304       Result.trunc(BitWidth);
00305       return ConstantInt::get(Result);
00306     }
00307     return 0;
00308   case Instruction::BitCast:
00309     return FoldBitCast(const_cast<Constant*>(V), DestTy);
00310   default:
00311     assert(!"Invalid CE CastInst opcode");
00312     break;
00313   }
00314 
00315   assert(0 && "Failed to cast constant expression");
00316   return 0;
00317 }
00318 
00319 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
00320                                               const Constant *V1,
00321                                               const Constant *V2) {
00322   if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
00323     return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
00324 
00325   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
00326   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
00327   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
00328   if (V1 == V2) return const_cast<Constant*>(V1);
00329   return 0;
00330 }
00331 
00332 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
00333                                                       const Constant *Idx) {
00334   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
00335     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
00336   if (Val->isNullValue())  // ee(zero, x) -> zero
00337     return Constant::getNullValue(
00338                           cast<VectorType>(Val->getType())->getElementType());
00339   
00340   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
00341     if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
00342       return CVal->getOperand(CIdx->getZExtValue());
00343     } else if (isa<UndefValue>(Idx)) {
00344       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
00345       return CVal->getOperand(0);
00346     }
00347   }
00348   return 0;
00349 }
00350 
00351 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
00352                                                      const Constant *Elt,
00353                                                      const Constant *Idx) {
00354   const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
00355   if (!CIdx) return 0;
00356   APInt idxVal = CIdx->getValue();
00357   if (isa<UndefValue>(Val)) { 
00358     // Insertion of scalar constant into vector undef
00359     // Optimize away insertion of undef
00360     if (isa<UndefValue>(Elt))
00361       return const_cast<Constant*>(Val);
00362     // Otherwise break the aggregate undef into multiple undefs and do
00363     // the insertion
00364     unsigned numOps = 
00365       cast<VectorType>(Val->getType())->getNumElements();
00366     std::vector<Constant*> Ops; 
00367     Ops.reserve(numOps);
00368     for (unsigned i = 0; i < numOps; ++i) {
00369       const Constant *Op =
00370         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
00371       Ops.push_back(const_cast<Constant*>(Op));
00372     }
00373     return ConstantVector::get(Ops);
00374   }
00375   if (isa<ConstantAggregateZero>(Val)) {
00376     // Insertion of scalar constant into vector aggregate zero
00377     // Optimize away insertion of zero
00378     if (Elt->isNullValue())
00379       return const_cast<Constant*>(Val);
00380     // Otherwise break the aggregate zero into multiple zeros and do
00381     // the insertion
00382     unsigned numOps = 
00383       cast<VectorType>(Val->getType())->getNumElements();
00384     std::vector<Constant*> Ops; 
00385     Ops.reserve(numOps);
00386     for (unsigned i = 0; i < numOps; ++i) {
00387       const Constant *Op =
00388         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
00389       Ops.push_back(const_cast<Constant*>(Op));
00390     }
00391     return ConstantVector::get(Ops);
00392   }
00393   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
00394     // Insertion of scalar constant into vector constant
00395     std::vector<Constant*> Ops; 
00396     Ops.reserve(CVal->getNumOperands());
00397     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
00398       const Constant *Op =
00399         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
00400       Ops.push_back(const_cast<Constant*>(Op));
00401     }
00402     return ConstantVector::get(Ops);
00403   }
00404 
00405   return 0;
00406 }
00407 
00408 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
00409 /// return the specified element value.  Otherwise return null.
00410 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
00411   if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
00412     return CV->getOperand(EltNo);
00413   
00414   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
00415   if (isa<ConstantAggregateZero>(C))
00416     return Constant::getNullValue(EltTy);
00417   if (isa<UndefValue>(C))
00418     return UndefValue::get(EltTy);
00419   return 0;
00420 }
00421 
00422 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
00423                                                      const Constant *V2,
00424                                                      const Constant *Mask) {
00425   // Undefined shuffle mask -> undefined value.
00426   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
00427 
00428   unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
00429   unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
00430   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
00431 
00432   // Loop over the shuffle mask, evaluating each element.
00433   SmallVector<Constant*, 32> Result;
00434   for (unsigned i = 0; i != MaskNumElts; ++i) {
00435     Constant *InElt = GetVectorElement(Mask, i);
00436     if (InElt == 0) return 0;
00437 
00438     if (isa<UndefValue>(InElt))
00439       InElt = UndefValue::get(EltTy);
00440     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
00441       unsigned Elt = CI->getZExtValue();
00442       if (Elt >= SrcNumElts*2)
00443         InElt = UndefValue::get(EltTy);
00444       else if (Elt >= SrcNumElts)
00445         InElt = GetVectorElement(V2, Elt - SrcNumElts);
00446       else
00447         InElt = GetVectorElement(V1, Elt);
00448       if (InElt == 0) return 0;
00449     } else {
00450       // Unknown value.
00451       return 0;
00452     }
00453     Result.push_back(InElt);
00454   }
00455 
00456   return ConstantVector::get(&Result[0], Result.size());
00457 }
00458 
00459 Constant *llvm::ConstantFoldExtractValueInstruction(const Constant *Agg,
00460                                                     const unsigned *Idxs,
00461                                                     unsigned NumIdx) {
00462   // Base case: no indices, so return the entire value.
00463   if (NumIdx == 0)
00464     return const_cast<Constant *>(Agg);
00465 
00466   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
00467     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
00468                                                             Idxs,
00469                                                             Idxs + NumIdx));
00470 
00471   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
00472     return
00473       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
00474                                                               Idxs,
00475                                                               Idxs + NumIdx));
00476 
00477   // Otherwise recurse.
00478   return ConstantFoldExtractValueInstruction(Agg->getOperand(*Idxs),
00479                                              Idxs+1, NumIdx-1);
00480 }
00481 
00482 Constant *llvm::ConstantFoldInsertValueInstruction(const Constant *Agg,
00483                                                    const Constant *Val,
00484                                                    const unsigned *Idxs,
00485                                                    unsigned NumIdx) {
00486   // Base case: no indices, so replace the entire value.
00487   if (NumIdx == 0)
00488     return const_cast<Constant *>(Val);
00489 
00490   if (isa<UndefValue>(Agg)) {
00491     // Insertion of constant into aggregate undef
00492     // Optimize away insertion of undef
00493     if (isa<UndefValue>(Val))
00494       return const_cast<Constant*>(Agg);
00495     // Otherwise break the aggregate undef into multiple undefs and do
00496     // the insertion
00497     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
00498     unsigned numOps;
00499     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
00500       numOps = AR->getNumElements();
00501     else
00502       numOps = cast<StructType>(AggTy)->getNumElements();
00503     std::vector<Constant*> Ops(numOps); 
00504     for (unsigned i = 0; i < numOps; ++i) {
00505       const Type *MemberTy = AggTy->getTypeAtIndex(i);
00506       const Constant *Op =
00507         (*Idxs == i) ?
00508         ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
00509                                            Val, Idxs+1, NumIdx-1) :
00510         UndefValue::get(MemberTy);
00511       Ops[i] = const_cast<Constant*>(Op);
00512     }
00513     if (isa<StructType>(AggTy))
00514       return ConstantStruct::get(Ops);
00515     else
00516       return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
00517   }
00518   if (isa<ConstantAggregateZero>(Agg)) {
00519     // Insertion of constant into aggregate zero
00520     // Optimize away insertion of zero
00521     if (Val->isNullValue())
00522       return const_cast<Constant*>(Agg);
00523     // Otherwise break the aggregate zero into multiple zeros and do
00524     // the insertion
00525     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
00526     unsigned numOps;
00527     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
00528       numOps = AR->getNumElements();
00529     else
00530       numOps = cast<StructType>(AggTy)->getNumElements();
00531     std::vector<Constant*> Ops(numOps);
00532     for (unsigned i = 0; i < numOps; ++i) {
00533       const Type *MemberTy = AggTy->getTypeAtIndex(i);
00534       const Constant *Op =
00535         (*Idxs == i) ?
00536         ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
00537                                            Val, Idxs+1, NumIdx-1) :
00538         Constant::getNullValue(MemberTy);
00539       Ops[i] = const_cast<Constant*>(Op);
00540     }
00541     if (isa<StructType>(AggTy))
00542       return ConstantStruct::get(Ops);
00543     else
00544       return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
00545   }
00546   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
00547     // Insertion of constant into aggregate constant
00548     std::vector<Constant*> Ops(Agg->getNumOperands());
00549     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
00550       const Constant *Op =
00551         (*Idxs == i) ?
00552         ConstantFoldInsertValueInstruction(Agg->getOperand(i),
00553                                            Val, Idxs+1, NumIdx-1) :
00554         Agg->getOperand(i);
00555       Ops[i] = const_cast<Constant*>(Op);
00556     }
00557     Constant *C;
00558     if (isa<StructType>(Agg->getType()))
00559       C = ConstantStruct::get(Ops);
00560     else
00561       C = ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
00562     return C;
00563   }
00564 
00565   return 0;
00566 }
00567 
00568 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
00569 /// function pointer to each element pair, producing a new ConstantVector
00570 /// constant. Either or both of V1 and V2 may be NULL, meaning a
00571 /// ConstantAggregateZero operand.
00572 static Constant *EvalVectorOp(const ConstantVector *V1, 
00573                               const ConstantVector *V2,
00574                               const VectorType *VTy,
00575                               Constant *(*FP)(Constant*, Constant*)) {
00576   std::vector<Constant*> Res;
00577   const Type *EltTy = VTy->getElementType();
00578   for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
00579     const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
00580     const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
00581     Res.push_back(FP(const_cast<Constant*>(C1),
00582                      const_cast<Constant*>(C2)));
00583   }
00584   return ConstantVector::get(Res);
00585 }
00586 
00587 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
00588                                               const Constant *C1,
00589                                               const Constant *C2) {
00590   // No compile-time operations on this type yet.
00591   if (C1->getType() == Type::PPC_FP128Ty)
00592     return 0;
00593 
00594   // Handle UndefValue up front
00595   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
00596     switch (Opcode) {
00597     case Instruction::Xor:
00598       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00599         // Handle undef ^ undef -> 0 special case. This is a common
00600         // idiom (misuse).
00601         return Constant::getNullValue(C1->getType());
00602       // Fallthrough
00603     case Instruction::Add:
00604     case Instruction::Sub:
00605       return UndefValue::get(C1->getType());
00606     case Instruction::Mul:
00607     case Instruction::And:
00608       return Constant::getNullValue(C1->getType());
00609     case Instruction::UDiv:
00610     case Instruction::SDiv:
00611     case Instruction::FDiv:
00612     case Instruction::URem:
00613     case Instruction::SRem:
00614     case Instruction::FRem:
00615       if (!isa<UndefValue>(C2))                    // undef / X -> 0
00616         return Constant::getNullValue(C1->getType());
00617       return const_cast<Constant*>(C2);            // X / undef -> undef
00618     case Instruction::Or:                          // X | undef -> -1
00619       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
00620         return ConstantVector::getAllOnesValue(PTy);
00621       return ConstantInt::getAllOnesValue(C1->getType());
00622     case Instruction::LShr:
00623       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
00624         return const_cast<Constant*>(C1);           // undef lshr undef -> undef
00625       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
00626                                                     // undef lshr X -> 0
00627     case Instruction::AShr:
00628       if (!isa<UndefValue>(C2))
00629         return const_cast<Constant*>(C1);           // undef ashr X --> undef
00630       else if (isa<UndefValue>(C1)) 
00631         return const_cast<Constant*>(C1);           // undef ashr undef -> undef
00632       else
00633         return const_cast<Constant*>(C1);           // X ashr undef --> X
00634     case Instruction::Shl:
00635       // undef << X -> 0   or   X << undef -> 0
00636       return Constant::getNullValue(C1->getType());
00637     }
00638   }
00639 
00640   // Handle simplifications of the RHS when a constant int.
00641   if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
00642     switch (Opcode) {
00643     case Instruction::Add:
00644       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X + 0 == X
00645       break;
00646     case Instruction::Sub:
00647       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X - 0 == X
00648       break;
00649     case Instruction::Mul:
00650       if (CI2->equalsInt(0)) return const_cast<Constant*>(C2);  // X * 0 == 0
00651       if (CI2->equalsInt(1))
00652         return const_cast<Constant*>(C1);                       // X * 1 == X
00653       break;
00654     case Instruction::UDiv:
00655     case Instruction::SDiv:
00656       if (CI2->equalsInt(1))
00657         return const_cast<Constant*>(C1);                     // X / 1 == X
00658       if (CI2->equalsInt(0))
00659         return UndefValue::get(CI2->getType());               // X / 0 == undef
00660       break;
00661     case Instruction::URem:
00662     case Instruction::SRem:
00663       if (CI2->equalsInt(1))
00664         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
00665       if (CI2->equalsInt(0))
00666         return UndefValue::get(CI2->getType());               // X % 0 == undef
00667       break;
00668     case Instruction::And:
00669       if (CI2->isZero()) return const_cast<Constant*>(C2);    // X & 0 == 0
00670       if (CI2->isAllOnesValue())
00671         return const_cast<Constant*>(C1);                     // X & -1 == X
00672       
00673       if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
00674         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
00675         if (CE1->getOpcode() == Instruction::ZExt) {
00676           unsigned DstWidth = CI2->getType()->getBitWidth();
00677           unsigned SrcWidth =
00678             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
00679           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
00680           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
00681             return const_cast<Constant*>(C1);
00682         }
00683         
00684         // If and'ing the address of a global with a constant, fold it.
00685         if (CE1->getOpcode() == Instruction::PtrToInt && 
00686             isa<GlobalValue>(CE1->getOperand(0))) {
00687           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
00688         
00689           // Functions are at least 4-byte aligned.
00690           unsigned GVAlign = GV->getAlignment();
00691           if (isa<Function>(GV))
00692             GVAlign = std::max(GVAlign, 4U);
00693           
00694           if (GVAlign > 1) {
00695             unsigned DstWidth = CI2->getType()->getBitWidth();
00696             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
00697             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
00698 
00699             // If checking bits we know are clear, return zero.
00700             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
00701               return Constant::getNullValue(CI2->getType());
00702           }
00703         }
00704       }
00705       break;
00706     case Instruction::Or:
00707       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X | 0 == X
00708       if (CI2->isAllOnesValue())
00709         return const_cast<Constant*>(C2);  // X | -1 == -1
00710       break;
00711     case Instruction::Xor:
00712       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X ^ 0 == X
00713       break;
00714     case Instruction::AShr:
00715       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
00716       if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
00717         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
00718           return ConstantExpr::getLShr(const_cast<Constant*>(C1),
00719                                        const_cast<Constant*>(C2));
00720       break;
00721     }
00722   }
00723   
00724   // At this point we know neither constant is an UndefValue.
00725   if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
00726     if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
00727       using namespace APIntOps;
00728       const APInt &C1V = CI1->getValue();
00729       const APInt &C2V = CI2->getValue();
00730       switch (Opcode) {
00731       default:
00732         break;
00733       case Instruction::Add:     
00734         return ConstantInt::get(C1V + C2V);
00735       case Instruction::Sub:     
00736         return ConstantInt::get(C1V - C2V);
00737       case Instruction::Mul:     
00738         return ConstantInt::get(C1V * C2V);
00739       case Instruction::UDiv:
00740         assert(!CI2->isNullValue() && "Div by zero handled above");
00741         return ConstantInt::get(C1V.udiv(C2V));
00742       case Instruction::SDiv:
00743         assert(!CI2->isNullValue() && "Div by zero handled above");
00744         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
00745           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
00746         return ConstantInt::get(C1V.sdiv(C2V));
00747       case Instruction::URem:
00748         assert(!CI2->isNullValue() && "Div by zero handled above");
00749         return ConstantInt::get(C1V.urem(C2V));
00750       case Instruction::SRem:
00751         assert(!CI2->isNullValue() && "Div by zero handled above");
00752         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
00753           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
00754         return ConstantInt::get(C1V.srem(C2V));
00755       case Instruction::And:
00756         return ConstantInt::get(C1V & C2V);
00757       case Instruction::Or:
00758         return ConstantInt::get(C1V | C2V);
00759       case Instruction::Xor:
00760         return ConstantInt::get(C1V ^ C2V);
00761       case Instruction::Shl: {
00762         uint32_t shiftAmt = C2V.getZExtValue();
00763         if (shiftAmt < C1V.getBitWidth())
00764           return ConstantInt::get(C1V.shl(shiftAmt));
00765         else
00766           return UndefValue::get(C1->getType()); // too big shift is undef
00767       }
00768       case Instruction::LShr: {
00769         uint32_t shiftAmt = C2V.getZExtValue();
00770         if (shiftAmt < C1V.getBitWidth())
00771           return ConstantInt::get(C1V.lshr(shiftAmt));
00772         else
00773           return UndefValue::get(C1->getType()); // too big shift is undef
00774       }
00775       case Instruction::AShr: {
00776         uint32_t shiftAmt = C2V.getZExtValue();
00777         if (shiftAmt < C1V.getBitWidth())
00778           return ConstantInt::get(C1V.ashr(shiftAmt));
00779         else
00780           return UndefValue::get(C1->getType()); // too big shift is undef
00781       }
00782       }
00783     }
00784   } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
00785     if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
00786       APFloat C1V = CFP1->getValueAPF();
00787       APFloat C2V = CFP2->getValueAPF();
00788       APFloat C3V = C1V;  // copy for modification
00789       switch (Opcode) {
00790       default:                   
00791         break;
00792       case Instruction::Add:
00793         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
00794         return ConstantFP::get(C3V);
00795       case Instruction::Sub:     
00796         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
00797         return ConstantFP::get(C3V);
00798       case Instruction::Mul:
00799         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
00800         return ConstantFP::get(C3V);
00801       case Instruction::FDiv:
00802         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
00803         return ConstantFP::get(C3V);
00804       case Instruction::FRem:
00805         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
00806         return ConstantFP::get(C3V);
00807       }
00808     }
00809   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
00810     const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
00811     const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
00812     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
00813         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
00814       switch (Opcode) {
00815       default:
00816         break;
00817       case Instruction::Add: 
00818         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
00819       case Instruction::Sub: 
00820         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
00821       case Instruction::Mul: 
00822         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
00823       case Instruction::UDiv:
00824         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
00825       case Instruction::SDiv:
00826         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
00827       case Instruction::FDiv:
00828         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
00829       case Instruction::URem:
00830         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
00831       case Instruction::SRem:
00832         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
00833       case Instruction::FRem:
00834         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
00835       case Instruction::And: 
00836         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
00837       case Instruction::Or:  
00838         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
00839       case Instruction::Xor: 
00840         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
00841       }
00842     }
00843   }
00844 
00845   if (isa<ConstantExpr>(C1)) {
00846     // There are many possible foldings we could do here.  We should probably
00847     // at least fold add of a pointer with an integer into the appropriate
00848     // getelementptr.  This will improve alias analysis a bit.
00849   } else if (isa<ConstantExpr>(C2)) {
00850     // If C2 is a constant expr and C1 isn't, flop them around and fold the
00851     // other way if possible.
00852     switch (Opcode) {
00853     case Instruction::Add:
00854     case Instruction::Mul:
00855     case Instruction::And:
00856     case Instruction::Or:
00857     case Instruction::Xor:
00858       // No change of opcode required.
00859       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
00860       
00861     case Instruction::Shl:
00862     case Instruction::LShr:
00863     case Instruction::AShr:
00864     case Instruction::Sub:
00865     case Instruction::SDiv:
00866     case Instruction::UDiv:
00867     case Instruction::FDiv:
00868     case Instruction::URem:
00869     case Instruction::SRem:
00870     case Instruction::FRem:
00871     default:  // These instructions cannot be flopped around.
00872       break;
00873     }
00874   }
00875   
00876   // We don't know how to fold this.
00877   return 0;
00878 }
00879 
00880 /// isZeroSizedType - This type is zero sized if its an array or structure of
00881 /// zero sized types.  The only leaf zero sized type is an empty structure.
00882 static bool isMaybeZeroSizedType(const Type *Ty) {
00883   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
00884   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00885 
00886     // If all of elements have zero size, this does too.
00887     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00888       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
00889     return true;
00890 
00891   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00892     return isMaybeZeroSizedType(ATy->getElementType());
00893   }
00894   return false;
00895 }
00896 
00897 /// IdxCompare - Compare the two constants as though they were getelementptr
00898 /// indices.  This allows coersion of the types to be the same thing.
00899 ///
00900 /// If the two constants are the "same" (after coersion), return 0.  If the
00901 /// first is less than the second, return -1, if the second is less than the
00902 /// first, return 1.  If the constants are not integral, return -2.
00903 ///
00904 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
00905   if (C1 == C2) return 0;
00906 
00907   // Ok, we found a different index.  If they are not ConstantInt, we can't do
00908   // anything with them.
00909   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
00910     return -2; // don't know!
00911 
00912   // Ok, we have two differing integer indices.  Sign extend them to be the same
00913   // type.  Long is always big enough, so we use it.
00914   if (C1->getType() != Type::Int64Ty)
00915     C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
00916 
00917   if (C2->getType() != Type::Int64Ty)
00918     C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
00919 
00920   if (C1 == C2) return 0;  // They are equal
00921 
00922   // If the type being indexed over is really just a zero sized type, there is
00923   // no pointer difference being made here.
00924   if (isMaybeZeroSizedType(ElTy))
00925     return -2; // dunno.
00926 
00927   // If they are really different, now that they are the same type, then we
00928   // found a difference!
00929   if (cast<ConstantInt>(C1)->getSExtValue() < 
00930       cast<ConstantInt>(C2)->getSExtValue())
00931     return -1;
00932   else
00933     return 1;
00934 }
00935 
00936 /// evaluateFCmpRelation - This function determines if there is anything we can
00937 /// decide about the two constants provided.  This doesn't need to handle simple
00938 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
00939 /// If we can determine that the two constants have a particular relation to 
00940 /// each other, we should return the corresponding FCmpInst predicate, 
00941 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
00942 /// ConstantFoldCompareInstruction.
00943 ///
00944 /// To simplify this code we canonicalize the relation so that the first
00945 /// operand is always the most "complex" of the two.  We consider ConstantFP
00946 /// to be the simplest, and ConstantExprs to be the most complex.
00947 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1, 
00948                                                 const Constant *V2) {
00949   assert(V1->getType() == V2->getType() &&
00950          "Cannot compare values of different types!");
00951 
00952   // No compile-time operations on this type yet.
00953   if (V1->getType() == Type::PPC_FP128Ty)
00954     return FCmpInst::BAD_FCMP_PREDICATE;
00955 
00956   // Handle degenerate case quickly
00957   if (V1 == V2) return FCmpInst::FCMP_OEQ;
00958 
00959   if (!isa<ConstantExpr>(V1)) {
00960     if (!isa<ConstantExpr>(V2)) {
00961       // We distilled thisUse the standard constant folder for a few cases
00962       ConstantInt *R = 0;
00963       Constant *C1 = const_cast<Constant*>(V1);
00964       Constant *C2 = const_cast<Constant*>(V2);
00965       R = dyn_cast<ConstantInt>(
00966                              ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
00967       if (R && !R->isZero()) 
00968         return FCmpInst::FCMP_OEQ;
00969       R = dyn_cast<ConstantInt>(
00970                              ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
00971       if (R && !R->isZero()) 
00972         return FCmpInst::FCMP_OLT;
00973       R = dyn_cast<ConstantInt>(
00974                              ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
00975       if (R && !R->isZero()) 
00976         return FCmpInst::FCMP_OGT;
00977 
00978       // Nothing more we can do
00979       return FCmpInst::BAD_FCMP_PREDICATE;
00980     }
00981     
00982     // If the first operand is simple and second is ConstantExpr, swap operands.
00983     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
00984     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
00985       return FCmpInst::getSwappedPredicate(SwappedRelation);
00986   } else {
00987     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
00988     // constantexpr or a simple constant.
00989     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
00990     switch (CE1->getOpcode()) {
00991     case Instruction::FPTrunc:
00992     case Instruction::FPExt:
00993     case Instruction::UIToFP:
00994     case Instruction::SIToFP:
00995       // We might be able to do something with these but we don't right now.
00996       break;
00997     default:
00998       break;
00999     }
01000   }
01001   // There are MANY other foldings that we could perform here.  They will
01002   // probably be added on demand, as they seem needed.
01003   return FCmpInst::BAD_FCMP_PREDICATE;
01004 }
01005 
01006 /// evaluateICmpRelation - This function determines if there is anything we can
01007 /// decide about the two constants provided.  This doesn't need to handle simple
01008 /// things like integer comparisons, but should instead handle ConstantExprs
01009 /// and GlobalValues.  If we can determine that the two constants have a
01010 /// particular relation to each other, we should return the corresponding ICmp
01011 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
01012 ///
01013 /// To simplify this code we canonicalize the relation so that the first
01014 /// operand is always the most "complex" of the two.  We consider simple
01015 /// constants (like ConstantInt) to be the simplest, followed by
01016 /// GlobalValues, followed by ConstantExpr's (the most complex).
01017 ///
01018 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1, 
01019                                                 const Constant *V2,
01020                                                 bool isSigned) {
01021   assert(V1->getType() == V2->getType() &&
01022          "Cannot compare different types of values!");
01023   if (V1 == V2) return ICmpInst::ICMP_EQ;
01024 
01025   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
01026     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
01027       // We distilled this down to a simple case, use the standard constant
01028       // folder.
01029       ConstantInt *R = 0;
01030       Constant *C1 = const_cast<Constant*>(V1);
01031       Constant *C2 = const_cast<Constant*>(V2);
01032       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
01033       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
01034       if (R && !R->isZero()) 
01035         return pred;
01036       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01037       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
01038       if (R && !R->isZero())
01039         return pred;
01040       pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01041       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
01042       if (R && !R->isZero())
01043         return pred;
01044       
01045       // If we couldn't figure it out, bail.
01046       return ICmpInst::BAD_ICMP_PREDICATE;
01047     }
01048     
01049     // If the first operand is simple, swap operands.
01050     ICmpInst::Predicate SwappedRelation = 
01051       evaluateICmpRelation(V2, V1, isSigned);
01052     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01053       return ICmpInst::getSwappedPredicate(SwappedRelation);
01054 
01055   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
01056     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01057       ICmpInst::Predicate SwappedRelation = 
01058         evaluateICmpRelation(V2, V1, isSigned);
01059       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01060         return ICmpInst::getSwappedPredicate(SwappedRelation);
01061       else
01062         return ICmpInst::BAD_ICMP_PREDICATE;
01063     }
01064 
01065     // Now we know that the RHS is a GlobalValue or simple constant,
01066     // which (since the types must match) means that it's a ConstantPointerNull.
01067     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
01068       // Don't try to decide equality of aliases.
01069       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
01070         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
01071           return ICmpInst::ICMP_NE;
01072     } else {
01073       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
01074       // GlobalVals can never be null.  Don't try to evaluate aliases.
01075       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
01076         return ICmpInst::ICMP_NE;
01077     }
01078   } else {
01079     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01080     // constantexpr, a CPR, or a simple constant.
01081     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01082     const Constant *CE1Op0 = CE1->getOperand(0);
01083 
01084     switch (CE1->getOpcode()) {
01085     case Instruction::Trunc:
01086     case Instruction::FPTrunc:
01087     case Instruction::FPExt:
01088     case Instruction::FPToUI:
01089     case Instruction::FPToSI:
01090       break; // We can't evaluate floating point casts or truncations.
01091 
01092     case Instruction::UIToFP:
01093     case Instruction::SIToFP:
01094     case Instruction::BitCast:
01095     case Instruction::ZExt:
01096     case Instruction::SExt:
01097       // If the cast is not actually changing bits, and the second operand is a
01098       // null pointer, do the comparison with the pre-casted value.
01099       if (V2->isNullValue() &&
01100           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
01101         bool sgnd = isSigned;
01102         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
01103         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
01104         return evaluateICmpRelation(CE1Op0,
01105                                     Constant::getNullValue(CE1Op0->getType()), 
01106                                     sgnd);
01107       }
01108 
01109       // If the dest type is a pointer type, and the RHS is a constantexpr cast
01110       // from the same type as the src of the LHS, evaluate the inputs.  This is
01111       // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
01112       // which happens a lot in compilers with tagged integers.
01113       if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
01114         if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
01115             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
01116             CE1->getOperand(0)->getType()->isInteger()) {
01117           bool sgnd = isSigned;
01118           if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
01119           if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
01120           return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
01121                                       sgnd);
01122         }
01123       break;
01124 
01125     case Instruction::GetElementPtr:
01126       // Ok, since this is a getelementptr, we know that the constant has a
01127       // pointer type.  Check the various cases.
01128       if (isa<ConstantPointerNull>(V2)) {
01129         // If we are comparing a GEP to a null pointer, check to see if the base
01130         // of the GEP equals the null pointer.
01131         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01132           if (GV->hasExternalWeakLinkage())
01133             // Weak linkage GVals could be zero or not. We're comparing that
01134             // to null pointer so its greater-or-equal
01135             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
01136           else 
01137             // If its not weak linkage, the GVal must have a non-zero address
01138             // so the result is greater-than
01139             return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
01140         } else if (isa<ConstantPointerNull>(CE1Op0)) {
01141           // If we are indexing from a null pointer, check to see if we have any
01142           // non-zero indices.
01143           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
01144             if (!CE1->getOperand(i)->isNullValue())
01145               // Offsetting from null, must not be equal.
01146               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01147           // Only zero indexes from null, must still be zero.
01148           return ICmpInst::ICMP_EQ;
01149         }
01150         // Otherwise, we can't really say if the first operand is null or not.
01151       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
01152         if (isa<ConstantPointerNull>(CE1Op0)) {
01153           if (CPR2->hasExternalWeakLinkage())
01154             // Weak linkage GVals could be zero or not. We're comparing it to
01155             // a null pointer, so its less-or-equal
01156             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
01157           else
01158             // If its not weak linkage, the GVal must have a non-zero address
01159             // so the result is less-than
01160             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01161         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
01162           if (CPR1 == CPR2) {
01163             // If this is a getelementptr of the same global, then it must be
01164             // different.  Because the types must match, the getelementptr could
01165             // only have at most one index, and because we fold getelementptr's
01166             // with a single zero index, it must be nonzero.
01167             assert(CE1->getNumOperands() == 2 &&
01168                    !CE1->getOperand(1)->isNullValue() &&
01169                    "Suprising getelementptr!");
01170             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01171           } else {
01172             // If they are different globals, we don't know what the value is,
01173             // but they can't be equal.
01174             return ICmpInst::ICMP_NE;
01175           }
01176         }
01177       } else {
01178         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
01179         const Constant *CE2Op0 = CE2->getOperand(0);
01180 
01181         // There are MANY other foldings that we could perform here.  They will
01182         // probably be added on demand, as they seem needed.
01183         switch (CE2->getOpcode()) {
01184         default: break;
01185         case Instruction::GetElementPtr:
01186           // By far the most common case to handle is when the base pointers are
01187           // obviously to the same or different globals.
01188           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
01189             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
01190               return ICmpInst::ICMP_NE;
01191             // Ok, we know that both getelementptr instructions are based on the
01192             // same global.  From this, we can precisely determine the relative
01193             // ordering of the resultant pointers.
01194             unsigned i = 1;
01195 
01196             // Compare all of the operands the GEP's have in common.
01197             gep_type_iterator GTI = gep_type_begin(CE1);
01198             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
01199                  ++i, ++GTI)
01200               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
01201                                  GTI.getIndexedType())) {
01202               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
01203               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
01204               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
01205               }
01206 
01207             // Ok, we ran out of things they have in common.  If any leftovers
01208             // are non-zero then we have a difference, otherwise we are equal.
01209             for (; i < CE1->getNumOperands(); ++i)
01210               if (!CE1->getOperand(i)->isNullValue()) {
01211                 if (isa<ConstantInt>(CE1->getOperand(i)))
01212                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01213                 else
01214                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01215               }
01216 
01217             for (; i < CE2->getNumOperands(); ++i)
01218               if (!CE2->getOperand(i)->isNullValue()) {
01219                 if (isa<ConstantInt>(CE2->getOperand(i)))
01220                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01221                 else
01222                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01223               }
01224             return ICmpInst::ICMP_EQ;
01225           }
01226         }
01227       }
01228     default:
01229       break;
01230     }
01231   }
01232 
01233   return ICmpInst::BAD_ICMP_PREDICATE;
01234 }
01235 
01236 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
01237                                                const Constant *C1, 
01238                                                const Constant *C2) {
01239   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
01240   if (pred == FCmpInst::FCMP_FALSE) {
01241     if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
01242       return Constant::getNullValue(VectorType::getInteger(VT));
01243     else
01244       return ConstantInt::getFalse();
01245   }
01246   
01247   if (pred == FCmpInst::FCMP_TRUE) {
01248     if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
01249       return Constant::getAllOnesValue(VectorType::getInteger(VT));
01250     else
01251       return ConstantInt::getTrue();
01252   }
01253       
01254   // Handle some degenerate cases first
01255   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
01256     // vicmp/vfcmp -> [vector] undef
01257     if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType()))
01258       return UndefValue::get(VectorType::getInteger(VTy));
01259     
01260     // icmp/fcmp -> i1 undef
01261     return UndefValue::get(Type::Int1Ty);
01262   }
01263 
01264   // No compile-time operations on this type yet.
01265   if (C1->getType() == Type::PPC_FP128Ty)
01266     return 0;
01267 
01268   // icmp eq/ne(null,GV) -> false/true
01269   if (C1->isNullValue()) {
01270     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
01271       // Don't try to evaluate aliases.  External weak GV can be null.
01272       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01273         if (pred == ICmpInst::ICMP_EQ)
01274           return ConstantInt::getFalse();
01275         else if (pred == ICmpInst::ICMP_NE)
01276           return ConstantInt::getTrue();
01277       }
01278   // icmp eq/ne(GV,null) -> false/true
01279   } else if (C2->isNullValue()) {
01280     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
01281       // Don't try to evaluate aliases.  External weak GV can be null.
01282       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01283         if (pred == ICmpInst::ICMP_EQ)
01284           return ConstantInt::getFalse();
01285         else if (pred == ICmpInst::ICMP_NE)
01286           return ConstantInt::getTrue();
01287       }
01288   }
01289 
01290   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
01291     APInt V1 = cast<ConstantInt>(C1)->getValue();
01292     APInt V2 = cast<ConstantInt>(C2)->getValue();
01293     switch (pred) {
01294     default: assert(0 && "Invalid ICmp Predicate"); return 0;
01295     case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
01296     case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
01297     case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
01298     case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
01299     case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
01300     case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
01301     case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
01302     case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
01303     case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
01304     case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
01305     }
01306   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
01307     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
01308     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
01309     APFloat::cmpResult R = C1V.compare(C2V);
01310     switch (pred) {
01311     default: assert(0 && "Invalid FCmp Predicate"); return 0;
01312     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
01313     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
01314     case FCmpInst::FCMP_UNO:
01315       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
01316     case FCmpInst::FCMP_ORD:
01317       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
01318     case FCmpInst::FCMP_UEQ:
01319       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
01320                                             R==APFloat::cmpEqual);
01321     case FCmpInst::FCMP_OEQ:   
01322       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
01323     case FCmpInst::FCMP_UNE:
01324       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
01325     case FCmpInst::FCMP_ONE:   
01326       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
01327                                             R==APFloat::cmpGreaterThan);
01328     case FCmpInst::FCMP_ULT: 
01329       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
01330                                             R==APFloat::cmpLessThan);
01331     case FCmpInst::FCMP_OLT:   
01332       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
01333     case FCmpInst::FCMP_UGT:
01334       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
01335                                             R==APFloat::cmpGreaterThan);
01336     case FCmpInst::FCMP_OGT:
01337       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
01338     case FCmpInst::FCMP_ULE:
01339       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
01340     case FCmpInst::FCMP_OLE: 
01341       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
01342                                             R==APFloat::cmpEqual);
01343     case FCmpInst::FCMP_UGE:
01344       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
01345     case FCmpInst::FCMP_OGE: 
01346       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
01347                                             R==APFloat::cmpEqual);
01348     }
01349   } else if (isa<VectorType>(C1->getType())) {
01350     SmallVector<Constant*, 16> C1Elts, C2Elts;
01351     C1->getVectorElements(C1Elts);
01352     C2->getVectorElements(C2Elts);
01353     
01354     // If we can constant fold the comparison of each element, constant fold
01355     // the whole vector comparison.
01356     SmallVector<Constant*, 4> ResElts;
01357     const Type *InEltTy = C1Elts[0]->getType();
01358     bool isFP = InEltTy->isFloatingPoint();
01359     const Type *ResEltTy = InEltTy;
01360     if (isFP)
01361       ResEltTy = IntegerType::get(InEltTy->getPrimitiveSizeInBits());
01362     
01363     for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
01364       // Compare the elements, producing an i1 result or constant expr.
01365       Constant *C;
01366       if (isFP)
01367         C = ConstantExpr::getFCmp(pred, C1Elts[i], C2Elts[i]);
01368       else
01369         C = ConstantExpr::getICmp(pred, C1Elts[i], C2Elts[i]);
01370 
01371       // If it is a bool or undef result, convert to the dest type.
01372       if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
01373         if (CI->isZero())
01374           ResElts.push_back(Constant::getNullValue(ResEltTy));
01375         else
01376           ResElts.push_back(Constant::getAllOnesValue(ResEltTy));
01377       } else if (isa<UndefValue>(C)) {
01378         ResElts.push_back(UndefValue::get(ResEltTy));
01379       } else {
01380         break;
01381       }
01382     }
01383     
01384     if (ResElts.size() == C1Elts.size())
01385       return ConstantVector::get(&ResElts[0], ResElts.size());
01386   }
01387 
01388   if (C1->getType()->isFloatingPoint()) {
01389     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01390     switch (evaluateFCmpRelation(C1, C2)) {
01391     default: assert(0 && "Unknown relation!");
01392     case FCmpInst::FCMP_UNO:
01393     case FCmpInst::FCMP_ORD:
01394     case FCmpInst::FCMP_UEQ:
01395     case FCmpInst::FCMP_UNE:
01396     case FCmpInst::FCMP_ULT:
01397     case FCmpInst::FCMP_UGT:
01398     case FCmpInst::FCMP_ULE:
01399     case FCmpInst::FCMP_UGE:
01400     case FCmpInst::FCMP_TRUE:
01401     case FCmpInst::FCMP_FALSE:
01402     case FCmpInst::BAD_FCMP_PREDICATE:
01403       break; // Couldn't determine anything about these constants.
01404     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
01405       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
01406                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
01407                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01408       break;
01409     case FCmpInst::FCMP_OLT: // We know that C1 < C2
01410       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01411                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
01412                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
01413       break;
01414     case FCmpInst::FCMP_OGT: // We know that C1 > C2
01415       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01416                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
01417                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01418       break;
01419     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
01420       // We can only partially decide this relation.
01421       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01422         Result = 0;
01423       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01424         Result = 1;
01425       break;
01426     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
01427       // We can only partially decide this relation.
01428       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01429         Result = 0;
01430       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01431         Result = 1;
01432       break;
01433     case ICmpInst::ICMP_NE: // We know that C1 != C2
01434       // We can only partially decide this relation.
01435       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
01436         Result = 0;
01437       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
01438         Result = 1;
01439       break;
01440     }
01441     
01442     // If we evaluated the result, return it now.
01443     if (Result != -1) {
01444       if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
01445         if (Result == 0)
01446           return Constant::getNullValue(VectorType::getInteger(VT));
01447         else
01448           return Constant::getAllOnesValue(VectorType::getInteger(VT));
01449       }
01450       return ConstantInt::get(Type::Int1Ty, Result);
01451     }
01452     
01453   } else {
01454     // Evaluate the relation between the two constants, per the predicate.
01455     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01456     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
01457     default: assert(0 && "Unknown relational!");
01458     case ICmpInst::BAD_ICMP_PREDICATE:
01459       break;  // Couldn't determine anything about these constants.
01460     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
01461       // If we know the constants are equal, we can decide the result of this
01462       // computation precisely.
01463       Result = (pred == ICmpInst::ICMP_EQ  ||
01464                 pred == ICmpInst::ICMP_ULE ||
01465                 pred == ICmpInst::ICMP_SLE ||
01466                 pred == ICmpInst::ICMP_UGE ||
01467                 pred == ICmpInst::ICMP_SGE);
01468       break;
01469     case ICmpInst::ICMP_ULT:
01470       // If we know that C1 < C2, we can decide the result of this computation
01471       // precisely.
01472       Result = (pred == ICmpInst::ICMP_ULT ||
01473                 pred == ICmpInst::ICMP_NE  ||
01474                 pred == ICmpInst::ICMP_ULE);
01475       break;
01476     case ICmpInst::ICMP_SLT:
01477       // If we know that C1 < C2, we can decide the result of this computation
01478       // precisely.
01479       Result = (pred == ICmpInst::ICMP_SLT ||
01480                 pred == ICmpInst::ICMP_NE  ||
01481                 pred == ICmpInst::ICMP_SLE);
01482       break;
01483     case ICmpInst::ICMP_UGT:
01484       // If we know that C1 > C2, we can decide the result of this computation
01485       // precisely.
01486       Result = (pred == ICmpInst::ICMP_UGT ||
01487                 pred == ICmpInst::ICMP_NE  ||
01488                 pred == ICmpInst::ICMP_UGE);
01489       break;
01490     case ICmpInst::ICMP_SGT:
01491       // If we know that C1 > C2, we can decide the result of this computation
01492       // precisely.
01493       Result = (pred == ICmpInst::ICMP_SGT ||
01494                 pred == ICmpInst::ICMP_NE  ||
01495                 pred == ICmpInst::ICMP_SGE);
01496       break;
01497     case ICmpInst::ICMP_ULE:
01498       // If we know that C1 <= C2, we can only partially decide this relation.
01499       if (pred == ICmpInst::ICMP_UGT) Result = 0;
01500       if (pred == ICmpInst::ICMP_ULT) Result = 1;
01501       break;
01502     case ICmpInst::ICMP_SLE:
01503       // If we know that C1 <= C2, we can only partially decide this relation.
01504       if (pred == ICmpInst::ICMP_SGT) Result = 0;
01505       if (pred == ICmpInst::ICMP_SLT) Result = 1;
01506       break;
01507 
01508     case ICmpInst::ICMP_UGE:
01509       // If we know that C1 >= C2, we can only partially decide this relation.
01510       if (pred == ICmpInst::ICMP_ULT) Result = 0;
01511       if (pred == ICmpInst::ICMP_UGT) Result = 1;
01512       break;
01513     case ICmpInst::ICMP_SGE:
01514       // If we know that C1 >= C2, we can only partially decide this relation.
01515       if (pred == ICmpInst::ICMP_SLT) Result = 0;
01516       if (pred == ICmpInst::ICMP_SGT) Result = 1;
01517       break;
01518 
01519     case ICmpInst::ICMP_NE:
01520       // If we know that C1 != C2, we can only partially decide this relation.
01521       if (pred == ICmpInst::ICMP_EQ) Result = 0;
01522       if (pred == ICmpInst::ICMP_NE) Result = 1;
01523       break;
01524     }
01525     
01526     // If we evaluated the result, return it now.
01527     if (Result != -1) {
01528       if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
01529         if (Result == 0)
01530           return Constant::getNullValue(VT);
01531         else
01532           return Constant::getAllOnesValue(VT);
01533       }
01534       return ConstantInt::get(Type::Int1Ty, Result);
01535     }
01536     
01537     if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
01538       // If C2 is a constant expr and C1 isn't, flop them around and fold the
01539       // other way if possible.
01540       switch (pred) {
01541       case ICmpInst::ICMP_EQ:
01542       case ICmpInst::ICMP_NE:
01543         // No change of predicate required.
01544         return ConstantFoldCompareInstruction(pred, C2, C1);
01545 
01546       case ICmpInst::ICMP_ULT:
01547       case ICmpInst::ICMP_SLT:
01548       case ICmpInst::ICMP_UGT:
01549       case ICmpInst::ICMP_SGT:
01550       case ICmpInst::ICMP_ULE:
01551       case ICmpInst::ICMP_SLE:
01552       case ICmpInst::ICMP_UGE:
01553       case ICmpInst::ICMP_SGE:
01554         // Change the predicate as necessary to swap the operands.
01555         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
01556         return ConstantFoldCompareInstruction(pred, C2, C1);
01557 
01558       default:  // These predicates cannot be flopped around.
01559         break;
01560       }
01561     }
01562   }
01563   return 0;
01564 }
01565 
01566 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
01567                                           Constant* const *Idxs,
01568                                           unsigned NumIdx) {
01569   if (NumIdx == 0 ||
01570       (NumIdx == 1 && Idxs[0]->isNullValue()))
01571     return const_cast<Constant*>(C);
01572 
01573   if (isa<UndefValue>(C)) {
01574     const PointerType *Ptr = cast<PointerType>(C->getType());
01575     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
01576                                                        (Value **)Idxs,
01577                                                        (Value **)Idxs+NumIdx);
01578     assert(Ty != 0 && "Invalid indices for GEP!");
01579     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
01580   }
01581 
01582   Constant *Idx0 = Idxs[0];
01583   if (C->isNullValue()) {
01584     bool isNull = true;
01585     for (unsigned i = 0, e = NumIdx; i != e; ++i)
01586       if (!Idxs[i]->isNullValue()) {
01587         isNull = false;
01588         break;
01589       }
01590     if (isNull) {
01591       const PointerType *Ptr = cast<PointerType>(C->getType());
01592       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
01593                                                          (Value**)Idxs,
01594                                                          (Value**)Idxs+NumIdx);
01595       assert(Ty != 0 && "Invalid indices for GEP!");
01596       return 
01597         ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
01598     }
01599   }
01600 
01601   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
01602     // Combine Indices - If the source pointer to this getelementptr instruction
01603     // is a getelementptr instruction, combine the indices of the two
01604     // getelementptr instructions into a single instruction.
01605     //
01606     if (CE->getOpcode() == Instruction::GetElementPtr) {
01607       const Type *LastTy = 0;
01608       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
01609            I != E; ++I)
01610         LastTy = *I;
01611 
01612       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
01613         SmallVector<Value*, 16> NewIndices;
01614         NewIndices.reserve(NumIdx + CE->getNumOperands());
01615         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
01616           NewIndices.push_back(CE->getOperand(i));
01617 
01618         // Add the last index of the source with the first index of the new GEP.
01619         // Make sure to handle the case when they are actually different types.
01620         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
01621         // Otherwise it must be an array.
01622         if (!Idx0->isNullValue()) {
01623           const Type *IdxTy = Combined->getType();
01624           if (IdxTy != Idx0->getType()) {
01625             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
01626             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
01627                                                           Type::Int64Ty);
01628             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
01629           } else {
01630             Combined =
01631               ConstantExpr::get(Instruction::Add, Idx0, Combined);
01632           }
01633         }
01634 
01635         NewIndices.push_back(Combined);
01636         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
01637         return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
01638                                               NewIndices.size());
01639       }
01640     }
01641 
01642     // Implement folding of:
01643     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
01644     //                        long 0, long 0)
01645     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
01646     //
01647     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
01648       if (const PointerType *SPT =
01649           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
01650         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
01651           if (const ArrayType *CAT =
01652         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
01653             if (CAT->getElementType() == SAT->getElementType())
01654               return ConstantExpr::getGetElementPtr(
01655                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
01656     }
01657     
01658     // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
01659     // Into: inttoptr (i64 0 to i8*)
01660     // This happens with pointers to member functions in C++.
01661     if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
01662         isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
01663         cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
01664       Constant *Base = CE->getOperand(0);
01665       Constant *Offset = Idxs[0];
01666       
01667       // Convert the smaller integer to the larger type.
01668       if (Offset->getType()->getPrimitiveSizeInBits() < 
01669           Base->getType()->getPrimitiveSizeInBits())
01670         Offset = ConstantExpr::getSExt(Offset, Base->getType());
01671       else if (Base->getType()->getPrimitiveSizeInBits() <
01672                Offset->getType()->getPrimitiveSizeInBits())
01673         Base = ConstantExpr::getZExt(Base, Base->getType());
01674       
01675       Base = ConstantExpr::getAdd(Base, Offset);
01676       return ConstantExpr::getIntToPtr(Base, CE->getType());
01677     }
01678   }
01679   return 0;
01680 }
01681