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