Fix some minor issues folding undef, PR2052
[oota-llvm.git] / lib / VMCore / ConstantFold.cpp
1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements folding of constants for LLVM.  This implements the
11 // (internal) ConstantFold.h interface, which is used by the
12 // ConstantExpr::get* methods to automatically fold constants when possible.
13 //
14 // The current constant folding implementation is implemented in two pieces: the
15 // template-based folder for simple primitive constants like ConstantInt, and
16 // the special case hackery that we use to symbolically evaluate expressions
17 // that use ConstantExprs.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "ConstantFold.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <limits>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //                ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
38
39 /// BitCastConstantVector - Convert the specified ConstantVector node to the
40 /// specified vector type.  At this point, we know that the elements of the
41 /// input vector constant are all simple integer or FP values.
42 static Constant *BitCastConstantVector(ConstantVector *CV,
43                                        const VectorType *DstTy) {
44   // If this cast changes element count then we can't handle it here:
45   // doing so requires endianness information.  This should be handled by
46   // Analysis/ConstantFolding.cpp
47   unsigned NumElts = DstTy->getNumElements();
48   if (NumElts != CV->getNumOperands())
49     return 0;
50   
51   // Check to verify that all elements of the input are simple.
52   for (unsigned i = 0; i != NumElts; ++i) {
53     if (!isa<ConstantInt>(CV->getOperand(i)) &&
54         !isa<ConstantFP>(CV->getOperand(i)))
55       return 0;
56   }
57
58   // Bitcast each element now.
59   std::vector<Constant*> Result;
60   const Type *DstEltTy = DstTy->getElementType();
61   for (unsigned i = 0; i != NumElts; ++i)
62     Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63   return ConstantVector::get(Result);
64 }
65
66 /// This function determines which opcode to use to fold two constant cast 
67 /// expressions together. It uses CastInst::isEliminableCastPair to determine
68 /// the opcode. Consequently its just a wrapper around that function.
69 /// @brief Determine if it is valid to fold a cast of a cast
70 static unsigned
71 foldConstantCastPair(
72   unsigned opc,          ///< opcode of the second cast constant expression
73   const ConstantExpr*Op, ///< the first cast constant expression
74   const Type *DstTy      ///< desintation type of the first cast
75 ) {
76   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78   assert(CastInst::isCast(opc) && "Invalid cast opcode");
79   
80   // The the types and opcodes for the two Cast constant expressions
81   const Type *SrcTy = Op->getOperand(0)->getType();
82   const Type *MidTy = Op->getType();
83   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84   Instruction::CastOps secondOp = Instruction::CastOps(opc);
85
86   // Let CastInst::isEliminableCastPair do the heavy lifting.
87   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
88                                         Type::Int64Ty);
89 }
90
91 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92   const Type *SrcTy = V->getType();
93   if (SrcTy == DestTy)
94     return V; // no-op cast
95   
96   // Check to see if we are casting a pointer to an aggregate to a pointer to
97   // the first element.  If so, return the appropriate GEP instruction.
98   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
100       SmallVector<Value*, 8> IdxList;
101       IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
102       const Type *ElTy = PTy->getElementType();
103       while (ElTy != DPTy->getElementType()) {
104         if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
105           if (STy->getNumElements() == 0) break;
106           ElTy = STy->getElementType(0);
107           IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
108         } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
109           if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
110           ElTy = STy->getElementType();
111           IdxList.push_back(IdxList[0]);
112         } else {
113           break;
114         }
115       }
116       
117       if (ElTy == DPTy->getElementType())
118         return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
119     }
120   
121   // Handle casts from one vector constant to another.  We know that the src 
122   // and dest type have the same size (otherwise its an illegal cast).
123   if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
124     if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
125       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
126              "Not cast between same sized vectors!");
127       // First, check for null.  Undef is already handled.
128       if (isa<ConstantAggregateZero>(V))
129         return Constant::getNullValue(DestTy);
130       
131       if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
132         return BitCastConstantVector(CV, DestPTy);
133     }
134   }
135   
136   // Finally, implement bitcast folding now.   The code below doesn't handle
137   // bitcast right.
138   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
139     return ConstantPointerNull::get(cast<PointerType>(DestTy));
140   
141   // Handle integral constant input.
142   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
143     if (DestTy->isInteger())
144       // Integral -> Integral. This is a no-op because the bit widths must
145       // be the same. Consequently, we just fold to V.
146       return V;
147     
148     if (DestTy->isFloatingPoint()) {
149       assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) && 
150              "Unknown FP type!");
151       return ConstantFP::get(DestTy, APFloat(CI->getValue()));
152     }
153     // Otherwise, can't fold this (vector?)
154     return 0;
155   }
156   
157   // Handle ConstantFP input.
158   if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
159     // FP -> Integral.
160     if (DestTy == Type::Int32Ty) {
161       return ConstantInt::get(FP->getValueAPF().convertToAPInt());
162     } else {
163       assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
164       return ConstantInt::get(FP->getValueAPF().convertToAPInt());
165     }
166   }
167   return 0;
168 }
169
170
171 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
172                                             const Type *DestTy) {
173   const Type *SrcTy = V->getType();
174
175   if (isa<UndefValue>(V)) {
176     // zext(undef) = 0, because the top bits will be zero.
177     // sext(undef) = 0, because the top bits will all be the same.
178     // [us]itofp(undef) = 0, because the result value is bounded.
179     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
180         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
181       return Constant::getNullValue(DestTy);
182     return UndefValue::get(DestTy);
183   }
184   // No compile-time operations on this type yet.
185   if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
186     return 0;
187
188   // If the cast operand is a constant expression, there's a few things we can
189   // do to try to simplify it.
190   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
191     if (CE->isCast()) {
192       // Try hard to fold cast of cast because they are often eliminable.
193       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
194         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
195     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
196       // If all of the indexes in the GEP are null values, there is no pointer
197       // adjustment going on.  We might as well cast the source pointer.
198       bool isAllNull = true;
199       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
200         if (!CE->getOperand(i)->isNullValue()) {
201           isAllNull = false;
202           break;
203         }
204       if (isAllNull)
205         // This is casting one pointer type to another, always BitCast
206         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
207     }
208   }
209
210   // We actually have to do a cast now. Perform the cast according to the
211   // opcode specified.
212   switch (opc) {
213   case Instruction::FPTrunc:
214   case Instruction::FPExt:
215     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
216       APFloat Val = FPC->getValueAPF();
217       Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
218                   DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
219                   DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
220                   DestTy == Type::FP128Ty ? APFloat::IEEEquad :
221                   APFloat::Bogus,
222                   APFloat::rmNearestTiesToEven);
223       return ConstantFP::get(DestTy, Val);
224     }
225     return 0; // Can't fold.
226   case Instruction::FPToUI: 
227   case Instruction::FPToSI:
228     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
229       const APFloat &V = FPC->getValueAPF();
230       uint64_t x[2]; 
231       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
232       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
233                                 APFloat::rmTowardZero);
234       APInt Val(DestBitWidth, 2, x);
235       return ConstantInt::get(Val);
236     }
237     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
238       std::vector<Constant*> res;
239       const VectorType *DestVecTy = cast<VectorType>(DestTy);
240       const Type *DstEltTy = DestVecTy->getElementType();
241       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
242         res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
243                                                   DstEltTy));
244       return ConstantVector::get(DestVecTy, res);
245     }
246     return 0; // Can't fold.
247   case Instruction::IntToPtr:   //always treated as unsigned
248     if (V->isNullValue())       // Is it an integral null value?
249       return ConstantPointerNull::get(cast<PointerType>(DestTy));
250     return 0;                   // Other pointer types cannot be casted
251   case Instruction::PtrToInt:   // always treated as unsigned
252     if (V->isNullValue())       // is it a null pointer value?
253       return ConstantInt::get(DestTy, 0);
254     return 0;                   // Other pointer types cannot be casted
255   case Instruction::UIToFP:
256   case Instruction::SIToFP:
257     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
258       APInt api = CI->getValue();
259       const uint64_t zero[] = {0, 0};
260       uint32_t BitWidth = cast<IntegerType>(SrcTy)->getBitWidth();
261       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
262                                   2, zero));
263       (void)apf.convertFromZeroExtendedInteger(api.getRawData(), BitWidth, 
264                                    opc==Instruction::SIToFP,
265                                    APFloat::rmNearestTiesToEven);
266       return ConstantFP::get(DestTy, apf);
267     }
268     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
269       std::vector<Constant*> res;
270       const VectorType *DestVecTy = cast<VectorType>(DestTy);
271       const Type *DstEltTy = DestVecTy->getElementType();
272       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
273         res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
274                                                   DstEltTy));
275       return ConstantVector::get(DestVecTy, res);
276     }
277     return 0;
278   case Instruction::ZExt:
279     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
280       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
281       APInt Result(CI->getValue());
282       Result.zext(BitWidth);
283       return ConstantInt::get(Result);
284     }
285     return 0;
286   case Instruction::SExt:
287     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
288       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
289       APInt Result(CI->getValue());
290       Result.sext(BitWidth);
291       return ConstantInt::get(Result);
292     }
293     return 0;
294   case Instruction::Trunc:
295     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
296       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
297       APInt Result(CI->getValue());
298       Result.trunc(BitWidth);
299       return ConstantInt::get(Result);
300     }
301     return 0;
302   case Instruction::BitCast:
303     return FoldBitCast(const_cast<Constant*>(V), DestTy);
304   default:
305     assert(!"Invalid CE CastInst opcode");
306     break;
307   }
308
309   assert(0 && "Failed to cast constant expression");
310   return 0;
311 }
312
313 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
314                                               const Constant *V1,
315                                               const Constant *V2) {
316   if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
317     return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
318
319   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
320   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
321   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
322   if (V1 == V2) return const_cast<Constant*>(V1);
323   return 0;
324 }
325
326 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
327                                                       const Constant *Idx) {
328   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
329     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
330   if (Val->isNullValue())  // ee(zero, x) -> zero
331     return Constant::getNullValue(
332                           cast<VectorType>(Val->getType())->getElementType());
333   
334   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
335     if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
336       return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
337     } else if (isa<UndefValue>(Idx)) {
338       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
339       return const_cast<Constant*>(CVal->getOperand(0));
340     }
341   }
342   return 0;
343 }
344
345 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
346                                                      const Constant *Elt,
347                                                      const Constant *Idx) {
348   const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
349   if (!CIdx) return 0;
350   APInt idxVal = CIdx->getValue();
351   if (isa<UndefValue>(Val)) { 
352     // Insertion of scalar constant into vector undef
353     // Optimize away insertion of undef
354     if (isa<UndefValue>(Elt))
355       return const_cast<Constant*>(Val);
356     // Otherwise break the aggregate undef into multiple undefs and do
357     // the insertion
358     unsigned numOps = 
359       cast<VectorType>(Val->getType())->getNumElements();
360     std::vector<Constant*> Ops; 
361     Ops.reserve(numOps);
362     for (unsigned i = 0; i < numOps; ++i) {
363       const Constant *Op =
364         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
365       Ops.push_back(const_cast<Constant*>(Op));
366     }
367     return ConstantVector::get(Ops);
368   }
369   if (isa<ConstantAggregateZero>(Val)) {
370     // Insertion of scalar constant into vector aggregate zero
371     // Optimize away insertion of zero
372     if (Elt->isNullValue())
373       return const_cast<Constant*>(Val);
374     // Otherwise break the aggregate zero into multiple zeros and do
375     // the insertion
376     unsigned numOps = 
377       cast<VectorType>(Val->getType())->getNumElements();
378     std::vector<Constant*> Ops; 
379     Ops.reserve(numOps);
380     for (unsigned i = 0; i < numOps; ++i) {
381       const Constant *Op =
382         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
383       Ops.push_back(const_cast<Constant*>(Op));
384     }
385     return ConstantVector::get(Ops);
386   }
387   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
388     // Insertion of scalar constant into vector constant
389     std::vector<Constant*> Ops; 
390     Ops.reserve(CVal->getNumOperands());
391     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
392       const Constant *Op =
393         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
394       Ops.push_back(const_cast<Constant*>(Op));
395     }
396     return ConstantVector::get(Ops);
397   }
398   return 0;
399 }
400
401 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
402 /// return the specified element value.  Otherwise return null.
403 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
404   if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
405     return const_cast<Constant*>(CV->getOperand(EltNo));
406   
407   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
408   if (isa<ConstantAggregateZero>(C))
409     return Constant::getNullValue(EltTy);
410   if (isa<UndefValue>(C))
411     return UndefValue::get(EltTy);
412   return 0;
413 }
414
415 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
416                                                      const Constant *V2,
417                                                      const Constant *Mask) {
418   // Undefined shuffle mask -> undefined value.
419   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
420   
421   unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
422   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
423   
424   // Loop over the shuffle mask, evaluating each element.
425   SmallVector<Constant*, 32> Result;
426   for (unsigned i = 0; i != NumElts; ++i) {
427     Constant *InElt = GetVectorElement(Mask, i);
428     if (InElt == 0) return 0;
429     
430     if (isa<UndefValue>(InElt))
431       InElt = UndefValue::get(EltTy);
432     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
433       unsigned Elt = CI->getZExtValue();
434       if (Elt >= NumElts*2)
435         InElt = UndefValue::get(EltTy);
436       else if (Elt >= NumElts)
437         InElt = GetVectorElement(V2, Elt-NumElts);
438       else
439         InElt = GetVectorElement(V1, Elt);
440       if (InElt == 0) return 0;
441     } else {
442       // Unknown value.
443       return 0;
444     }
445     Result.push_back(InElt);
446   }
447   
448   return ConstantVector::get(&Result[0], Result.size());
449 }
450
451 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
452 /// function pointer to each element pair, producing a new ConstantVector
453 /// constant. Either or both of V1 and V2 may be NULL, meaning a
454 /// ConstantAggregateZero operand.
455 static Constant *EvalVectorOp(const ConstantVector *V1, 
456                               const ConstantVector *V2,
457                               const VectorType *VTy,
458                               Constant *(*FP)(Constant*, Constant*)) {
459   std::vector<Constant*> Res;
460   const Type *EltTy = VTy->getElementType();
461   for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
462     const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
463     const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
464     Res.push_back(FP(const_cast<Constant*>(C1),
465                      const_cast<Constant*>(C2)));
466   }
467   return ConstantVector::get(Res);
468 }
469
470 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
471                                               const Constant *C1,
472                                               const Constant *C2) {
473   // No compile-time operations on this type yet.
474   if (C1->getType() == Type::PPC_FP128Ty)
475     return 0;
476
477   // Handle UndefValue up front
478   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
479     switch (Opcode) {
480     case Instruction::Add:
481     case Instruction::Sub:
482     case Instruction::Xor:
483       return UndefValue::get(C1->getType());
484     case Instruction::Mul:
485     case Instruction::And:
486       return Constant::getNullValue(C1->getType());
487     case Instruction::UDiv:
488     case Instruction::SDiv:
489     case Instruction::FDiv:
490     case Instruction::URem:
491     case Instruction::SRem:
492     case Instruction::FRem:
493       if (!isa<UndefValue>(C2))                    // undef / X -> 0
494         return Constant::getNullValue(C1->getType());
495       return const_cast<Constant*>(C2);            // X / undef -> undef
496     case Instruction::Or:                          // X | undef -> -1
497       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
498         return ConstantVector::getAllOnesValue(PTy);
499       return ConstantInt::getAllOnesValue(C1->getType());
500     case Instruction::LShr:
501       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
502         return const_cast<Constant*>(C1);           // undef lshr undef -> undef
503       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
504                                                     // undef lshr X -> 0
505     case Instruction::AShr:
506       if (!isa<UndefValue>(C2))
507         return const_cast<Constant*>(C1);           // undef ashr X --> undef
508       else if (isa<UndefValue>(C1)) 
509         return const_cast<Constant*>(C1);           // undef ashr undef -> undef
510       else
511         return const_cast<Constant*>(C1);           // X ashr undef --> X
512     case Instruction::Shl:
513       // undef << X -> 0   or   X << undef -> 0
514       return Constant::getNullValue(C1->getType());
515     }
516   }
517
518   if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
519     if (isa<ConstantExpr>(C2)) {
520       // There are many possible foldings we could do here.  We should probably
521       // at least fold add of a pointer with an integer into the appropriate
522       // getelementptr.  This will improve alias analysis a bit.
523     } else {
524       // Just implement a couple of simple identities.
525       switch (Opcode) {
526       case Instruction::Add:
527         if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X + 0 == X
528         break;
529       case Instruction::Sub:
530         if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X - 0 == X
531         break;
532       case Instruction::Mul:
533         if (C2->isNullValue()) return const_cast<Constant*>(C2);  // X * 0 == 0
534         if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
535           if (CI->equalsInt(1))
536             return const_cast<Constant*>(C1);                     // X * 1 == X
537         break;
538       case Instruction::UDiv:
539       case Instruction::SDiv:
540         if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
541           if (CI->equalsInt(1))
542             return const_cast<Constant*>(C1);                     // X / 1 == X
543         break;
544       case Instruction::URem:
545       case Instruction::SRem:
546         if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
547           if (CI->equalsInt(1))
548             return Constant::getNullValue(CI->getType());         // X % 1 == 0
549         break;
550       case Instruction::And:
551         if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2)) {
552           if (CI->isZero()) return const_cast<Constant*>(C2);     // X & 0 == 0
553           if (CI->isAllOnesValue())
554             return const_cast<Constant*>(C1);                     // X & -1 == X
555           
556           // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
557           if (CE1->getOpcode() == Instruction::ZExt) {
558             APInt PossiblySetBits
559               = cast<IntegerType>(CE1->getOperand(0)->getType())->getMask();
560             PossiblySetBits.zext(C1->getType()->getPrimitiveSizeInBits());
561             if ((PossiblySetBits & CI->getValue()) == PossiblySetBits)
562               return const_cast<Constant*>(C1);
563           }
564         }
565         if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
566           GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
567
568           // Functions are at least 4-byte aligned.  If and'ing the address of a
569           // function with a constant < 4, fold it to zero.
570           if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
571             if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) && 
572                 isa<Function>(CPR))
573               return Constant::getNullValue(CI->getType());
574         }
575         break;
576       case Instruction::Or:
577         if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X | 0 == X
578         if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
579           if (CI->isAllOnesValue())
580             return const_cast<Constant*>(C2);  // X | -1 == -1
581         break;
582       case Instruction::Xor:
583         if (C2->isNullValue()) return const_cast<Constant*>(C1);  // X ^ 0 == X
584         break;
585       case Instruction::AShr:
586         // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
587         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
588           return ConstantExpr::getLShr(const_cast<Constant*>(C1),
589                                        const_cast<Constant*>(C2));
590         break;
591       }
592     }
593   } else if (isa<ConstantExpr>(C2)) {
594     // If C2 is a constant expr and C1 isn't, flop them around and fold the
595     // other way if possible.
596     switch (Opcode) {
597     case Instruction::Add:
598     case Instruction::Mul:
599     case Instruction::And:
600     case Instruction::Or:
601     case Instruction::Xor:
602       // No change of opcode required.
603       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
604
605     case Instruction::Shl:
606     case Instruction::LShr:
607     case Instruction::AShr:
608     case Instruction::Sub:
609     case Instruction::SDiv:
610     case Instruction::UDiv:
611     case Instruction::FDiv:
612     case Instruction::URem:
613     case Instruction::SRem:
614     case Instruction::FRem:
615     default:  // These instructions cannot be flopped around.
616       return 0;
617     }
618   }
619
620   // At this point we know neither constant is an UndefValue nor a ConstantExpr
621   // so look at directly computing the value.
622   if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
623     if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
624       using namespace APIntOps;
625       APInt C1V = CI1->getValue();
626       APInt C2V = CI2->getValue();
627       switch (Opcode) {
628       default:
629         break;
630       case Instruction::Add:     
631         return ConstantInt::get(C1V + C2V);
632       case Instruction::Sub:     
633         return ConstantInt::get(C1V - C2V);
634       case Instruction::Mul:     
635         return ConstantInt::get(C1V * C2V);
636       case Instruction::UDiv:
637         if (CI2->isNullValue())                  
638           return 0;        // X / 0 -> can't fold
639         return ConstantInt::get(C1V.udiv(C2V));
640       case Instruction::SDiv:
641         if (CI2->isNullValue()) 
642           return 0;        // X / 0 -> can't fold
643         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
644           return 0;        // MIN_INT / -1 -> overflow
645         return ConstantInt::get(C1V.sdiv(C2V));
646       case Instruction::URem:
647         if (C2->isNullValue()) 
648           return 0;        // X / 0 -> can't fold
649         return ConstantInt::get(C1V.urem(C2V));
650       case Instruction::SRem:    
651         if (CI2->isNullValue()) 
652           return 0;        // X % 0 -> can't fold
653         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
654           return 0;        // MIN_INT % -1 -> overflow
655         return ConstantInt::get(C1V.srem(C2V));
656       case Instruction::And:
657         return ConstantInt::get(C1V & C2V);
658       case Instruction::Or:
659         return ConstantInt::get(C1V | C2V);
660       case Instruction::Xor:
661         return ConstantInt::get(C1V ^ C2V);
662       case Instruction::Shl:
663         if (uint32_t shiftAmt = C2V.getZExtValue())
664           if (shiftAmt < C1V.getBitWidth())
665             return ConstantInt::get(C1V.shl(shiftAmt));
666           else
667             return UndefValue::get(C1->getType()); // too big shift is undef
668         return const_cast<ConstantInt*>(CI1); // Zero shift is identity
669       case Instruction::LShr:
670         if (uint32_t shiftAmt = C2V.getZExtValue())
671           if (shiftAmt < C1V.getBitWidth())
672             return ConstantInt::get(C1V.lshr(shiftAmt));
673           else
674             return UndefValue::get(C1->getType()); // too big shift is undef
675         return const_cast<ConstantInt*>(CI1); // Zero shift is identity
676       case Instruction::AShr:
677         if (uint32_t shiftAmt = C2V.getZExtValue())
678           if (shiftAmt < C1V.getBitWidth())
679             return ConstantInt::get(C1V.ashr(shiftAmt));
680           else
681             return UndefValue::get(C1->getType()); // too big shift is undef
682         return const_cast<ConstantInt*>(CI1); // Zero shift is identity
683       }
684     }
685   } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
686     if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
687       APFloat C1V = CFP1->getValueAPF();
688       APFloat C2V = CFP2->getValueAPF();
689       APFloat C3V = C1V;  // copy for modification
690       bool isDouble = CFP1->getType()==Type::DoubleTy;
691       switch (Opcode) {
692       default:                   
693         break;
694       case Instruction::Add:
695         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
696         return ConstantFP::get(CFP1->getType(), C3V);
697       case Instruction::Sub:     
698         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
699         return ConstantFP::get(CFP1->getType(), C3V);
700       case Instruction::Mul:
701         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
702         return ConstantFP::get(CFP1->getType(), C3V);
703       case Instruction::FDiv:
704         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
705         return ConstantFP::get(CFP1->getType(), C3V);
706       case Instruction::FRem:
707         if (C2V.isZero())
708           // IEEE 754, Section 7.1, #5
709           return ConstantFP::get(CFP1->getType(), isDouble ?
710                             APFloat(std::numeric_limits<double>::quiet_NaN()) :
711                             APFloat(std::numeric_limits<float>::quiet_NaN()));
712         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
713         return ConstantFP::get(CFP1->getType(), C3V);
714       }
715     }
716   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
717     const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
718     const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
719     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
720         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
721       switch (Opcode) {
722         default:
723           break;
724         case Instruction::Add: 
725         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
726         case Instruction::Sub: 
727         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
728         case Instruction::Mul: 
729         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
730         case Instruction::UDiv:
731         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
732         case Instruction::SDiv:
733         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
734         case Instruction::FDiv:
735         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
736         case Instruction::URem:
737         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
738         case Instruction::SRem:
739         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
740         case Instruction::FRem:
741         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
742         case Instruction::And: 
743         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
744         case Instruction::Or:  
745         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
746         case Instruction::Xor: 
747         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
748       }
749     }
750   }
751
752   // We don't know how to fold this
753   return 0;
754 }
755
756 /// isZeroSizedType - This type is zero sized if its an array or structure of
757 /// zero sized types.  The only leaf zero sized type is an empty structure.
758 static bool isMaybeZeroSizedType(const Type *Ty) {
759   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
760   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
761
762     // If all of elements have zero size, this does too.
763     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
764       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
765     return true;
766
767   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
768     return isMaybeZeroSizedType(ATy->getElementType());
769   }
770   return false;
771 }
772
773 /// IdxCompare - Compare the two constants as though they were getelementptr
774 /// indices.  This allows coersion of the types to be the same thing.
775 ///
776 /// If the two constants are the "same" (after coersion), return 0.  If the
777 /// first is less than the second, return -1, if the second is less than the
778 /// first, return 1.  If the constants are not integral, return -2.
779 ///
780 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
781   if (C1 == C2) return 0;
782
783   // Ok, we found a different index.  If they are not ConstantInt, we can't do
784   // anything with them.
785   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
786     return -2; // don't know!
787
788   // Ok, we have two differing integer indices.  Sign extend them to be the same
789   // type.  Long is always big enough, so we use it.
790   if (C1->getType() != Type::Int64Ty)
791     C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
792
793   if (C2->getType() != Type::Int64Ty)
794     C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
795
796   if (C1 == C2) return 0;  // They are equal
797
798   // If the type being indexed over is really just a zero sized type, there is
799   // no pointer difference being made here.
800   if (isMaybeZeroSizedType(ElTy))
801     return -2; // dunno.
802
803   // If they are really different, now that they are the same type, then we
804   // found a difference!
805   if (cast<ConstantInt>(C1)->getSExtValue() < 
806       cast<ConstantInt>(C2)->getSExtValue())
807     return -1;
808   else
809     return 1;
810 }
811
812 /// evaluateFCmpRelation - This function determines if there is anything we can
813 /// decide about the two constants provided.  This doesn't need to handle simple
814 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
815 /// If we can determine that the two constants have a particular relation to 
816 /// each other, we should return the corresponding FCmpInst predicate, 
817 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
818 /// ConstantFoldCompareInstruction.
819 ///
820 /// To simplify this code we canonicalize the relation so that the first
821 /// operand is always the most "complex" of the two.  We consider ConstantFP
822 /// to be the simplest, and ConstantExprs to be the most complex.
823 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1, 
824                                                 const Constant *V2) {
825   assert(V1->getType() == V2->getType() &&
826          "Cannot compare values of different types!");
827
828   // No compile-time operations on this type yet.
829   if (V1->getType() == Type::PPC_FP128Ty)
830     return FCmpInst::BAD_FCMP_PREDICATE;
831
832   // Handle degenerate case quickly
833   if (V1 == V2) return FCmpInst::FCMP_OEQ;
834
835   if (!isa<ConstantExpr>(V1)) {
836     if (!isa<ConstantExpr>(V2)) {
837       // We distilled thisUse the standard constant folder for a few cases
838       ConstantInt *R = 0;
839       Constant *C1 = const_cast<Constant*>(V1);
840       Constant *C2 = const_cast<Constant*>(V2);
841       R = dyn_cast<ConstantInt>(
842                              ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
843       if (R && !R->isZero()) 
844         return FCmpInst::FCMP_OEQ;
845       R = dyn_cast<ConstantInt>(
846                              ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
847       if (R && !R->isZero()) 
848         return FCmpInst::FCMP_OLT;
849       R = dyn_cast<ConstantInt>(
850                              ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
851       if (R && !R->isZero()) 
852         return FCmpInst::FCMP_OGT;
853
854       // Nothing more we can do
855       return FCmpInst::BAD_FCMP_PREDICATE;
856     }
857     
858     // If the first operand is simple and second is ConstantExpr, swap operands.
859     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
860     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
861       return FCmpInst::getSwappedPredicate(SwappedRelation);
862   } else {
863     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
864     // constantexpr or a simple constant.
865     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
866     switch (CE1->getOpcode()) {
867     case Instruction::FPTrunc:
868     case Instruction::FPExt:
869     case Instruction::UIToFP:
870     case Instruction::SIToFP:
871       // We might be able to do something with these but we don't right now.
872       break;
873     default:
874       break;
875     }
876   }
877   // There are MANY other foldings that we could perform here.  They will
878   // probably be added on demand, as they seem needed.
879   return FCmpInst::BAD_FCMP_PREDICATE;
880 }
881
882 /// evaluateICmpRelation - This function determines if there is anything we can
883 /// decide about the two constants provided.  This doesn't need to handle simple
884 /// things like integer comparisons, but should instead handle ConstantExprs
885 /// and GlobalValues.  If we can determine that the two constants have a
886 /// particular relation to each other, we should return the corresponding ICmp
887 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
888 ///
889 /// To simplify this code we canonicalize the relation so that the first
890 /// operand is always the most "complex" of the two.  We consider simple
891 /// constants (like ConstantInt) to be the simplest, followed by
892 /// GlobalValues, followed by ConstantExpr's (the most complex).
893 ///
894 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1, 
895                                                 const Constant *V2,
896                                                 bool isSigned) {
897   assert(V1->getType() == V2->getType() &&
898          "Cannot compare different types of values!");
899   if (V1 == V2) return ICmpInst::ICMP_EQ;
900
901   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
902     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
903       // We distilled this down to a simple case, use the standard constant
904       // folder.
905       ConstantInt *R = 0;
906       Constant *C1 = const_cast<Constant*>(V1);
907       Constant *C2 = const_cast<Constant*>(V2);
908       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
909       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
910       if (R && !R->isZero()) 
911         return pred;
912       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
913       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
914       if (R && !R->isZero())
915         return pred;
916       pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
917       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
918       if (R && !R->isZero())
919         return pred;
920       
921       // If we couldn't figure it out, bail.
922       return ICmpInst::BAD_ICMP_PREDICATE;
923     }
924     
925     // If the first operand is simple, swap operands.
926     ICmpInst::Predicate SwappedRelation = 
927       evaluateICmpRelation(V2, V1, isSigned);
928     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
929       return ICmpInst::getSwappedPredicate(SwappedRelation);
930
931   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
932     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
933       ICmpInst::Predicate SwappedRelation = 
934         evaluateICmpRelation(V2, V1, isSigned);
935       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
936         return ICmpInst::getSwappedPredicate(SwappedRelation);
937       else
938         return ICmpInst::BAD_ICMP_PREDICATE;
939     }
940
941     // Now we know that the RHS is a GlobalValue or simple constant,
942     // which (since the types must match) means that it's a ConstantPointerNull.
943     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
944       // Don't try to decide equality of aliases.
945       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
946         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
947           return ICmpInst::ICMP_NE;
948     } else {
949       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
950       // GlobalVals can never be null.  Don't try to evaluate aliases.
951       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
952         return ICmpInst::ICMP_NE;
953     }
954   } else {
955     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
956     // constantexpr, a CPR, or a simple constant.
957     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
958     const Constant *CE1Op0 = CE1->getOperand(0);
959
960     switch (CE1->getOpcode()) {
961     case Instruction::Trunc:
962     case Instruction::FPTrunc:
963     case Instruction::FPExt:
964     case Instruction::FPToUI:
965     case Instruction::FPToSI:
966       break; // We can't evaluate floating point casts or truncations.
967
968     case Instruction::UIToFP:
969     case Instruction::SIToFP:
970     case Instruction::BitCast:
971     case Instruction::ZExt:
972     case Instruction::SExt:
973       // If the cast is not actually changing bits, and the second operand is a
974       // null pointer, do the comparison with the pre-casted value.
975       if (V2->isNullValue() &&
976           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
977         bool sgnd = isSigned;
978         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
979         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
980         return evaluateICmpRelation(CE1Op0,
981                                     Constant::getNullValue(CE1Op0->getType()), 
982                                     sgnd);
983       }
984
985       // If the dest type is a pointer type, and the RHS is a constantexpr cast
986       // from the same type as the src of the LHS, evaluate the inputs.  This is
987       // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
988       // which happens a lot in compilers with tagged integers.
989       if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
990         if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
991             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
992             CE1->getOperand(0)->getType()->isInteger()) {
993           bool sgnd = isSigned;
994           if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
995           if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
996           return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
997                                       sgnd);
998         }
999       break;
1000
1001     case Instruction::GetElementPtr:
1002       // Ok, since this is a getelementptr, we know that the constant has a
1003       // pointer type.  Check the various cases.
1004       if (isa<ConstantPointerNull>(V2)) {
1005         // If we are comparing a GEP to a null pointer, check to see if the base
1006         // of the GEP equals the null pointer.
1007         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1008           if (GV->hasExternalWeakLinkage())
1009             // Weak linkage GVals could be zero or not. We're comparing that
1010             // to null pointer so its greater-or-equal
1011             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1012           else 
1013             // If its not weak linkage, the GVal must have a non-zero address
1014             // so the result is greater-than
1015             return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
1016         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1017           // If we are indexing from a null pointer, check to see if we have any
1018           // non-zero indices.
1019           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1020             if (!CE1->getOperand(i)->isNullValue())
1021               // Offsetting from null, must not be equal.
1022               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1023           // Only zero indexes from null, must still be zero.
1024           return ICmpInst::ICMP_EQ;
1025         }
1026         // Otherwise, we can't really say if the first operand is null or not.
1027       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1028         if (isa<ConstantPointerNull>(CE1Op0)) {
1029           if (CPR2->hasExternalWeakLinkage())
1030             // Weak linkage GVals could be zero or not. We're comparing it to
1031             // a null pointer, so its less-or-equal
1032             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1033           else
1034             // If its not weak linkage, the GVal must have a non-zero address
1035             // so the result is less-than
1036             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1037         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1038           if (CPR1 == CPR2) {
1039             // If this is a getelementptr of the same global, then it must be
1040             // different.  Because the types must match, the getelementptr could
1041             // only have at most one index, and because we fold getelementptr's
1042             // with a single zero index, it must be nonzero.
1043             assert(CE1->getNumOperands() == 2 &&
1044                    !CE1->getOperand(1)->isNullValue() &&
1045                    "Suprising getelementptr!");
1046             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1047           } else {
1048             // If they are different globals, we don't know what the value is,
1049             // but they can't be equal.
1050             return ICmpInst::ICMP_NE;
1051           }
1052         }
1053       } else {
1054         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1055         const Constant *CE2Op0 = CE2->getOperand(0);
1056
1057         // There are MANY other foldings that we could perform here.  They will
1058         // probably be added on demand, as they seem needed.
1059         switch (CE2->getOpcode()) {
1060         default: break;
1061         case Instruction::GetElementPtr:
1062           // By far the most common case to handle is when the base pointers are
1063           // obviously to the same or different globals.
1064           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1065             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1066               return ICmpInst::ICMP_NE;
1067             // Ok, we know that both getelementptr instructions are based on the
1068             // same global.  From this, we can precisely determine the relative
1069             // ordering of the resultant pointers.
1070             unsigned i = 1;
1071
1072             // Compare all of the operands the GEP's have in common.
1073             gep_type_iterator GTI = gep_type_begin(CE1);
1074             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1075                  ++i, ++GTI)
1076               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1077                                  GTI.getIndexedType())) {
1078               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1079               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1080               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1081               }
1082
1083             // Ok, we ran out of things they have in common.  If any leftovers
1084             // are non-zero then we have a difference, otherwise we are equal.
1085             for (; i < CE1->getNumOperands(); ++i)
1086               if (!CE1->getOperand(i)->isNullValue())
1087                 if (isa<ConstantInt>(CE1->getOperand(i)))
1088                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1089                 else
1090                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1091
1092             for (; i < CE2->getNumOperands(); ++i)
1093               if (!CE2->getOperand(i)->isNullValue())
1094                 if (isa<ConstantInt>(CE2->getOperand(i)))
1095                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1096                 else
1097                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1098             return ICmpInst::ICMP_EQ;
1099           }
1100         }
1101       }
1102     default:
1103       break;
1104     }
1105   }
1106
1107   return ICmpInst::BAD_ICMP_PREDICATE;
1108 }
1109
1110 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1111                                                const Constant *C1, 
1112                                                const Constant *C2) {
1113
1114   // Handle some degenerate cases first
1115   if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1116     return UndefValue::get(Type::Int1Ty);
1117
1118   // No compile-time operations on this type yet.
1119   if (C1->getType() == Type::PPC_FP128Ty)
1120     return 0;
1121
1122   // icmp eq/ne(null,GV) -> false/true
1123   if (C1->isNullValue()) {
1124     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1125       // Don't try to evaluate aliases.  External weak GV can be null.
1126       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage())
1127         if (pred == ICmpInst::ICMP_EQ)
1128           return ConstantInt::getFalse();
1129         else if (pred == ICmpInst::ICMP_NE)
1130           return ConstantInt::getTrue();
1131   // icmp eq/ne(GV,null) -> false/true
1132   } else if (C2->isNullValue()) {
1133     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1134       // Don't try to evaluate aliases.  External weak GV can be null.
1135       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage())
1136         if (pred == ICmpInst::ICMP_EQ)
1137           return ConstantInt::getFalse();
1138         else if (pred == ICmpInst::ICMP_NE)
1139           return ConstantInt::getTrue();
1140   }
1141
1142   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1143     APInt V1 = cast<ConstantInt>(C1)->getValue();
1144     APInt V2 = cast<ConstantInt>(C2)->getValue();
1145     switch (pred) {
1146     default: assert(0 && "Invalid ICmp Predicate"); return 0;
1147     case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1148     case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1149     case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1150     case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1151     case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1152     case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1153     case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1154     case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1155     case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1156     case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1157     }
1158   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1159     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1160     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1161     APFloat::cmpResult R = C1V.compare(C2V);
1162     switch (pred) {
1163     default: assert(0 && "Invalid FCmp Predicate"); return 0;
1164     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1165     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1166     case FCmpInst::FCMP_UNO:
1167       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1168     case FCmpInst::FCMP_ORD:
1169       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1170     case FCmpInst::FCMP_UEQ:
1171       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1172                                             R==APFloat::cmpEqual);
1173     case FCmpInst::FCMP_OEQ:   
1174       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1175     case FCmpInst::FCMP_UNE:
1176       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1177     case FCmpInst::FCMP_ONE:   
1178       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1179                                             R==APFloat::cmpGreaterThan);
1180     case FCmpInst::FCMP_ULT: 
1181       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1182                                             R==APFloat::cmpLessThan);
1183     case FCmpInst::FCMP_OLT:   
1184       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1185     case FCmpInst::FCMP_UGT:
1186       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1187                                             R==APFloat::cmpGreaterThan);
1188     case FCmpInst::FCMP_OGT:
1189       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1190     case FCmpInst::FCMP_ULE:
1191       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1192     case FCmpInst::FCMP_OLE: 
1193       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1194                                             R==APFloat::cmpEqual);
1195     case FCmpInst::FCMP_UGE:
1196       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1197     case FCmpInst::FCMP_OGE: 
1198       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1199                                             R==APFloat::cmpEqual);
1200     }
1201   } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1202     if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1203       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1204         for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1205           Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1206               const_cast<Constant*>(CP1->getOperand(i)),
1207               const_cast<Constant*>(CP2->getOperand(i)));
1208           if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1209             return CB;
1210         }
1211         // Otherwise, could not decide from any element pairs.
1212         return 0;
1213       } else if (pred == ICmpInst::ICMP_EQ) {
1214         for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1215           Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1216               const_cast<Constant*>(CP1->getOperand(i)),
1217               const_cast<Constant*>(CP2->getOperand(i)));
1218           if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1219             return CB;
1220         }
1221         // Otherwise, could not decide from any element pairs.
1222         return 0;
1223       }
1224     }
1225   }
1226
1227   if (C1->getType()->isFloatingPoint()) {
1228     switch (evaluateFCmpRelation(C1, C2)) {
1229     default: assert(0 && "Unknown relation!");
1230     case FCmpInst::FCMP_UNO:
1231     case FCmpInst::FCMP_ORD:
1232     case FCmpInst::FCMP_UEQ:
1233     case FCmpInst::FCMP_UNE:
1234     case FCmpInst::FCMP_ULT:
1235     case FCmpInst::FCMP_UGT:
1236     case FCmpInst::FCMP_ULE:
1237     case FCmpInst::FCMP_UGE:
1238     case FCmpInst::FCMP_TRUE:
1239     case FCmpInst::FCMP_FALSE:
1240     case FCmpInst::BAD_FCMP_PREDICATE:
1241       break; // Couldn't determine anything about these constants.
1242     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1243       return ConstantInt::get(Type::Int1Ty,
1244           pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1245           pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1246           pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1247     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1248       return ConstantInt::get(Type::Int1Ty,
1249           pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1250           pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1251           pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1252     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1253       return ConstantInt::get(Type::Int1Ty,
1254           pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1255           pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1256           pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1257     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1258       // We can only partially decide this relation.
1259       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1260         return ConstantInt::getFalse();
1261       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1262         return ConstantInt::getTrue();
1263       break;
1264     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1265       // We can only partially decide this relation.
1266       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1267         return ConstantInt::getFalse();
1268       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1269         return ConstantInt::getTrue();
1270       break;
1271     case ICmpInst::ICMP_NE: // We know that C1 != C2
1272       // We can only partially decide this relation.
1273       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1274         return ConstantInt::getFalse();
1275       if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1276         return ConstantInt::getTrue();
1277       break;
1278     }
1279   } else {
1280     // Evaluate the relation between the two constants, per the predicate.
1281     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1282     default: assert(0 && "Unknown relational!");
1283     case ICmpInst::BAD_ICMP_PREDICATE:
1284       break;  // Couldn't determine anything about these constants.
1285     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1286       // If we know the constants are equal, we can decide the result of this
1287       // computation precisely.
1288       return ConstantInt::get(Type::Int1Ty, 
1289                               pred == ICmpInst::ICMP_EQ  ||
1290                               pred == ICmpInst::ICMP_ULE ||
1291                               pred == ICmpInst::ICMP_SLE ||
1292                               pred == ICmpInst::ICMP_UGE ||
1293                               pred == ICmpInst::ICMP_SGE);
1294     case ICmpInst::ICMP_ULT:
1295       // If we know that C1 < C2, we can decide the result of this computation
1296       // precisely.
1297       return ConstantInt::get(Type::Int1Ty, 
1298                               pred == ICmpInst::ICMP_ULT ||
1299                               pred == ICmpInst::ICMP_NE  ||
1300                               pred == ICmpInst::ICMP_ULE);
1301     case ICmpInst::ICMP_SLT:
1302       // If we know that C1 < C2, we can decide the result of this computation
1303       // precisely.
1304       return ConstantInt::get(Type::Int1Ty,
1305                               pred == ICmpInst::ICMP_SLT ||
1306                               pred == ICmpInst::ICMP_NE  ||
1307                               pred == ICmpInst::ICMP_SLE);
1308     case ICmpInst::ICMP_UGT:
1309       // If we know that C1 > C2, we can decide the result of this computation
1310       // precisely.
1311       return ConstantInt::get(Type::Int1Ty, 
1312                               pred == ICmpInst::ICMP_UGT ||
1313                               pred == ICmpInst::ICMP_NE  ||
1314                               pred == ICmpInst::ICMP_UGE);
1315     case ICmpInst::ICMP_SGT:
1316       // If we know that C1 > C2, we can decide the result of this computation
1317       // precisely.
1318       return ConstantInt::get(Type::Int1Ty, 
1319                               pred == ICmpInst::ICMP_SGT ||
1320                               pred == ICmpInst::ICMP_NE  ||
1321                               pred == ICmpInst::ICMP_SGE);
1322     case ICmpInst::ICMP_ULE:
1323       // If we know that C1 <= C2, we can only partially decide this relation.
1324       if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1325       if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1326       break;
1327     case ICmpInst::ICMP_SLE:
1328       // If we know that C1 <= C2, we can only partially decide this relation.
1329       if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1330       if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1331       break;
1332
1333     case ICmpInst::ICMP_UGE:
1334       // If we know that C1 >= C2, we can only partially decide this relation.
1335       if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1336       if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1337       break;
1338     case ICmpInst::ICMP_SGE:
1339       // If we know that C1 >= C2, we can only partially decide this relation.
1340       if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1341       if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1342       break;
1343
1344     case ICmpInst::ICMP_NE:
1345       // If we know that C1 != C2, we can only partially decide this relation.
1346       if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1347       if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1348       break;
1349     }
1350
1351     if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1352       // If C2 is a constant expr and C1 isn't, flop them around and fold the
1353       // other way if possible.
1354       switch (pred) {
1355       case ICmpInst::ICMP_EQ:
1356       case ICmpInst::ICMP_NE:
1357         // No change of predicate required.
1358         return ConstantFoldCompareInstruction(pred, C2, C1);
1359
1360       case ICmpInst::ICMP_ULT:
1361       case ICmpInst::ICMP_SLT:
1362       case ICmpInst::ICMP_UGT:
1363       case ICmpInst::ICMP_SGT:
1364       case ICmpInst::ICMP_ULE:
1365       case ICmpInst::ICMP_SLE:
1366       case ICmpInst::ICMP_UGE:
1367       case ICmpInst::ICMP_SGE:
1368         // Change the predicate as necessary to swap the operands.
1369         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1370         return ConstantFoldCompareInstruction(pred, C2, C1);
1371
1372       default:  // These predicates cannot be flopped around.
1373         break;
1374       }
1375     }
1376   }
1377   return 0;
1378 }
1379
1380 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1381                                           Constant* const *Idxs,
1382                                           unsigned NumIdx) {
1383   if (NumIdx == 0 ||
1384       (NumIdx == 1 && Idxs[0]->isNullValue()))
1385     return const_cast<Constant*>(C);
1386
1387   if (isa<UndefValue>(C)) {
1388     const PointerType *Ptr = cast<PointerType>(C->getType());
1389     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1390                                                        (Value **)Idxs,
1391                                                        (Value **)Idxs+NumIdx,
1392                                                        true);
1393     assert(Ty != 0 && "Invalid indices for GEP!");
1394     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1395   }
1396
1397   Constant *Idx0 = Idxs[0];
1398   if (C->isNullValue()) {
1399     bool isNull = true;
1400     for (unsigned i = 0, e = NumIdx; i != e; ++i)
1401       if (!Idxs[i]->isNullValue()) {
1402         isNull = false;
1403         break;
1404       }
1405     if (isNull) {
1406       const PointerType *Ptr = cast<PointerType>(C->getType());
1407       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1408                                                          (Value**)Idxs,
1409                                                          (Value**)Idxs+NumIdx,
1410                                                          true);
1411       assert(Ty != 0 && "Invalid indices for GEP!");
1412       return 
1413         ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1414     }
1415   }
1416
1417   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1418     // Combine Indices - If the source pointer to this getelementptr instruction
1419     // is a getelementptr instruction, combine the indices of the two
1420     // getelementptr instructions into a single instruction.
1421     //
1422     if (CE->getOpcode() == Instruction::GetElementPtr) {
1423       const Type *LastTy = 0;
1424       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1425            I != E; ++I)
1426         LastTy = *I;
1427
1428       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1429         SmallVector<Value*, 16> NewIndices;
1430         NewIndices.reserve(NumIdx + CE->getNumOperands());
1431         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1432           NewIndices.push_back(CE->getOperand(i));
1433
1434         // Add the last index of the source with the first index of the new GEP.
1435         // Make sure to handle the case when they are actually different types.
1436         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1437         // Otherwise it must be an array.
1438         if (!Idx0->isNullValue()) {
1439           const Type *IdxTy = Combined->getType();
1440           if (IdxTy != Idx0->getType()) {
1441             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1442             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
1443                                                           Type::Int64Ty);
1444             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1445           } else {
1446             Combined =
1447               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1448           }
1449         }
1450
1451         NewIndices.push_back(Combined);
1452         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1453         return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1454                                               NewIndices.size());
1455       }
1456     }
1457
1458     // Implement folding of:
1459     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1460     //                        long 0, long 0)
1461     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1462     //
1463     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1464       if (const PointerType *SPT =
1465           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1466         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1467           if (const ArrayType *CAT =
1468         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1469             if (CAT->getElementType() == SAT->getElementType())
1470               return ConstantExpr::getGetElementPtr(
1471                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
1472     }
1473     
1474     // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1475     // Into: inttoptr (i64 0 to i8*)
1476     // This happens with pointers to member functions in C++.
1477     if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1478         isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1479         cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1480       Constant *Base = CE->getOperand(0);
1481       Constant *Offset = Idxs[0];
1482       
1483       // Convert the smaller integer to the larger type.
1484       if (Offset->getType()->getPrimitiveSizeInBits() < 
1485           Base->getType()->getPrimitiveSizeInBits())
1486         Offset = ConstantExpr::getSExt(Offset, Base->getType());
1487       else if (Base->getType()->getPrimitiveSizeInBits() <
1488                Offset->getType()->getPrimitiveSizeInBits())
1489         Base = ConstantExpr::getZExt(Base, Base->getType());
1490       
1491       Base = ConstantExpr::getAdd(Base, Offset);
1492       return ConstantExpr::getIntToPtr(Base, CE->getType());
1493     }
1494   }
1495   return 0;
1496 }
1497