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