Unbreak build with gcc 4.3: provide missed includes and silence most annoying warnings.
[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         }
669         return const_cast<ConstantInt*>(CI1); // Zero shift is identity
670       case Instruction::LShr:
671         if (uint32_t shiftAmt = C2V.getZExtValue()) {
672           if (shiftAmt < C1V.getBitWidth())
673             return ConstantInt::get(C1V.lshr(shiftAmt));
674           else
675             return UndefValue::get(C1->getType()); // too big shift is undef
676         }
677         return const_cast<ConstantInt*>(CI1); // Zero shift is identity
678       case Instruction::AShr:
679         if (uint32_t shiftAmt = C2V.getZExtValue()) {
680           if (shiftAmt < C1V.getBitWidth())
681             return ConstantInt::get(C1V.ashr(shiftAmt));
682           else
683             return UndefValue::get(C1->getType()); // too big shift is undef
684         }
685         return const_cast<ConstantInt*>(CI1); // Zero shift is identity
686       }
687     }
688   } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
689     if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
690       APFloat C1V = CFP1->getValueAPF();
691       APFloat C2V = CFP2->getValueAPF();
692       APFloat C3V = C1V;  // copy for modification
693       bool isDouble = CFP1->getType()==Type::DoubleTy;
694       switch (Opcode) {
695       default:                   
696         break;
697       case Instruction::Add:
698         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
699         return ConstantFP::get(CFP1->getType(), C3V);
700       case Instruction::Sub:     
701         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
702         return ConstantFP::get(CFP1->getType(), C3V);
703       case Instruction::Mul:
704         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
705         return ConstantFP::get(CFP1->getType(), C3V);
706       case Instruction::FDiv:
707         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
708         return ConstantFP::get(CFP1->getType(), C3V);
709       case Instruction::FRem:
710         if (C2V.isZero())
711           // IEEE 754, Section 7.1, #5
712           return ConstantFP::get(CFP1->getType(), isDouble ?
713                             APFloat(std::numeric_limits<double>::quiet_NaN()) :
714                             APFloat(std::numeric_limits<float>::quiet_NaN()));
715         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
716         return ConstantFP::get(CFP1->getType(), C3V);
717       }
718     }
719   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
720     const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
721     const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
722     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
723         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
724       switch (Opcode) {
725         default:
726           break;
727         case Instruction::Add: 
728         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
729         case Instruction::Sub: 
730         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
731         case Instruction::Mul: 
732         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
733         case Instruction::UDiv:
734         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
735         case Instruction::SDiv:
736         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
737         case Instruction::FDiv:
738         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
739         case Instruction::URem:
740         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
741         case Instruction::SRem:
742         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
743         case Instruction::FRem:
744         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
745         case Instruction::And: 
746         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
747         case Instruction::Or:  
748         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
749         case Instruction::Xor: 
750         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
751       }
752     }
753   }
754
755   // We don't know how to fold this
756   return 0;
757 }
758
759 /// isZeroSizedType - This type is zero sized if its an array or structure of
760 /// zero sized types.  The only leaf zero sized type is an empty structure.
761 static bool isMaybeZeroSizedType(const Type *Ty) {
762   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
763   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
764
765     // If all of elements have zero size, this does too.
766     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
767       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
768     return true;
769
770   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
771     return isMaybeZeroSizedType(ATy->getElementType());
772   }
773   return false;
774 }
775
776 /// IdxCompare - Compare the two constants as though they were getelementptr
777 /// indices.  This allows coersion of the types to be the same thing.
778 ///
779 /// If the two constants are the "same" (after coersion), return 0.  If the
780 /// first is less than the second, return -1, if the second is less than the
781 /// first, return 1.  If the constants are not integral, return -2.
782 ///
783 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
784   if (C1 == C2) return 0;
785
786   // Ok, we found a different index.  If they are not ConstantInt, we can't do
787   // anything with them.
788   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
789     return -2; // don't know!
790
791   // Ok, we have two differing integer indices.  Sign extend them to be the same
792   // type.  Long is always big enough, so we use it.
793   if (C1->getType() != Type::Int64Ty)
794     C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
795
796   if (C2->getType() != Type::Int64Ty)
797     C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
798
799   if (C1 == C2) return 0;  // They are equal
800
801   // If the type being indexed over is really just a zero sized type, there is
802   // no pointer difference being made here.
803   if (isMaybeZeroSizedType(ElTy))
804     return -2; // dunno.
805
806   // If they are really different, now that they are the same type, then we
807   // found a difference!
808   if (cast<ConstantInt>(C1)->getSExtValue() < 
809       cast<ConstantInt>(C2)->getSExtValue())
810     return -1;
811   else
812     return 1;
813 }
814
815 /// evaluateFCmpRelation - This function determines if there is anything we can
816 /// decide about the two constants provided.  This doesn't need to handle simple
817 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
818 /// If we can determine that the two constants have a particular relation to 
819 /// each other, we should return the corresponding FCmpInst predicate, 
820 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
821 /// ConstantFoldCompareInstruction.
822 ///
823 /// To simplify this code we canonicalize the relation so that the first
824 /// operand is always the most "complex" of the two.  We consider ConstantFP
825 /// to be the simplest, and ConstantExprs to be the most complex.
826 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1, 
827                                                 const Constant *V2) {
828   assert(V1->getType() == V2->getType() &&
829          "Cannot compare values of different types!");
830
831   // No compile-time operations on this type yet.
832   if (V1->getType() == Type::PPC_FP128Ty)
833     return FCmpInst::BAD_FCMP_PREDICATE;
834
835   // Handle degenerate case quickly
836   if (V1 == V2) return FCmpInst::FCMP_OEQ;
837
838   if (!isa<ConstantExpr>(V1)) {
839     if (!isa<ConstantExpr>(V2)) {
840       // We distilled thisUse the standard constant folder for a few cases
841       ConstantInt *R = 0;
842       Constant *C1 = const_cast<Constant*>(V1);
843       Constant *C2 = const_cast<Constant*>(V2);
844       R = dyn_cast<ConstantInt>(
845                              ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
846       if (R && !R->isZero()) 
847         return FCmpInst::FCMP_OEQ;
848       R = dyn_cast<ConstantInt>(
849                              ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
850       if (R && !R->isZero()) 
851         return FCmpInst::FCMP_OLT;
852       R = dyn_cast<ConstantInt>(
853                              ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
854       if (R && !R->isZero()) 
855         return FCmpInst::FCMP_OGT;
856
857       // Nothing more we can do
858       return FCmpInst::BAD_FCMP_PREDICATE;
859     }
860     
861     // If the first operand is simple and second is ConstantExpr, swap operands.
862     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
863     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
864       return FCmpInst::getSwappedPredicate(SwappedRelation);
865   } else {
866     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
867     // constantexpr or a simple constant.
868     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
869     switch (CE1->getOpcode()) {
870     case Instruction::FPTrunc:
871     case Instruction::FPExt:
872     case Instruction::UIToFP:
873     case Instruction::SIToFP:
874       // We might be able to do something with these but we don't right now.
875       break;
876     default:
877       break;
878     }
879   }
880   // There are MANY other foldings that we could perform here.  They will
881   // probably be added on demand, as they seem needed.
882   return FCmpInst::BAD_FCMP_PREDICATE;
883 }
884
885 /// evaluateICmpRelation - This function determines if there is anything we can
886 /// decide about the two constants provided.  This doesn't need to handle simple
887 /// things like integer comparisons, but should instead handle ConstantExprs
888 /// and GlobalValues.  If we can determine that the two constants have a
889 /// particular relation to each other, we should return the corresponding ICmp
890 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
891 ///
892 /// To simplify this code we canonicalize the relation so that the first
893 /// operand is always the most "complex" of the two.  We consider simple
894 /// constants (like ConstantInt) to be the simplest, followed by
895 /// GlobalValues, followed by ConstantExpr's (the most complex).
896 ///
897 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1, 
898                                                 const Constant *V2,
899                                                 bool isSigned) {
900   assert(V1->getType() == V2->getType() &&
901          "Cannot compare different types of values!");
902   if (V1 == V2) return ICmpInst::ICMP_EQ;
903
904   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
905     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
906       // We distilled this down to a simple case, use the standard constant
907       // folder.
908       ConstantInt *R = 0;
909       Constant *C1 = const_cast<Constant*>(V1);
910       Constant *C2 = const_cast<Constant*>(V2);
911       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
912       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
913       if (R && !R->isZero()) 
914         return pred;
915       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
916       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
917       if (R && !R->isZero())
918         return pred;
919       pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
920       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
921       if (R && !R->isZero())
922         return pred;
923       
924       // If we couldn't figure it out, bail.
925       return ICmpInst::BAD_ICMP_PREDICATE;
926     }
927     
928     // If the first operand is simple, swap operands.
929     ICmpInst::Predicate SwappedRelation = 
930       evaluateICmpRelation(V2, V1, isSigned);
931     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
932       return ICmpInst::getSwappedPredicate(SwappedRelation);
933
934   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
935     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
936       ICmpInst::Predicate SwappedRelation = 
937         evaluateICmpRelation(V2, V1, isSigned);
938       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
939         return ICmpInst::getSwappedPredicate(SwappedRelation);
940       else
941         return ICmpInst::BAD_ICMP_PREDICATE;
942     }
943
944     // Now we know that the RHS is a GlobalValue or simple constant,
945     // which (since the types must match) means that it's a ConstantPointerNull.
946     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
947       // Don't try to decide equality of aliases.
948       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
949         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
950           return ICmpInst::ICMP_NE;
951     } else {
952       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
953       // GlobalVals can never be null.  Don't try to evaluate aliases.
954       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
955         return ICmpInst::ICMP_NE;
956     }
957   } else {
958     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
959     // constantexpr, a CPR, or a simple constant.
960     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
961     const Constant *CE1Op0 = CE1->getOperand(0);
962
963     switch (CE1->getOpcode()) {
964     case Instruction::Trunc:
965     case Instruction::FPTrunc:
966     case Instruction::FPExt:
967     case Instruction::FPToUI:
968     case Instruction::FPToSI:
969       break; // We can't evaluate floating point casts or truncations.
970
971     case Instruction::UIToFP:
972     case Instruction::SIToFP:
973     case Instruction::BitCast:
974     case Instruction::ZExt:
975     case Instruction::SExt:
976       // If the cast is not actually changing bits, and the second operand is a
977       // null pointer, do the comparison with the pre-casted value.
978       if (V2->isNullValue() &&
979           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
980         bool sgnd = isSigned;
981         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
982         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
983         return evaluateICmpRelation(CE1Op0,
984                                     Constant::getNullValue(CE1Op0->getType()), 
985                                     sgnd);
986       }
987
988       // If the dest type is a pointer type, and the RHS is a constantexpr cast
989       // from the same type as the src of the LHS, evaluate the inputs.  This is
990       // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
991       // which happens a lot in compilers with tagged integers.
992       if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
993         if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
994             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
995             CE1->getOperand(0)->getType()->isInteger()) {
996           bool sgnd = isSigned;
997           if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
998           if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
999           return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1000                                       sgnd);
1001         }
1002       break;
1003
1004     case Instruction::GetElementPtr:
1005       // Ok, since this is a getelementptr, we know that the constant has a
1006       // pointer type.  Check the various cases.
1007       if (isa<ConstantPointerNull>(V2)) {
1008         // If we are comparing a GEP to a null pointer, check to see if the base
1009         // of the GEP equals the null pointer.
1010         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1011           if (GV->hasExternalWeakLinkage())
1012             // Weak linkage GVals could be zero or not. We're comparing that
1013             // to null pointer so its greater-or-equal
1014             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1015           else 
1016             // If its not weak linkage, the GVal must have a non-zero address
1017             // so the result is greater-than
1018             return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
1019         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1020           // If we are indexing from a null pointer, check to see if we have any
1021           // non-zero indices.
1022           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1023             if (!CE1->getOperand(i)->isNullValue())
1024               // Offsetting from null, must not be equal.
1025               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1026           // Only zero indexes from null, must still be zero.
1027           return ICmpInst::ICMP_EQ;
1028         }
1029         // Otherwise, we can't really say if the first operand is null or not.
1030       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1031         if (isa<ConstantPointerNull>(CE1Op0)) {
1032           if (CPR2->hasExternalWeakLinkage())
1033             // Weak linkage GVals could be zero or not. We're comparing it to
1034             // a null pointer, so its less-or-equal
1035             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1036           else
1037             // If its not weak linkage, the GVal must have a non-zero address
1038             // so the result is less-than
1039             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1040         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1041           if (CPR1 == CPR2) {
1042             // If this is a getelementptr of the same global, then it must be
1043             // different.  Because the types must match, the getelementptr could
1044             // only have at most one index, and because we fold getelementptr's
1045             // with a single zero index, it must be nonzero.
1046             assert(CE1->getNumOperands() == 2 &&
1047                    !CE1->getOperand(1)->isNullValue() &&
1048                    "Suprising getelementptr!");
1049             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1050           } else {
1051             // If they are different globals, we don't know what the value is,
1052             // but they can't be equal.
1053             return ICmpInst::ICMP_NE;
1054           }
1055         }
1056       } else {
1057         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1058         const Constant *CE2Op0 = CE2->getOperand(0);
1059
1060         // There are MANY other foldings that we could perform here.  They will
1061         // probably be added on demand, as they seem needed.
1062         switch (CE2->getOpcode()) {
1063         default: break;
1064         case Instruction::GetElementPtr:
1065           // By far the most common case to handle is when the base pointers are
1066           // obviously to the same or different globals.
1067           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1068             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1069               return ICmpInst::ICMP_NE;
1070             // Ok, we know that both getelementptr instructions are based on the
1071             // same global.  From this, we can precisely determine the relative
1072             // ordering of the resultant pointers.
1073             unsigned i = 1;
1074
1075             // Compare all of the operands the GEP's have in common.
1076             gep_type_iterator GTI = gep_type_begin(CE1);
1077             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1078                  ++i, ++GTI)
1079               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1080                                  GTI.getIndexedType())) {
1081               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1082               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1083               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1084               }
1085
1086             // Ok, we ran out of things they have in common.  If any leftovers
1087             // are non-zero then we have a difference, otherwise we are equal.
1088             for (; i < CE1->getNumOperands(); ++i)
1089               if (!CE1->getOperand(i)->isNullValue()) {
1090                 if (isa<ConstantInt>(CE1->getOperand(i)))
1091                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1092                 else
1093                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1094               }
1095
1096             for (; i < CE2->getNumOperands(); ++i)
1097               if (!CE2->getOperand(i)->isNullValue()) {
1098                 if (isa<ConstantInt>(CE2->getOperand(i)))
1099                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1100                 else
1101                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1102               }
1103             return ICmpInst::ICMP_EQ;
1104           }
1105         }
1106       }
1107     default:
1108       break;
1109     }
1110   }
1111
1112   return ICmpInst::BAD_ICMP_PREDICATE;
1113 }
1114
1115 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1116                                                const Constant *C1, 
1117                                                const Constant *C2) {
1118
1119   // Handle some degenerate cases first
1120   if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1121     return UndefValue::get(Type::Int1Ty);
1122
1123   // No compile-time operations on this type yet.
1124   if (C1->getType() == Type::PPC_FP128Ty)
1125     return 0;
1126
1127   // icmp eq/ne(null,GV) -> false/true
1128   if (C1->isNullValue()) {
1129     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1130       // Don't try to evaluate aliases.  External weak GV can be null.
1131       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1132         if (pred == ICmpInst::ICMP_EQ)
1133           return ConstantInt::getFalse();
1134         else if (pred == ICmpInst::ICMP_NE)
1135           return ConstantInt::getTrue();
1136       }
1137   // icmp eq/ne(GV,null) -> false/true
1138   } else if (C2->isNullValue()) {
1139     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1140       // Don't try to evaluate aliases.  External weak GV can be null.
1141       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1142         if (pred == ICmpInst::ICMP_EQ)
1143           return ConstantInt::getFalse();
1144         else if (pred == ICmpInst::ICMP_NE)
1145           return ConstantInt::getTrue();
1146       }
1147   }
1148
1149   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1150     APInt V1 = cast<ConstantInt>(C1)->getValue();
1151     APInt V2 = cast<ConstantInt>(C2)->getValue();
1152     switch (pred) {
1153     default: assert(0 && "Invalid ICmp Predicate"); return 0;
1154     case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1155     case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1156     case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1157     case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1158     case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1159     case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1160     case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1161     case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1162     case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1163     case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1164     }
1165   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1166     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1167     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1168     APFloat::cmpResult R = C1V.compare(C2V);
1169     switch (pred) {
1170     default: assert(0 && "Invalid FCmp Predicate"); return 0;
1171     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1172     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1173     case FCmpInst::FCMP_UNO:
1174       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1175     case FCmpInst::FCMP_ORD:
1176       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1177     case FCmpInst::FCMP_UEQ:
1178       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1179                                             R==APFloat::cmpEqual);
1180     case FCmpInst::FCMP_OEQ:   
1181       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1182     case FCmpInst::FCMP_UNE:
1183       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1184     case FCmpInst::FCMP_ONE:   
1185       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1186                                             R==APFloat::cmpGreaterThan);
1187     case FCmpInst::FCMP_ULT: 
1188       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1189                                             R==APFloat::cmpLessThan);
1190     case FCmpInst::FCMP_OLT:   
1191       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1192     case FCmpInst::FCMP_UGT:
1193       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1194                                             R==APFloat::cmpGreaterThan);
1195     case FCmpInst::FCMP_OGT:
1196       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1197     case FCmpInst::FCMP_ULE:
1198       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1199     case FCmpInst::FCMP_OLE: 
1200       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1201                                             R==APFloat::cmpEqual);
1202     case FCmpInst::FCMP_UGE:
1203       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1204     case FCmpInst::FCMP_OGE: 
1205       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1206                                             R==APFloat::cmpEqual);
1207     }
1208   } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1209     if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1210       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1211         for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1212           Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1213               const_cast<Constant*>(CP1->getOperand(i)),
1214               const_cast<Constant*>(CP2->getOperand(i)));
1215           if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1216             return CB;
1217         }
1218         // Otherwise, could not decide from any element pairs.
1219         return 0;
1220       } else if (pred == ICmpInst::ICMP_EQ) {
1221         for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1222           Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1223               const_cast<Constant*>(CP1->getOperand(i)),
1224               const_cast<Constant*>(CP2->getOperand(i)));
1225           if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1226             return CB;
1227         }
1228         // Otherwise, could not decide from any element pairs.
1229         return 0;
1230       }
1231     }
1232   }
1233
1234   if (C1->getType()->isFloatingPoint()) {
1235     switch (evaluateFCmpRelation(C1, C2)) {
1236     default: assert(0 && "Unknown relation!");
1237     case FCmpInst::FCMP_UNO:
1238     case FCmpInst::FCMP_ORD:
1239     case FCmpInst::FCMP_UEQ:
1240     case FCmpInst::FCMP_UNE:
1241     case FCmpInst::FCMP_ULT:
1242     case FCmpInst::FCMP_UGT:
1243     case FCmpInst::FCMP_ULE:
1244     case FCmpInst::FCMP_UGE:
1245     case FCmpInst::FCMP_TRUE:
1246     case FCmpInst::FCMP_FALSE:
1247     case FCmpInst::BAD_FCMP_PREDICATE:
1248       break; // Couldn't determine anything about these constants.
1249     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1250       return ConstantInt::get(Type::Int1Ty,
1251           pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1252           pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1253           pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1254     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1255       return ConstantInt::get(Type::Int1Ty,
1256           pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1257           pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1258           pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1259     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1260       return ConstantInt::get(Type::Int1Ty,
1261           pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1262           pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1263           pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1264     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1265       // We can only partially decide this relation.
1266       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1267         return ConstantInt::getFalse();
1268       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1269         return ConstantInt::getTrue();
1270       break;
1271     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1272       // We can only partially decide this relation.
1273       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1274         return ConstantInt::getFalse();
1275       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1276         return ConstantInt::getTrue();
1277       break;
1278     case ICmpInst::ICMP_NE: // We know that C1 != C2
1279       // We can only partially decide this relation.
1280       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1281         return ConstantInt::getFalse();
1282       if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1283         return ConstantInt::getTrue();
1284       break;
1285     }
1286   } else {
1287     // Evaluate the relation between the two constants, per the predicate.
1288     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1289     default: assert(0 && "Unknown relational!");
1290     case ICmpInst::BAD_ICMP_PREDICATE:
1291       break;  // Couldn't determine anything about these constants.
1292     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1293       // If we know the constants are equal, we can decide the result of this
1294       // computation precisely.
1295       return ConstantInt::get(Type::Int1Ty, 
1296                               pred == ICmpInst::ICMP_EQ  ||
1297                               pred == ICmpInst::ICMP_ULE ||
1298                               pred == ICmpInst::ICMP_SLE ||
1299                               pred == ICmpInst::ICMP_UGE ||
1300                               pred == ICmpInst::ICMP_SGE);
1301     case ICmpInst::ICMP_ULT:
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_ULT ||
1306                               pred == ICmpInst::ICMP_NE  ||
1307                               pred == ICmpInst::ICMP_ULE);
1308     case ICmpInst::ICMP_SLT:
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_SLT ||
1313                               pred == ICmpInst::ICMP_NE  ||
1314                               pred == ICmpInst::ICMP_SLE);
1315     case ICmpInst::ICMP_UGT:
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_UGT ||
1320                               pred == ICmpInst::ICMP_NE  ||
1321                               pred == ICmpInst::ICMP_UGE);
1322     case ICmpInst::ICMP_SGT:
1323       // If we know that C1 > C2, we can decide the result of this computation
1324       // precisely.
1325       return ConstantInt::get(Type::Int1Ty, 
1326                               pred == ICmpInst::ICMP_SGT ||
1327                               pred == ICmpInst::ICMP_NE  ||
1328                               pred == ICmpInst::ICMP_SGE);
1329     case ICmpInst::ICMP_ULE:
1330       // If we know that C1 <= C2, we can only partially decide this relation.
1331       if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1332       if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
1333       break;
1334     case ICmpInst::ICMP_SLE:
1335       // If we know that C1 <= C2, we can only partially decide this relation.
1336       if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1337       if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
1338       break;
1339
1340     case ICmpInst::ICMP_UGE:
1341       // If we know that C1 >= C2, we can only partially decide this relation.
1342       if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1343       if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
1344       break;
1345     case ICmpInst::ICMP_SGE:
1346       // If we know that C1 >= C2, we can only partially decide this relation.
1347       if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1348       if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
1349       break;
1350
1351     case ICmpInst::ICMP_NE:
1352       // If we know that C1 != C2, we can only partially decide this relation.
1353       if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1354       if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
1355       break;
1356     }
1357
1358     if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1359       // If C2 is a constant expr and C1 isn't, flop them around and fold the
1360       // other way if possible.
1361       switch (pred) {
1362       case ICmpInst::ICMP_EQ:
1363       case ICmpInst::ICMP_NE:
1364         // No change of predicate required.
1365         return ConstantFoldCompareInstruction(pred, C2, C1);
1366
1367       case ICmpInst::ICMP_ULT:
1368       case ICmpInst::ICMP_SLT:
1369       case ICmpInst::ICMP_UGT:
1370       case ICmpInst::ICMP_SGT:
1371       case ICmpInst::ICMP_ULE:
1372       case ICmpInst::ICMP_SLE:
1373       case ICmpInst::ICMP_UGE:
1374       case ICmpInst::ICMP_SGE:
1375         // Change the predicate as necessary to swap the operands.
1376         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1377         return ConstantFoldCompareInstruction(pred, C2, C1);
1378
1379       default:  // These predicates cannot be flopped around.
1380         break;
1381       }
1382     }
1383   }
1384   return 0;
1385 }
1386
1387 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1388                                           Constant* const *Idxs,
1389                                           unsigned NumIdx) {
1390   if (NumIdx == 0 ||
1391       (NumIdx == 1 && Idxs[0]->isNullValue()))
1392     return const_cast<Constant*>(C);
1393
1394   if (isa<UndefValue>(C)) {
1395     const PointerType *Ptr = cast<PointerType>(C->getType());
1396     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1397                                                        (Value **)Idxs,
1398                                                        (Value **)Idxs+NumIdx,
1399                                                        true);
1400     assert(Ty != 0 && "Invalid indices for GEP!");
1401     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1402   }
1403
1404   Constant *Idx0 = Idxs[0];
1405   if (C->isNullValue()) {
1406     bool isNull = true;
1407     for (unsigned i = 0, e = NumIdx; i != e; ++i)
1408       if (!Idxs[i]->isNullValue()) {
1409         isNull = false;
1410         break;
1411       }
1412     if (isNull) {
1413       const PointerType *Ptr = cast<PointerType>(C->getType());
1414       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1415                                                          (Value**)Idxs,
1416                                                          (Value**)Idxs+NumIdx,
1417                                                          true);
1418       assert(Ty != 0 && "Invalid indices for GEP!");
1419       return 
1420         ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1421     }
1422   }
1423
1424   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1425     // Combine Indices - If the source pointer to this getelementptr instruction
1426     // is a getelementptr instruction, combine the indices of the two
1427     // getelementptr instructions into a single instruction.
1428     //
1429     if (CE->getOpcode() == Instruction::GetElementPtr) {
1430       const Type *LastTy = 0;
1431       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1432            I != E; ++I)
1433         LastTy = *I;
1434
1435       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1436         SmallVector<Value*, 16> NewIndices;
1437         NewIndices.reserve(NumIdx + CE->getNumOperands());
1438         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1439           NewIndices.push_back(CE->getOperand(i));
1440
1441         // Add the last index of the source with the first index of the new GEP.
1442         // Make sure to handle the case when they are actually different types.
1443         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1444         // Otherwise it must be an array.
1445         if (!Idx0->isNullValue()) {
1446           const Type *IdxTy = Combined->getType();
1447           if (IdxTy != Idx0->getType()) {
1448             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1449             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
1450                                                           Type::Int64Ty);
1451             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1452           } else {
1453             Combined =
1454               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1455           }
1456         }
1457
1458         NewIndices.push_back(Combined);
1459         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1460         return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1461                                               NewIndices.size());
1462       }
1463     }
1464
1465     // Implement folding of:
1466     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1467     //                        long 0, long 0)
1468     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1469     //
1470     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1471       if (const PointerType *SPT =
1472           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1473         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1474           if (const ArrayType *CAT =
1475         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1476             if (CAT->getElementType() == SAT->getElementType())
1477               return ConstantExpr::getGetElementPtr(
1478                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
1479     }
1480     
1481     // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1482     // Into: inttoptr (i64 0 to i8*)
1483     // This happens with pointers to member functions in C++.
1484     if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1485         isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1486         cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1487       Constant *Base = CE->getOperand(0);
1488       Constant *Offset = Idxs[0];
1489       
1490       // Convert the smaller integer to the larger type.
1491       if (Offset->getType()->getPrimitiveSizeInBits() < 
1492           Base->getType()->getPrimitiveSizeInBits())
1493         Offset = ConstantExpr::getSExt(Offset, Base->getType());
1494       else if (Base->getType()->getPrimitiveSizeInBits() <
1495                Offset->getType()->getPrimitiveSizeInBits())
1496         Base = ConstantExpr::getZExt(Base, Base->getType());
1497       
1498       Base = ConstantExpr::getAdd(Base, Offset);
1499       return ConstantExpr::getIntToPtr(Base, CE->getType());
1500     }
1501   }
1502   return 0;
1503 }
1504