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