Fix constant folding of FP->int due to cut & paste error in last commit.
[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 namespace {
34   struct VISIBILITY_HIDDEN ConstRules {
35     ConstRules() {}
36     virtual ~ConstRules() {}
37
38     // Binary Operators...
39     virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
40     virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
41     virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
42     virtual Constant *urem(const Constant *V1, const Constant *V2) const = 0;
43     virtual Constant *srem(const Constant *V1, const Constant *V2) const = 0;
44     virtual Constant *frem(const Constant *V1, const Constant *V2) const = 0;
45     virtual Constant *udiv(const Constant *V1, const Constant *V2) const = 0;
46     virtual Constant *sdiv(const Constant *V1, const Constant *V2) const = 0;
47     virtual Constant *fdiv(const Constant *V1, const Constant *V2) const = 0;
48     virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
49     virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
50     virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
51     virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
52     virtual Constant *lshr(const Constant *V1, const Constant *V2) const = 0;
53     virtual Constant *ashr(const Constant *V1, const Constant *V2) const = 0;
54     virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
55     virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
56
57     // Casting operators.
58     virtual Constant *castToBool  (const Constant *V) const = 0;
59     virtual Constant *castToSByte (const Constant *V) const = 0;
60     virtual Constant *castToUByte (const Constant *V) const = 0;
61     virtual Constant *castToShort (const Constant *V) const = 0;
62     virtual Constant *castToUShort(const Constant *V) const = 0;
63     virtual Constant *castToInt   (const Constant *V) const = 0;
64     virtual Constant *castToUInt  (const Constant *V) const = 0;
65     virtual Constant *castToLong  (const Constant *V) const = 0;
66     virtual Constant *castToULong (const Constant *V) const = 0;
67     virtual Constant *castToFloat (const Constant *V) const = 0;
68     virtual Constant *castToDouble(const Constant *V) const = 0;
69     virtual Constant *castToPointer(const Constant *V,
70                                     const PointerType *Ty) const = 0;
71
72     // ConstRules::get - Return an instance of ConstRules for the specified
73     // constant operands.
74     //
75     static ConstRules &get(const Constant *V1, const Constant *V2);
76   private:
77     ConstRules(const ConstRules &);             // Do not implement
78     ConstRules &operator=(const ConstRules &);  // Do not implement
79   };
80 }
81
82
83 //===----------------------------------------------------------------------===//
84 //                             TemplateRules Class
85 //===----------------------------------------------------------------------===//
86 //
87 // TemplateRules - Implement a subclass of ConstRules that provides all
88 // operations as noops.  All other rules classes inherit from this class so
89 // that if functionality is needed in the future, it can simply be added here
90 // and to ConstRules without changing anything else...
91 //
92 // This class also provides subclasses with typesafe implementations of methods
93 // so that don't have to do type casting.
94 //
95 namespace {
96 template<class ArgType, class SubClassName>
97 class VISIBILITY_HIDDEN TemplateRules : public ConstRules {
98
99
100   //===--------------------------------------------------------------------===//
101   // Redirecting functions that cast to the appropriate types
102   //===--------------------------------------------------------------------===//
103
104   virtual Constant *add(const Constant *V1, const Constant *V2) const {
105     return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
106   }
107   virtual Constant *sub(const Constant *V1, const Constant *V2) const {
108     return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
109   }
110   virtual Constant *mul(const Constant *V1, const Constant *V2) const {
111     return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
112   }
113   virtual Constant *udiv(const Constant *V1, const Constant *V2) const {
114     return SubClassName::UDiv((const ArgType *)V1, (const ArgType *)V2);
115   }
116   virtual Constant *sdiv(const Constant *V1, const Constant *V2) const {
117     return SubClassName::SDiv((const ArgType *)V1, (const ArgType *)V2);
118   }
119   virtual Constant *fdiv(const Constant *V1, const Constant *V2) const {
120     return SubClassName::FDiv((const ArgType *)V1, (const ArgType *)V2);
121   }
122   virtual Constant *urem(const Constant *V1, const Constant *V2) const {
123     return SubClassName::URem((const ArgType *)V1, (const ArgType *)V2);
124   }
125   virtual Constant *srem(const Constant *V1, const Constant *V2) const {
126     return SubClassName::SRem((const ArgType *)V1, (const ArgType *)V2);
127   }
128   virtual Constant *frem(const Constant *V1, const Constant *V2) const {
129     return SubClassName::FRem((const ArgType *)V1, (const ArgType *)V2);
130   }
131   virtual Constant *op_and(const Constant *V1, const Constant *V2) const {
132     return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);
133   }
134   virtual Constant *op_or(const Constant *V1, const Constant *V2) const {
135     return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);
136   }
137   virtual Constant *op_xor(const Constant *V1, const Constant *V2) const {
138     return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);
139   }
140   virtual Constant *shl(const Constant *V1, const Constant *V2) const {
141     return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);
142   }
143   virtual Constant *lshr(const Constant *V1, const Constant *V2) const {
144     return SubClassName::LShr((const ArgType *)V1, (const ArgType *)V2);
145   }
146   virtual Constant *ashr(const Constant *V1, const Constant *V2) const {
147     return SubClassName::AShr((const ArgType *)V1, (const ArgType *)V2);
148   }
149
150   virtual Constant *lessthan(const Constant *V1, const Constant *V2) const {
151     return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
152   }
153   virtual Constant *equalto(const Constant *V1, const Constant *V2) const {
154     return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
155   }
156
157   // Casting operators.  ick
158   virtual Constant *castToBool(const Constant *V) const {
159     return SubClassName::CastToBool((const ArgType*)V);
160   }
161   virtual Constant *castToSByte(const Constant *V) const {
162     return SubClassName::CastToSByte((const ArgType*)V);
163   }
164   virtual Constant *castToUByte(const Constant *V) const {
165     return SubClassName::CastToUByte((const ArgType*)V);
166   }
167   virtual Constant *castToShort(const Constant *V) const {
168     return SubClassName::CastToShort((const ArgType*)V);
169   }
170   virtual Constant *castToUShort(const Constant *V) const {
171     return SubClassName::CastToUShort((const ArgType*)V);
172   }
173   virtual Constant *castToInt(const Constant *V) const {
174     return SubClassName::CastToInt((const ArgType*)V);
175   }
176   virtual Constant *castToUInt(const Constant *V) const {
177     return SubClassName::CastToUInt((const ArgType*)V);
178   }
179   virtual Constant *castToLong(const Constant *V) const {
180     return SubClassName::CastToLong((const ArgType*)V);
181   }
182   virtual Constant *castToULong(const Constant *V) const {
183     return SubClassName::CastToULong((const ArgType*)V);
184   }
185   virtual Constant *castToFloat(const Constant *V) const {
186     return SubClassName::CastToFloat((const ArgType*)V);
187   }
188   virtual Constant *castToDouble(const Constant *V) const {
189     return SubClassName::CastToDouble((const ArgType*)V);
190   }
191   virtual Constant *castToPointer(const Constant *V,
192                                   const PointerType *Ty) const {
193     return SubClassName::CastToPointer((const ArgType*)V, Ty);
194   }
195
196   //===--------------------------------------------------------------------===//
197   // Default "noop" implementations
198   //===--------------------------------------------------------------------===//
199
200   static Constant *Add (const ArgType *V1, const ArgType *V2) { return 0; }
201   static Constant *Sub (const ArgType *V1, const ArgType *V2) { return 0; }
202   static Constant *Mul (const ArgType *V1, const ArgType *V2) { return 0; }
203   static Constant *SDiv(const ArgType *V1, const ArgType *V2) { return 0; }
204   static Constant *UDiv(const ArgType *V1, const ArgType *V2) { return 0; }
205   static Constant *FDiv(const ArgType *V1, const ArgType *V2) { return 0; }
206   static Constant *URem(const ArgType *V1, const ArgType *V2) { return 0; }
207   static Constant *SRem(const ArgType *V1, const ArgType *V2) { return 0; }
208   static Constant *FRem(const ArgType *V1, const ArgType *V2) { return 0; }
209   static Constant *And (const ArgType *V1, const ArgType *V2) { return 0; }
210   static Constant *Or  (const ArgType *V1, const ArgType *V2) { return 0; }
211   static Constant *Xor (const ArgType *V1, const ArgType *V2) { return 0; }
212   static Constant *Shl (const ArgType *V1, const ArgType *V2) { return 0; }
213   static Constant *LShr(const ArgType *V1, const ArgType *V2) { return 0; }
214   static Constant *AShr(const ArgType *V1, const ArgType *V2) { return 0; }
215   static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
216     return 0;
217   }
218   static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
219     return 0;
220   }
221
222   // Casting operators.  ick
223   static Constant *CastToBool  (const Constant *V) { return 0; }
224   static Constant *CastToSByte (const Constant *V) { return 0; }
225   static Constant *CastToUByte (const Constant *V) { return 0; }
226   static Constant *CastToShort (const Constant *V) { return 0; }
227   static Constant *CastToUShort(const Constant *V) { return 0; }
228   static Constant *CastToInt   (const Constant *V) { return 0; }
229   static Constant *CastToUInt  (const Constant *V) { return 0; }
230   static Constant *CastToLong  (const Constant *V) { return 0; }
231   static Constant *CastToULong (const Constant *V) { return 0; }
232   static Constant *CastToFloat (const Constant *V) { return 0; }
233   static Constant *CastToDouble(const Constant *V) { return 0; }
234   static Constant *CastToPointer(const Constant *,
235                                  const PointerType *) {return 0;}
236
237 public:
238   virtual ~TemplateRules() {}
239 };
240 }  // end anonymous namespace
241
242
243 //===----------------------------------------------------------------------===//
244 //                             EmptyRules Class
245 //===----------------------------------------------------------------------===//
246 //
247 // EmptyRules provides a concrete base class of ConstRules that does nothing
248 //
249 namespace {
250 struct VISIBILITY_HIDDEN EmptyRules
251   : public TemplateRules<Constant, EmptyRules> {
252   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
253     if (V1 == V2) return ConstantBool::getTrue();
254     return 0;
255   }
256 };
257 }  // end anonymous namespace
258
259
260
261 //===----------------------------------------------------------------------===//
262 //                              BoolRules Class
263 //===----------------------------------------------------------------------===//
264 //
265 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
266 //
267 namespace {
268 struct VISIBILITY_HIDDEN BoolRules
269   : public TemplateRules<ConstantBool, BoolRules> {
270
271   static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2) {
272     return ConstantBool::get(V1->getValue() < V2->getValue());
273   }
274
275   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
276     return ConstantBool::get(V1 == V2);
277   }
278
279   static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
280     return ConstantBool::get(V1->getValue() & V2->getValue());
281   }
282
283   static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
284     return ConstantBool::get(V1->getValue() | V2->getValue());
285   }
286
287   static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
288     return ConstantBool::get(V1->getValue() ^ V2->getValue());
289   }
290
291   // Casting operators.  ick
292 #define DEF_CAST(TYPE, CLASS, CTYPE) \
293   static Constant *CastTo##TYPE  (const ConstantBool *V) {    \
294     return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
295   }
296
297   DEF_CAST(Bool  , ConstantBool, bool)
298   DEF_CAST(SByte , ConstantInt, signed char)
299   DEF_CAST(UByte , ConstantInt, unsigned char)
300   DEF_CAST(Short , ConstantInt, signed short)
301   DEF_CAST(UShort, ConstantInt, unsigned short)
302   DEF_CAST(Int   , ConstantInt, signed int)
303   DEF_CAST(UInt  , ConstantInt, unsigned int)
304   DEF_CAST(Long  , ConstantInt, int64_t)
305   DEF_CAST(ULong , ConstantInt, uint64_t)
306   DEF_CAST(Float , ConstantFP  , float)
307   DEF_CAST(Double, ConstantFP  , double)
308 #undef DEF_CAST
309 };
310 }  // end anonymous namespace
311
312
313 //===----------------------------------------------------------------------===//
314 //                            NullPointerRules Class
315 //===----------------------------------------------------------------------===//
316 //
317 // NullPointerRules provides a concrete base class of ConstRules for null
318 // pointers.
319 //
320 namespace {
321 struct VISIBILITY_HIDDEN NullPointerRules
322   : public TemplateRules<ConstantPointerNull, NullPointerRules> {
323   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
324     return ConstantBool::getTrue();  // Null pointers are always equal
325   }
326   static Constant *CastToBool(const Constant *V) {
327     return ConstantBool::getFalse();
328   }
329   static Constant *CastToSByte (const Constant *V) {
330     return ConstantInt::get(Type::SByteTy, 0);
331   }
332   static Constant *CastToUByte (const Constant *V) {
333     return ConstantInt::get(Type::UByteTy, 0);
334   }
335   static Constant *CastToShort (const Constant *V) {
336     return ConstantInt::get(Type::ShortTy, 0);
337   }
338   static Constant *CastToUShort(const Constant *V) {
339     return ConstantInt::get(Type::UShortTy, 0);
340   }
341   static Constant *CastToInt   (const Constant *V) {
342     return ConstantInt::get(Type::IntTy, 0);
343   }
344   static Constant *CastToUInt  (const Constant *V) {
345     return ConstantInt::get(Type::UIntTy, 0);
346   }
347   static Constant *CastToLong  (const Constant *V) {
348     return ConstantInt::get(Type::LongTy, 0);
349   }
350   static Constant *CastToULong (const Constant *V) {
351     return ConstantInt::get(Type::ULongTy, 0);
352   }
353   static Constant *CastToFloat (const Constant *V) {
354     return ConstantFP::get(Type::FloatTy, 0);
355   }
356   static Constant *CastToDouble(const Constant *V) {
357     return ConstantFP::get(Type::DoubleTy, 0);
358   }
359
360   static Constant *CastToPointer(const ConstantPointerNull *V,
361                                  const PointerType *PTy) {
362     return ConstantPointerNull::get(PTy);
363   }
364 };
365 }  // end anonymous namespace
366
367 //===----------------------------------------------------------------------===//
368 //                          ConstantPackedRules Class
369 //===----------------------------------------------------------------------===//
370
371 /// DoVectorOp - Given two packed constants and a function pointer, apply the
372 /// function pointer to each element pair, producing a new ConstantPacked
373 /// constant.
374 static Constant *EvalVectorOp(const ConstantPacked *V1, 
375                               const ConstantPacked *V2,
376                               Constant *(*FP)(Constant*, Constant*)) {
377   std::vector<Constant*> Res;
378   for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
379     Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
380                      const_cast<Constant*>(V2->getOperand(i))));
381   return ConstantPacked::get(Res);
382 }
383
384 /// PackedTypeRules provides a concrete base class of ConstRules for
385 /// ConstantPacked operands.
386 ///
387 namespace {
388 struct VISIBILITY_HIDDEN ConstantPackedRules
389   : public TemplateRules<ConstantPacked, ConstantPackedRules> {
390   
391   static Constant *Add(const ConstantPacked *V1, const ConstantPacked *V2) {
392     return EvalVectorOp(V1, V2, ConstantExpr::getAdd);
393   }
394   static Constant *Sub(const ConstantPacked *V1, const ConstantPacked *V2) {
395     return EvalVectorOp(V1, V2, ConstantExpr::getSub);
396   }
397   static Constant *Mul(const ConstantPacked *V1, const ConstantPacked *V2) {
398     return EvalVectorOp(V1, V2, ConstantExpr::getMul);
399   }
400   static Constant *UDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
401     return EvalVectorOp(V1, V2, ConstantExpr::getUDiv);
402   }
403   static Constant *SDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
404     return EvalVectorOp(V1, V2, ConstantExpr::getSDiv);
405   }
406   static Constant *FDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
407     return EvalVectorOp(V1, V2, ConstantExpr::getFDiv);
408   }
409   static Constant *URem(const ConstantPacked *V1, const ConstantPacked *V2) {
410     return EvalVectorOp(V1, V2, ConstantExpr::getURem);
411   }
412   static Constant *SRem(const ConstantPacked *V1, const ConstantPacked *V2) {
413     return EvalVectorOp(V1, V2, ConstantExpr::getSRem);
414   }
415   static Constant *FRem(const ConstantPacked *V1, const ConstantPacked *V2) {
416     return EvalVectorOp(V1, V2, ConstantExpr::getFRem);
417   }
418   static Constant *And(const ConstantPacked *V1, const ConstantPacked *V2) {
419     return EvalVectorOp(V1, V2, ConstantExpr::getAnd);
420   }
421   static Constant *Or (const ConstantPacked *V1, const ConstantPacked *V2) {
422     return EvalVectorOp(V1, V2, ConstantExpr::getOr);
423   }
424   static Constant *Xor(const ConstantPacked *V1, const ConstantPacked *V2) {
425     return EvalVectorOp(V1, V2, ConstantExpr::getXor);
426   }
427   static Constant *LessThan(const ConstantPacked *V1, const ConstantPacked *V2){
428     return 0;
429   }
430   static Constant *EqualTo(const ConstantPacked *V1, const ConstantPacked *V2) {
431     for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i) {
432       Constant *C = 
433         ConstantExpr::getSetEQ(const_cast<Constant*>(V1->getOperand(i)),
434                                const_cast<Constant*>(V2->getOperand(i)));
435       if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
436         return CB;
437     }
438     // Otherwise, could not decide from any element pairs.
439     return 0;
440   }
441 };
442 }  // end anonymous namespace
443
444
445 //===----------------------------------------------------------------------===//
446 //                          GeneralPackedRules Class
447 //===----------------------------------------------------------------------===//
448
449 /// GeneralPackedRules provides a concrete base class of ConstRules for
450 /// PackedType operands, where both operands are not ConstantPacked.  The usual
451 /// cause for this is that one operand is a ConstantAggregateZero.
452 ///
453 namespace {
454 struct VISIBILITY_HIDDEN GeneralPackedRules
455   : public TemplateRules<Constant, GeneralPackedRules> {
456 };
457 }  // end anonymous namespace
458
459
460 //===----------------------------------------------------------------------===//
461 //                           DirectIntRules Class
462 //===----------------------------------------------------------------------===//
463 //
464 // DirectIntRules provides implementations of functions that are valid on
465 // integer types, but not all types in general.
466 //
467 namespace {
468 template <class BuiltinType, Type **Ty>
469 struct VISIBILITY_HIDDEN DirectIntRules
470   : public TemplateRules<ConstantInt, DirectIntRules<BuiltinType, Ty> > {
471
472   static Constant *Add(const ConstantInt *V1, const ConstantInt *V2) {
473     BuiltinType R = (BuiltinType)V1->getZExtValue() + 
474                     (BuiltinType)V2->getZExtValue();
475     return ConstantInt::get(*Ty, R);
476   }
477
478   static Constant *Sub(const ConstantInt *V1, const ConstantInt *V2) {
479     BuiltinType R = (BuiltinType)V1->getZExtValue() - 
480                     (BuiltinType)V2->getZExtValue();
481     return ConstantInt::get(*Ty, R);
482   }
483
484   static Constant *Mul(const ConstantInt *V1, const ConstantInt *V2) {
485     BuiltinType R = (BuiltinType)V1->getZExtValue() * 
486                     (BuiltinType)V2->getZExtValue();
487     return ConstantInt::get(*Ty, R);
488   }
489
490   static Constant *LessThan(const ConstantInt *V1, const ConstantInt *V2) {
491     bool R = (BuiltinType)V1->getZExtValue() < (BuiltinType)V2->getZExtValue();
492     return ConstantBool::get(R);
493   }
494
495   static Constant *EqualTo(const ConstantInt *V1, const ConstantInt *V2) {
496     bool R = (BuiltinType)V1->getZExtValue() == (BuiltinType)V2->getZExtValue();
497     return ConstantBool::get(R);
498   }
499
500   static Constant *CastToPointer(const ConstantInt *V,
501                                  const PointerType *PTy) {
502     if (V->isNullValue())    // Is it a FP or Integral null value?
503       return ConstantPointerNull::get(PTy);
504     return 0;  // Can't const prop other types of pointers
505   }
506
507   // Casting operators.  ick
508 #define DEF_CAST(TYPE, CLASS, CTYPE) \
509   static Constant *CastTo##TYPE  (const ConstantInt *V) {    \
510     return CLASS::get(Type::TYPE##Ty, (CTYPE)((BuiltinType)V->getZExtValue()));\
511   }
512
513   DEF_CAST(Bool  , ConstantBool, bool)
514   DEF_CAST(SByte , ConstantInt, signed char)
515   DEF_CAST(UByte , ConstantInt, unsigned char)
516   DEF_CAST(Short , ConstantInt, signed short)
517   DEF_CAST(UShort, ConstantInt, unsigned short)
518   DEF_CAST(Int   , ConstantInt, signed int)
519   DEF_CAST(UInt  , ConstantInt, unsigned int)
520   DEF_CAST(Long  , ConstantInt, int64_t)
521   DEF_CAST(ULong , ConstantInt, uint64_t)
522   DEF_CAST(Float , ConstantFP , float)
523   DEF_CAST(Double, ConstantFP , double)
524 #undef DEF_CAST
525
526   static Constant *UDiv(const ConstantInt *V1, const ConstantInt *V2) {
527     if (V2->isNullValue())                   // X / 0
528       return 0;
529     BuiltinType R = (BuiltinType)(V1->getZExtValue() / V2->getZExtValue());
530     return ConstantInt::get(*Ty, R);
531   }
532
533   static Constant *SDiv(const ConstantInt *V1, const ConstantInt *V2) {
534     if (V2->isNullValue())                   // X / 0
535       return 0;
536     if (V2->isAllOnesValue() &&              // MIN_INT / -1
537         (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
538       return 0;
539     BuiltinType R = (BuiltinType)(V1->getSExtValue() / V2->getSExtValue());
540     return ConstantInt::get(*Ty, R);
541   }
542
543   static Constant *URem(const ConstantInt *V1,
544                         const ConstantInt *V2) {
545     if (V2->isNullValue()) return 0;         // X / 0
546     BuiltinType R = (BuiltinType)(V1->getZExtValue() % V2->getZExtValue());
547     return ConstantInt::get(*Ty, R);
548   }
549
550   static Constant *SRem(const ConstantInt *V1,
551                         const ConstantInt *V2) {
552     if (V2->isNullValue()) return 0;         // X % 0
553     if (V2->isAllOnesValue() &&              // MIN_INT % -1
554         (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
555       return 0;
556     BuiltinType R = (BuiltinType)(V1->getSExtValue() % V2->getSExtValue());
557     return ConstantInt::get(*Ty, R);
558   }
559
560   static Constant *And(const ConstantInt *V1, const ConstantInt *V2) {
561     BuiltinType R = 
562       (BuiltinType)V1->getZExtValue() & (BuiltinType)V2->getZExtValue();
563     return ConstantInt::get(*Ty, R);
564   }
565   static Constant *Or(const ConstantInt *V1, const ConstantInt *V2) {
566     BuiltinType R = 
567       (BuiltinType)V1->getZExtValue() | (BuiltinType)V2->getZExtValue();
568     return ConstantInt::get(*Ty, R);
569   }
570   static Constant *Xor(const ConstantInt *V1, const ConstantInt *V2) {
571     BuiltinType R = 
572       (BuiltinType)V1->getZExtValue() ^ (BuiltinType)V2->getZExtValue();
573     return ConstantInt::get(*Ty, R);
574   }
575
576   static Constant *Shl(const ConstantInt *V1, const ConstantInt *V2) {
577     BuiltinType R = 
578       (BuiltinType)V1->getZExtValue() << (BuiltinType)V2->getZExtValue();
579     return ConstantInt::get(*Ty, R);
580   }
581
582   static Constant *LShr(const ConstantInt *V1, const ConstantInt *V2) {
583     BuiltinType R = BuiltinType(V1->getZExtValue() >> V2->getZExtValue());
584     return ConstantInt::get(*Ty, R);
585   }
586
587   static Constant *AShr(const ConstantInt *V1, const ConstantInt *V2) {
588     BuiltinType R = BuiltinType(V1->getSExtValue() >> V2->getZExtValue());
589     return ConstantInt::get(*Ty, R);
590   }
591 };
592 }  // end anonymous namespace
593
594
595 //===----------------------------------------------------------------------===//
596 //                           DirectFPRules Class
597 //===----------------------------------------------------------------------===//
598 //
599 /// DirectFPRules provides implementations of functions that are valid on
600 /// floating point types, but not all types in general.
601 ///
602 namespace {
603 template <class BuiltinType, Type **Ty>
604 struct VISIBILITY_HIDDEN DirectFPRules
605   : public TemplateRules<ConstantFP, DirectFPRules<BuiltinType, Ty> > {
606
607   static Constant *Add(const ConstantFP *V1, const ConstantFP *V2) {
608     BuiltinType R = (BuiltinType)V1->getValue() + 
609                     (BuiltinType)V2->getValue();
610     return ConstantFP::get(*Ty, R);
611   }
612
613   static Constant *Sub(const ConstantFP *V1, const ConstantFP *V2) {
614     BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
615     return ConstantFP::get(*Ty, R);
616   }
617
618   static Constant *Mul(const ConstantFP *V1, const ConstantFP *V2) {
619     BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
620     return ConstantFP::get(*Ty, R);
621   }
622
623   static Constant *LessThan(const ConstantFP *V1, const ConstantFP *V2) {
624     bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
625     return ConstantBool::get(R);
626   }
627
628   static Constant *EqualTo(const ConstantFP *V1, const ConstantFP *V2) {
629     bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
630     return ConstantBool::get(R);
631   }
632
633   static Constant *CastToPointer(const ConstantFP *V,
634                                  const PointerType *PTy) {
635     if (V->isNullValue())    // Is it a FP or Integral null value?
636       return ConstantPointerNull::get(PTy);
637     return 0;  // Can't const prop other types of pointers
638   }
639
640   // Casting operators.  ick
641 #define DEF_CAST(TYPE, CLASS, CTYPE) \
642   static Constant *CastTo##TYPE  (const ConstantFP *V) {    \
643     return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
644   }
645
646   DEF_CAST(Bool  , ConstantBool, bool)
647   DEF_CAST(SByte , ConstantInt, signed char)
648   DEF_CAST(UByte , ConstantInt, unsigned char)
649   DEF_CAST(Short , ConstantInt, signed short)
650   DEF_CAST(UShort, ConstantInt, unsigned short)
651   DEF_CAST(Int   , ConstantInt, signed int)
652   DEF_CAST(UInt  , ConstantInt, unsigned int)
653   DEF_CAST(Long  , ConstantInt, int64_t)
654   DEF_CAST(ULong , ConstantInt, uint64_t)
655   DEF_CAST(Float , ConstantFP , float)
656   DEF_CAST(Double, ConstantFP , double)
657 #undef DEF_CAST
658
659   static Constant *FRem(const ConstantFP *V1, const ConstantFP *V2) {
660     if (V2->isNullValue()) return 0;
661     BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
662                                    (BuiltinType)V2->getValue());
663     return ConstantFP::get(*Ty, Result);
664   }
665   static Constant *FDiv(const ConstantFP *V1, const ConstantFP *V2) {
666     BuiltinType inf = std::numeric_limits<BuiltinType>::infinity();
667     if (V2->isExactlyValue(0.0)) return ConstantFP::get(*Ty, inf);
668     if (V2->isExactlyValue(-0.0)) return ConstantFP::get(*Ty, -inf);
669     BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
670     return ConstantFP::get(*Ty, R);
671   }
672 };
673 }  // end anonymous namespace
674
675 static ManagedStatic<EmptyRules>       EmptyR;
676 static ManagedStatic<BoolRules>        BoolR;
677 static ManagedStatic<NullPointerRules> NullPointerR;
678 static ManagedStatic<ConstantPackedRules> ConstantPackedR;
679 static ManagedStatic<GeneralPackedRules> GeneralPackedR;
680 static ManagedStatic<DirectIntRules<signed char   , &Type::SByteTy> > SByteR;
681 static ManagedStatic<DirectIntRules<unsigned char , &Type::UByteTy> > UByteR;
682 static ManagedStatic<DirectIntRules<signed short  , &Type::ShortTy> > ShortR;
683 static ManagedStatic<DirectIntRules<unsigned short, &Type::UShortTy> > UShortR;
684 static ManagedStatic<DirectIntRules<signed int    , &Type::IntTy> >   IntR;
685 static ManagedStatic<DirectIntRules<unsigned int  , &Type::UIntTy> >  UIntR;
686 static ManagedStatic<DirectIntRules<int64_t       , &Type::LongTy> >  LongR;
687 static ManagedStatic<DirectIntRules<uint64_t      , &Type::ULongTy> > ULongR;
688 static ManagedStatic<DirectFPRules <float         , &Type::FloatTy> > FloatR;
689 static ManagedStatic<DirectFPRules <double        , &Type::DoubleTy> > DoubleR;
690
691 /// ConstRules::get - This method returns the constant rules implementation that
692 /// implements the semantics of the two specified constants.
693 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
694   if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
695       isa<GlobalValue>(V1) || isa<GlobalValue>(V2) ||
696       isa<UndefValue>(V1) || isa<UndefValue>(V2))
697     return *EmptyR;
698
699   switch (V1->getType()->getTypeID()) {
700   default: assert(0 && "Unknown value type for constant folding!");
701   case Type::BoolTyID:    return *BoolR;
702   case Type::PointerTyID: return *NullPointerR;
703   case Type::SByteTyID:   return *SByteR;
704   case Type::UByteTyID:   return *UByteR;
705   case Type::ShortTyID:   return *ShortR;
706   case Type::UShortTyID:  return *UShortR;
707   case Type::IntTyID:     return *IntR;
708   case Type::UIntTyID:    return *UIntR;
709   case Type::LongTyID:    return *LongR;
710   case Type::ULongTyID:   return *ULongR;
711   case Type::FloatTyID:   return *FloatR;
712   case Type::DoubleTyID:  return *DoubleR;
713   case Type::PackedTyID:
714     if (isa<ConstantPacked>(V1) && isa<ConstantPacked>(V2))
715       return *ConstantPackedR;
716     return *GeneralPackedR; // Constant folding rules for ConstantAggregateZero.
717   }
718 }
719
720
721 //===----------------------------------------------------------------------===//
722 //                ConstantFold*Instruction Implementations
723 //===----------------------------------------------------------------------===//
724
725 /// CastConstantPacked - Convert the specified ConstantPacked node to the
726 /// specified packed type.  At this point, we know that the elements of the
727 /// input packed constant are all simple integer or FP values.
728 static Constant *CastConstantPacked(ConstantPacked *CP,
729                                     const PackedType *DstTy) {
730   unsigned SrcNumElts = CP->getType()->getNumElements();
731   unsigned DstNumElts = DstTy->getNumElements();
732   const Type *SrcEltTy = CP->getType()->getElementType();
733   const Type *DstEltTy = DstTy->getElementType();
734   
735   // If both vectors have the same number of elements (thus, the elements
736   // are the same size), perform the conversion now.
737   if (SrcNumElts == DstNumElts) {
738     std::vector<Constant*> Result;
739     
740     // If the src and dest elements are both integers, or both floats, we can 
741     // just BitCast each element because the elements are the same size.
742     if ((SrcEltTy->isIntegral() && DstEltTy->isIntegral()) ||
743         (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
744       for (unsigned i = 0; i != SrcNumElts; ++i)
745         Result.push_back(
746           ConstantExpr::getCast(Instruction::BitCast, CP->getOperand(i), 
747                                 DstEltTy));
748       return ConstantPacked::get(Result);
749     }
750     
751     // If this is an int-to-fp cast ..
752     if (SrcEltTy->isIntegral()) {
753       // Ensure that it is int-to-fp cast
754       assert(DstEltTy->isFloatingPoint());
755       if (DstEltTy->getTypeID() == Type::DoubleTyID) {
756         for (unsigned i = 0; i != SrcNumElts; ++i) {
757           double V =
758             BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
759           Result.push_back(ConstantFP::get(Type::DoubleTy, V));
760         }
761         return ConstantPacked::get(Result);
762       }
763       assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
764       for (unsigned i = 0; i != SrcNumElts; ++i) {
765         float V =
766         BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
767         Result.push_back(ConstantFP::get(Type::FloatTy, V));
768       }
769       return ConstantPacked::get(Result);
770     }
771     
772     // Otherwise, this is an fp-to-int cast.
773     assert(SrcEltTy->isFloatingPoint() && DstEltTy->isIntegral());
774     
775     if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
776       for (unsigned i = 0; i != SrcNumElts; ++i) {
777         uint64_t V =
778           DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
779         Constant *C = ConstantInt::get(Type::ULongTy, V);
780         Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
781       }
782       return ConstantPacked::get(Result);
783     }
784
785     assert(SrcEltTy->getTypeID() == Type::FloatTyID);
786     for (unsigned i = 0; i != SrcNumElts; ++i) {
787       uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
788       Constant *C = ConstantInt::get(Type::UIntTy, V);
789       Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
790     }
791     return ConstantPacked::get(Result);
792   }
793   
794   // Otherwise, this is a cast that changes element count and size.  Handle
795   // casts which shrink the elements here.
796   
797   // FIXME: We need to know endianness to do this!
798   
799   return 0;
800 }
801
802 /// This function determines which opcode to use to fold two constant cast 
803 /// expressions together. It uses CastInst::isEliminableCastPair to determine
804 /// the opcode. Consequently its just a wrapper around that function.
805 /// @Determine if it is valid to fold a cast of a cast
806 static unsigned
807 foldConstantCastPair(
808   unsigned opc,          ///< opcode of the second cast constant expression
809   const ConstantExpr*Op, ///< the first cast constant expression
810   const Type *DstTy      ///< desintation type of the first cast
811 ) {
812   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
813   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
814   assert(CastInst::isCast(opc) && "Invalid cast opcode");
815   
816   // The the types and opcodes for the two Cast constant expressions
817   const Type *SrcTy = Op->getOperand(0)->getType();
818   const Type *MidTy = Op->getType();
819   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
820   Instruction::CastOps secondOp = Instruction::CastOps(opc);
821
822   // Let CastInst::isEliminableCastPair do the heavy lifting.
823   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
824                                         Type::ULongTy);
825 }
826
827 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
828                                             const Type *DestTy) {
829   const Type *SrcTy = V->getType();
830
831   if (isa<UndefValue>(V))
832     return UndefValue::get(DestTy);
833
834   // If the cast operand is a constant expression, there's a few things we can
835   // do to try to simplify it.
836   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
837     if (CE->isCast()) {
838       // Try hard to fold cast of cast because they are often eliminable.
839       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
840         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
841     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
842       // If all of the indexes in the GEP are null values, there is no pointer
843       // adjustment going on.  We might as well cast the source pointer.
844       bool isAllNull = true;
845       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
846         if (!CE->getOperand(i)->isNullValue()) {
847           isAllNull = false;
848           break;
849         }
850       if (isAllNull)
851         // This is casting one pointer type to another, always BitCast
852         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
853     }
854   }
855
856   // We actually have to do a cast now, but first, we might need to fix up
857   // the value of the operand.
858   switch (opc) {
859   case Instruction::PtrToInt:
860   case Instruction::FPTrunc:
861   case Instruction::FPExt:
862     break;
863   case Instruction::FPToUI: {
864     ConstRules &Rules = ConstRules::get(V, V);
865     V = Rules.castToULong(V); // make sure we get an unsigned value first 
866     break;
867   }
868   case Instruction::FPToSI: {
869     ConstRules &Rules = ConstRules::get(V, V);
870     V = Rules.castToLong(V); // make sure we get a signed value first 
871     break;
872   }
873   case Instruction::IntToPtr: //always treated as unsigned
874   case Instruction::UIToFP:
875   case Instruction::ZExt:
876     // A ZExt always produces an unsigned value so we need to cast the value
877     // now before we try to cast it to the destination type
878     if (isa<ConstantInt>(V))
879       V = ConstantInt::get(SrcTy->getUnsignedVersion(), 
880                            cast<ConstantIntegral>(V)->getZExtValue());
881     break;
882   case Instruction::SIToFP:
883   case Instruction::SExt:
884     // A SExt always produces a signed value so we need to cast the value
885     // now before we try to cast it to the destiniation type.
886     if (isa<ConstantInt>(V))
887       V = ConstantInt::get(SrcTy->getSignedVersion(), 
888                            cast<ConstantIntegral>(V)->getSExtValue());
889     else if (const ConstantBool *CB = dyn_cast<ConstantBool>(V))
890       V = ConstantInt::get(Type::SByteTy, CB->getValue() ? -1 : 0);
891       
892     break;
893   case Instruction::Trunc:
894     // We just handle trunc directly here.  The code below doesn't work for
895     // trunc to bool.
896     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
897       return ConstantIntegral::get(DestTy, CI->getZExtValue());
898     return 0;
899   case Instruction::BitCast:
900     if (SrcTy == DestTy) return (Constant*)V; // no-op cast
901     
902     // Check to see if we are casting a pointer to an aggregate to a pointer to
903     // the first element.  If so, return the appropriate GEP instruction.
904     if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
905       if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
906         std::vector<Value*> IdxList;
907         IdxList.push_back(Constant::getNullValue(Type::IntTy));
908         const Type *ElTy = PTy->getElementType();
909         while (ElTy != DPTy->getElementType()) {
910           if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
911             if (STy->getNumElements() == 0) break;
912             ElTy = STy->getElementType(0);
913             IdxList.push_back(Constant::getNullValue(Type::UIntTy));
914           } else if (const SequentialType *STy = 
915                      dyn_cast<SequentialType>(ElTy)) {
916             if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
917             ElTy = STy->getElementType();
918             IdxList.push_back(IdxList[0]);
919           } else {
920             break;
921           }
922         }
923
924         if (ElTy == DPTy->getElementType())
925           return ConstantExpr::getGetElementPtr(
926               const_cast<Constant*>(V),IdxList);
927       }
928         
929     // Handle casts from one packed constant to another.  We know that the src 
930     // and dest type have the same size (otherwise its an illegal cast).
931     if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
932       if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
933         assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
934                "Not cast between same sized vectors!");
935         // First, check for null and undef
936         if (isa<ConstantAggregateZero>(V))
937           return Constant::getNullValue(DestTy);
938         if (isa<UndefValue>(V))
939           return UndefValue::get(DestTy);
940
941         if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
942           // This is a cast from a ConstantPacked of one type to a 
943           // ConstantPacked of another type.  Check to see if all elements of 
944           // the input are simple.
945           bool AllSimpleConstants = true;
946           for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
947             if (!isa<ConstantInt>(CP->getOperand(i)) &&
948                 !isa<ConstantFP>(CP->getOperand(i))) {
949               AllSimpleConstants = false;
950               break;
951             }
952           }
953               
954           // If all of the elements are simple constants, we can fold this.
955           if (AllSimpleConstants)
956             return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
957         }
958       }
959     }
960
961     // Finally, implement bitcast folding now.   The code below doesn't handle
962     // bitcast right.
963     if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
964       return ConstantPointerNull::get(cast<PointerType>(DestTy));
965
966     // Handle integral constant input.
967     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
968       // Integral -> Integral, must be changing sign.
969       if (DestTy->isIntegral())
970         return ConstantInt::get(DestTy, CI->getZExtValue());
971
972       if (DestTy->isFloatingPoint()) {
973         if (DestTy == Type::FloatTy)
974           return ConstantFP::get(DestTy, BitsToFloat(CI->getZExtValue()));
975         assert(DestTy == Type::DoubleTy && "Unknown FP type!");
976         return ConstantFP::get(DestTy, BitsToDouble(CI->getZExtValue()));
977       }
978       // Otherwise, can't fold this (packed?)
979       return 0;
980     }
981       
982     // Handle ConstantFP input.
983     if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
984       // FP -> Integral.
985       if (DestTy->isIntegral()) {
986         if (DestTy == Type::IntTy || DestTy == Type::UIntTy)
987           return ConstantInt::get(DestTy, FloatToBits(FP->getValue()));
988         assert((DestTy == Type::LongTy || DestTy == Type::ULongTy) 
989                && "Incorrect integer  type for bitcast!");
990         return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
991       }
992     }
993     return 0;
994   default:
995     assert(!"Invalid CE CastInst opcode");
996     break;
997   }
998
999   // Okay, no more folding possible, time to cast
1000   ConstRules &Rules = ConstRules::get(V, V);
1001   switch (DestTy->getTypeID()) {
1002   case Type::BoolTyID:    return Rules.castToBool(V);
1003   case Type::UByteTyID:   return Rules.castToUByte(V);
1004   case Type::SByteTyID:   return Rules.castToSByte(V);
1005   case Type::UShortTyID:  return Rules.castToUShort(V);
1006   case Type::ShortTyID:   return Rules.castToShort(V);
1007   case Type::UIntTyID:    return Rules.castToUInt(V);
1008   case Type::IntTyID:     return Rules.castToInt(V);
1009   case Type::ULongTyID:   return Rules.castToULong(V);
1010   case Type::LongTyID:    return Rules.castToLong(V);
1011   case Type::FloatTyID:   return Rules.castToFloat(V);
1012   case Type::DoubleTyID:  return Rules.castToDouble(V);
1013   case Type::PointerTyID:
1014     return Rules.castToPointer(V, cast<PointerType>(DestTy));
1015   // what about packed ?
1016   default: return 0;
1017   }
1018 }
1019
1020 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
1021                                               const Constant *V1,
1022                                               const Constant *V2) {
1023   if (const ConstantBool *CB = dyn_cast<ConstantBool>(Cond))
1024     return const_cast<Constant*>(CB->getValue() ? V1 : V2);
1025
1026   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
1027   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
1028   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
1029   if (V1 == V2) return const_cast<Constant*>(V1);
1030   return 0;
1031 }
1032
1033 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
1034                                                       const Constant *Idx) {
1035   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
1036     return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
1037   if (Val->isNullValue())  // ee(zero, x) -> zero
1038     return Constant::getNullValue(
1039                           cast<PackedType>(Val->getType())->getElementType());
1040   
1041   if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
1042     if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
1043       return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
1044     } else if (isa<UndefValue>(Idx)) {
1045       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
1046       return const_cast<Constant*>(CVal->getOperand(0));
1047     }
1048   }
1049   return 0;
1050 }
1051
1052 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
1053                                                      const Constant *Elt,
1054                                                      const Constant *Idx) {
1055   const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
1056   if (!CIdx) return 0;
1057   uint64_t idxVal = CIdx->getZExtValue();
1058   if (isa<UndefValue>(Val)) { 
1059     // Insertion of scalar constant into packed undef
1060     // Optimize away insertion of undef
1061     if (isa<UndefValue>(Elt))
1062       return const_cast<Constant*>(Val);
1063     // Otherwise break the aggregate undef into multiple undefs and do
1064     // the insertion
1065     unsigned numOps = 
1066       cast<PackedType>(Val->getType())->getNumElements();
1067     std::vector<Constant*> Ops; 
1068     Ops.reserve(numOps);
1069     for (unsigned i = 0; i < numOps; ++i) {
1070       const Constant *Op =
1071         (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
1072       Ops.push_back(const_cast<Constant*>(Op));
1073     }
1074     return ConstantPacked::get(Ops);
1075   }
1076   if (isa<ConstantAggregateZero>(Val)) {
1077     // Insertion of scalar constant into packed aggregate zero
1078     // Optimize away insertion of zero
1079     if (Elt->isNullValue())
1080       return const_cast<Constant*>(Val);
1081     // Otherwise break the aggregate zero into multiple zeros and do
1082     // the insertion
1083     unsigned numOps = 
1084       cast<PackedType>(Val->getType())->getNumElements();
1085     std::vector<Constant*> Ops; 
1086     Ops.reserve(numOps);
1087     for (unsigned i = 0; i < numOps; ++i) {
1088       const Constant *Op =
1089         (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
1090       Ops.push_back(const_cast<Constant*>(Op));
1091     }
1092     return ConstantPacked::get(Ops);
1093   }
1094   if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
1095     // Insertion of scalar constant into packed constant
1096     std::vector<Constant*> Ops; 
1097     Ops.reserve(CVal->getNumOperands());
1098     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
1099       const Constant *Op =
1100         (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
1101       Ops.push_back(const_cast<Constant*>(Op));
1102     }
1103     return ConstantPacked::get(Ops);
1104   }
1105   return 0;
1106 }
1107
1108 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
1109                                                      const Constant *V2,
1110                                                      const Constant *Mask) {
1111   // TODO:
1112   return 0;
1113 }
1114
1115
1116 /// isZeroSizedType - This type is zero sized if its an array or structure of
1117 /// zero sized types.  The only leaf zero sized type is an empty structure.
1118 static bool isMaybeZeroSizedType(const Type *Ty) {
1119   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
1120   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1121
1122     // If all of elements have zero size, this does too.
1123     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1124       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1125     return true;
1126
1127   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1128     return isMaybeZeroSizedType(ATy->getElementType());
1129   }
1130   return false;
1131 }
1132
1133 /// IdxCompare - Compare the two constants as though they were getelementptr
1134 /// indices.  This allows coersion of the types to be the same thing.
1135 ///
1136 /// If the two constants are the "same" (after coersion), return 0.  If the
1137 /// first is less than the second, return -1, if the second is less than the
1138 /// first, return 1.  If the constants are not integral, return -2.
1139 ///
1140 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
1141   if (C1 == C2) return 0;
1142
1143   // Ok, we found a different index.  Are either of the operands ConstantExprs?
1144   // If so, we can't do anything with them.
1145   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1146     return -2; // don't know!
1147
1148   // Ok, we have two differing integer indices.  Sign extend them to be the same
1149   // type.  Long is always big enough, so we use it.
1150   if (C1->getType() != Type::LongTy && C1->getType() != Type::ULongTy)
1151     C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
1152   else
1153     C1 = ConstantExpr::getBitCast(C1, Type::LongTy);
1154   if (C2->getType() != Type::LongTy && C1->getType() != Type::ULongTy)
1155     C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
1156   else
1157     C2 = ConstantExpr::getBitCast(C2, Type::LongTy);
1158
1159   if (C1 == C2) return 0;  // Are they just differing types?
1160
1161   // If the type being indexed over is really just a zero sized type, there is
1162   // no pointer difference being made here.
1163   if (isMaybeZeroSizedType(ElTy))
1164     return -2; // dunno.
1165
1166   // If they are really different, now that they are the same type, then we
1167   // found a difference!
1168   if (cast<ConstantInt>(C1)->getSExtValue() < 
1169       cast<ConstantInt>(C2)->getSExtValue())
1170     return -1;
1171   else
1172     return 1;
1173 }
1174
1175 /// evaluateRelation - This function determines if there is anything we can
1176 /// decide about the two constants provided.  This doesn't need to handle simple
1177 /// things like integer comparisons, but should instead handle ConstantExprs
1178 /// and GlobalValues.  If we can determine that the two constants have a
1179 /// particular relation to each other, we should return the corresponding SetCC
1180 /// code, otherwise return Instruction::BinaryOpsEnd.
1181 ///
1182 /// To simplify this code we canonicalize the relation so that the first
1183 /// operand is always the most "complex" of the two.  We consider simple
1184 /// constants (like ConstantInt) to be the simplest, followed by
1185 /// GlobalValues, followed by ConstantExpr's (the most complex).
1186 ///
1187 static Instruction::BinaryOps evaluateRelation(Constant *V1, Constant *V2) {
1188   assert(V1->getType() == V2->getType() &&
1189          "Cannot compare different types of values!");
1190   if (V1 == V2) return Instruction::SetEQ;
1191
1192   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1193     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1194       // We distilled this down to a simple case, use the standard constant
1195       // folder.
1196       ConstantBool *R = dyn_cast<ConstantBool>(ConstantExpr::getSetEQ(V1, V2));
1197       if (R && R->getValue()) return Instruction::SetEQ;
1198       R = dyn_cast<ConstantBool>(ConstantExpr::getSetLT(V1, V2));
1199       if (R && R->getValue()) return Instruction::SetLT;
1200       R = dyn_cast<ConstantBool>(ConstantExpr::getSetGT(V1, V2));
1201       if (R && R->getValue()) return Instruction::SetGT;
1202       
1203       // If we couldn't figure it out, bail.
1204       return Instruction::BinaryOpsEnd;
1205     }
1206     
1207     // If the first operand is simple, swap operands.
1208     Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1209     if (SwappedRelation != Instruction::BinaryOpsEnd)
1210       return SetCondInst::getSwappedCondition(SwappedRelation);
1211
1212   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1213     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1214       Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1215       if (SwappedRelation != Instruction::BinaryOpsEnd)
1216         return SetCondInst::getSwappedCondition(SwappedRelation);
1217       else
1218         return Instruction::BinaryOpsEnd;
1219     }
1220
1221     // Now we know that the RHS is a GlobalValue or simple constant,
1222     // which (since the types must match) means that it's a ConstantPointerNull.
1223     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1224       if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1225         return Instruction::SetNE;
1226     } else {
1227       // GlobalVals can never be null.
1228       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1229       if (!CPR1->hasExternalWeakLinkage())
1230         return Instruction::SetNE;
1231     }
1232   } else {
1233     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1234     // constantexpr, a CPR, or a simple constant.
1235     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1236     Constant *CE1Op0 = CE1->getOperand(0);
1237
1238     switch (CE1->getOpcode()) {
1239     case Instruction::Trunc:
1240     case Instruction::FPTrunc:
1241     case Instruction::FPExt:
1242     case Instruction::FPToUI:
1243     case Instruction::FPToSI:
1244       break; // We don't do anything with floating point.
1245     case Instruction::ZExt:
1246     case Instruction::SExt:
1247     case Instruction::UIToFP:
1248     case Instruction::SIToFP:
1249     case Instruction::PtrToInt:
1250     case Instruction::IntToPtr:
1251     case Instruction::BitCast:
1252       // If the cast is not actually changing bits, and the second operand is a
1253       // null pointer, do the comparison with the pre-casted value.
1254       if (V2->isNullValue() &&
1255           (isa<PointerType>(CE1->getType()) || CE1->getType()->isIntegral()))
1256         return evaluateRelation(CE1Op0,
1257                                 Constant::getNullValue(CE1Op0->getType()));
1258
1259       // If the dest type is a pointer type, and the RHS is a constantexpr cast
1260       // from the same type as the src of the LHS, evaluate the inputs.  This is
1261       // important for things like "seteq (cast 4 to int*), (cast 5 to int*)",
1262       // which happens a lot in compilers with tagged integers.
1263       if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1264         if (isa<PointerType>(CE1->getType()) && CE2->isCast() &&
1265             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1266             CE1->getOperand(0)->getType()->isIntegral()) {
1267           return evaluateRelation(CE1->getOperand(0), CE2->getOperand(0));
1268         }
1269       break;
1270
1271     case Instruction::GetElementPtr:
1272       // Ok, since this is a getelementptr, we know that the constant has a
1273       // pointer type.  Check the various cases.
1274       if (isa<ConstantPointerNull>(V2)) {
1275         // If we are comparing a GEP to a null pointer, check to see if the base
1276         // of the GEP equals the null pointer.
1277         if (GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1278           if (GV->hasExternalWeakLinkage())
1279             // Weak linkage GVals could be zero or not. We're comparing that
1280             // to null pointer so its greater-or-equal
1281             return Instruction::SetGE;
1282           else 
1283             // If its not weak linkage, the GVal must have a non-zero address
1284             // so the result is greater-than
1285             return Instruction::SetGT;
1286         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1287           // If we are indexing from a null pointer, check to see if we have any
1288           // non-zero indices.
1289           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1290             if (!CE1->getOperand(i)->isNullValue())
1291               // Offsetting from null, must not be equal.
1292               return Instruction::SetGT;
1293           // Only zero indexes from null, must still be zero.
1294           return Instruction::SetEQ;
1295         }
1296         // Otherwise, we can't really say if the first operand is null or not.
1297       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1298         if (isa<ConstantPointerNull>(CE1Op0)) {
1299           if (CPR2->hasExternalWeakLinkage())
1300             // Weak linkage GVals could be zero or not. We're comparing it to
1301             // a null pointer, so its less-or-equal
1302             return Instruction::SetLE;
1303           else
1304             // If its not weak linkage, the GVal must have a non-zero address
1305             // so the result is less-than
1306             return Instruction::SetLT;
1307         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1308           if (CPR1 == CPR2) {
1309             // If this is a getelementptr of the same global, then it must be
1310             // different.  Because the types must match, the getelementptr could
1311             // only have at most one index, and because we fold getelementptr's
1312             // with a single zero index, it must be nonzero.
1313             assert(CE1->getNumOperands() == 2 &&
1314                    !CE1->getOperand(1)->isNullValue() &&
1315                    "Suprising getelementptr!");
1316             return Instruction::SetGT;
1317           } else {
1318             // If they are different globals, we don't know what the value is,
1319             // but they can't be equal.
1320             return Instruction::SetNE;
1321           }
1322         }
1323       } else {
1324         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1325         const Constant *CE2Op0 = CE2->getOperand(0);
1326
1327         // There are MANY other foldings that we could perform here.  They will
1328         // probably be added on demand, as they seem needed.
1329         switch (CE2->getOpcode()) {
1330         default: break;
1331         case Instruction::GetElementPtr:
1332           // By far the most common case to handle is when the base pointers are
1333           // obviously to the same or different globals.
1334           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1335             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1336               return Instruction::SetNE;
1337             // Ok, we know that both getelementptr instructions are based on the
1338             // same global.  From this, we can precisely determine the relative
1339             // ordering of the resultant pointers.
1340             unsigned i = 1;
1341
1342             // Compare all of the operands the GEP's have in common.
1343             gep_type_iterator GTI = gep_type_begin(CE1);
1344             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1345                  ++i, ++GTI)
1346               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1347                                  GTI.getIndexedType())) {
1348               case -1: return Instruction::SetLT;
1349               case 1:  return Instruction::SetGT;
1350               case -2: return Instruction::BinaryOpsEnd;
1351               }
1352
1353             // Ok, we ran out of things they have in common.  If any leftovers
1354             // are non-zero then we have a difference, otherwise we are equal.
1355             for (; i < CE1->getNumOperands(); ++i)
1356               if (!CE1->getOperand(i)->isNullValue())
1357                 if (isa<ConstantIntegral>(CE1->getOperand(i)))
1358                   return Instruction::SetGT;
1359                 else
1360                   return Instruction::BinaryOpsEnd; // Might be equal.
1361
1362             for (; i < CE2->getNumOperands(); ++i)
1363               if (!CE2->getOperand(i)->isNullValue())
1364                 if (isa<ConstantIntegral>(CE2->getOperand(i)))
1365                   return Instruction::SetLT;
1366                 else
1367                   return Instruction::BinaryOpsEnd; // Might be equal.
1368             return Instruction::SetEQ;
1369           }
1370         }
1371       }
1372
1373     default:
1374       break;
1375     }
1376   }
1377
1378   return Instruction::BinaryOpsEnd;
1379 }
1380
1381 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
1382                                               const Constant *V1,
1383                                               const Constant *V2) {
1384   Constant *C = 0;
1385   switch (Opcode) {
1386   default:                   break;
1387   case Instruction::Add:     C = ConstRules::get(V1, V2).add(V1, V2); break;
1388   case Instruction::Sub:     C = ConstRules::get(V1, V2).sub(V1, V2); break;
1389   case Instruction::Mul:     C = ConstRules::get(V1, V2).mul(V1, V2); break;
1390   case Instruction::UDiv:    C = ConstRules::get(V1, V2).udiv(V1, V2); break;
1391   case Instruction::SDiv:    C = ConstRules::get(V1, V2).sdiv(V1, V2); break;
1392   case Instruction::FDiv:    C = ConstRules::get(V1, V2).fdiv(V1, V2); break;
1393   case Instruction::URem:    C = ConstRules::get(V1, V2).urem(V1, V2); break;
1394   case Instruction::SRem:    C = ConstRules::get(V1, V2).srem(V1, V2); break;
1395   case Instruction::FRem:    C = ConstRules::get(V1, V2).frem(V1, V2); break;
1396   case Instruction::And:     C = ConstRules::get(V1, V2).op_and(V1, V2); break;
1397   case Instruction::Or:      C = ConstRules::get(V1, V2).op_or (V1, V2); break;
1398   case Instruction::Xor:     C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
1399   case Instruction::Shl:     C = ConstRules::get(V1, V2).shl(V1, V2); break;
1400   case Instruction::LShr:    C = ConstRules::get(V1, V2).lshr(V1, V2); break;
1401   case Instruction::AShr:    C = ConstRules::get(V1, V2).ashr(V1, V2); break;
1402   case Instruction::SetEQ:   
1403     // SetEQ(null,GV) -> false
1404     if (V1->isNullValue()) {
1405       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V2))
1406         if (!GV->hasExternalWeakLinkage())
1407           return ConstantBool::getFalse();
1408     // SetEQ(GV,null) -> false
1409     } else if (V2->isNullValue()) {
1410       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1))
1411         if (!GV->hasExternalWeakLinkage())
1412           return ConstantBool::getFalse();
1413     }
1414     C = ConstRules::get(V1, V2).equalto(V1, V2); 
1415     break;
1416   case Instruction::SetLT:   C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
1417   case Instruction::SetGT:   C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
1418   case Instruction::SetNE:   
1419     // SetNE(null,GV) -> true
1420     if (V1->isNullValue()) {
1421       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V2))
1422         if (!GV->hasExternalWeakLinkage())
1423           return ConstantBool::getTrue();
1424     // SetNE(GV,null) -> true
1425     } else if (V2->isNullValue()) {
1426       if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1))
1427         if (!GV->hasExternalWeakLinkage())
1428           return ConstantBool::getTrue();
1429     }
1430     // V1 != V2  ===  !(V1 == V2)
1431     C = ConstRules::get(V1, V2).equalto(V1, V2);
1432     if (C) return ConstantExpr::getNot(C);
1433     break;
1434   case Instruction::SetLE:   // V1 <= V2  ===  !(V2 < V1)
1435     C = ConstRules::get(V1, V2).lessthan(V2, V1);
1436     if (C) return ConstantExpr::getNot(C);
1437     break;
1438   case Instruction::SetGE:   // V1 >= V2  ===  !(V1 < V2)
1439     C = ConstRules::get(V1, V2).lessthan(V1, V2);
1440     if (C) return ConstantExpr::getNot(C);
1441     break;
1442   }
1443
1444   // If we successfully folded the expression, return it now.
1445   if (C) return C;
1446
1447   if (SetCondInst::isComparison(Opcode)) {
1448     if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1449       return UndefValue::get(Type::BoolTy);
1450     switch (evaluateRelation(const_cast<Constant*>(V1),
1451                              const_cast<Constant*>(V2))) {
1452     default: assert(0 && "Unknown relational!");
1453     case Instruction::BinaryOpsEnd:
1454       break;  // Couldn't determine anything about these constants.
1455     case Instruction::SetEQ:   // We know the constants are equal!
1456       // If we know the constants are equal, we can decide the result of this
1457       // computation precisely.
1458       return ConstantBool::get(Opcode == Instruction::SetEQ ||
1459                                Opcode == Instruction::SetLE ||
1460                                Opcode == Instruction::SetGE);
1461     case Instruction::SetLT:
1462       // If we know that V1 < V2, we can decide the result of this computation
1463       // precisely.
1464       return ConstantBool::get(Opcode == Instruction::SetLT ||
1465                                Opcode == Instruction::SetNE ||
1466                                Opcode == Instruction::SetLE);
1467     case Instruction::SetGT:
1468       // If we know that V1 > V2, we can decide the result of this computation
1469       // precisely.
1470       return ConstantBool::get(Opcode == Instruction::SetGT ||
1471                                Opcode == Instruction::SetNE ||
1472                                Opcode == Instruction::SetGE);
1473     case Instruction::SetLE:
1474       // If we know that V1 <= V2, we can only partially decide this relation.
1475       if (Opcode == Instruction::SetGT) return ConstantBool::getFalse();
1476       if (Opcode == Instruction::SetLT) return ConstantBool::getTrue();
1477       break;
1478
1479     case Instruction::SetGE:
1480       // If we know that V1 >= V2, we can only partially decide this relation.
1481       if (Opcode == Instruction::SetLT) return ConstantBool::getFalse();
1482       if (Opcode == Instruction::SetGT) return ConstantBool::getTrue();
1483       break;
1484
1485     case Instruction::SetNE:
1486       // If we know that V1 != V2, we can only partially decide this relation.
1487       if (Opcode == Instruction::SetEQ) return ConstantBool::getFalse();
1488       if (Opcode == Instruction::SetNE) return ConstantBool::getTrue();
1489       break;
1490     }
1491   }
1492
1493   if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) {
1494     switch (Opcode) {
1495     case Instruction::Add:
1496     case Instruction::Sub:
1497     case Instruction::Xor:
1498       return UndefValue::get(V1->getType());
1499
1500     case Instruction::Mul:
1501     case Instruction::And:
1502       return Constant::getNullValue(V1->getType());
1503     case Instruction::UDiv:
1504     case Instruction::SDiv:
1505     case Instruction::FDiv:
1506     case Instruction::URem:
1507     case Instruction::SRem:
1508     case Instruction::FRem:
1509       if (!isa<UndefValue>(V2))                    // undef / X -> 0
1510         return Constant::getNullValue(V1->getType());
1511       return const_cast<Constant*>(V2);            // X / undef -> undef
1512     case Instruction::Or:                          // X | undef -> -1
1513       return ConstantInt::getAllOnesValue(V1->getType());
1514     case Instruction::LShr:
1515       if (isa<UndefValue>(V2) && isa<UndefValue>(V1))
1516         return const_cast<Constant*>(V1);           // undef lshr undef -> undef
1517       return Constant::getNullValue(V1->getType()); // X lshr undef -> 0
1518                                                     // undef lshr X -> 0
1519     case Instruction::AShr:
1520       if (!isa<UndefValue>(V2))
1521         return const_cast<Constant*>(V1);           // undef ashr X --> undef
1522       else if (isa<UndefValue>(V1)) 
1523         return const_cast<Constant*>(V1);           // undef ashr undef -> undef
1524       else
1525         return const_cast<Constant*>(V1);           // X ashr undef --> X
1526     case Instruction::Shl:
1527       // undef << X -> 0   or   X << undef -> 0
1528       return Constant::getNullValue(V1->getType());
1529     }
1530   }
1531
1532   if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
1533     if (isa<ConstantExpr>(V2)) {
1534       // There are many possible foldings we could do here.  We should probably
1535       // at least fold add of a pointer with an integer into the appropriate
1536       // getelementptr.  This will improve alias analysis a bit.
1537     } else {
1538       // Just implement a couple of simple identities.
1539       switch (Opcode) {
1540       case Instruction::Add:
1541         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X + 0 == X
1542         break;
1543       case Instruction::Sub:
1544         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X - 0 == X
1545         break;
1546       case Instruction::Mul:
1547         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X * 0 == 0
1548         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1549           if (CI->getZExtValue() == 1)
1550             return const_cast<Constant*>(V1);                     // X * 1 == X
1551         break;
1552       case Instruction::UDiv:
1553       case Instruction::SDiv:
1554         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1555           if (CI->getZExtValue() == 1)
1556             return const_cast<Constant*>(V1);                     // X / 1 == X
1557         break;
1558       case Instruction::URem:
1559       case Instruction::SRem:
1560         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1561           if (CI->getZExtValue() == 1)
1562             return Constant::getNullValue(CI->getType());         // X % 1 == 0
1563         break;
1564       case Instruction::And:
1565         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1566           return const_cast<Constant*>(V1);                       // X & -1 == X
1567         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X & 0 == 0
1568         if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
1569           GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
1570
1571           // Functions are at least 4-byte aligned.  If and'ing the address of a
1572           // function with a constant < 4, fold it to zero.
1573           if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1574             if (CI->getZExtValue() < 4 && isa<Function>(CPR))
1575               return Constant::getNullValue(CI->getType());
1576         }
1577         break;
1578       case Instruction::Or:
1579         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X | 0 == X
1580         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1581           return const_cast<Constant*>(V2);  // X | -1 == -1
1582         break;
1583       case Instruction::Xor:
1584         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X ^ 0 == X
1585         break;
1586       }
1587     }
1588
1589   } else if (isa<ConstantExpr>(V2)) {
1590     // If V2 is a constant expr and V1 isn't, flop them around and fold the
1591     // other way if possible.
1592     switch (Opcode) {
1593     case Instruction::Add:
1594     case Instruction::Mul:
1595     case Instruction::And:
1596     case Instruction::Or:
1597     case Instruction::Xor:
1598     case Instruction::SetEQ:
1599     case Instruction::SetNE:
1600       // No change of opcode required.
1601       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1602
1603     case Instruction::SetLT:
1604     case Instruction::SetGT:
1605     case Instruction::SetLE:
1606     case Instruction::SetGE:
1607       // Change the opcode as necessary to swap the operands.
1608       Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
1609       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1610
1611     case Instruction::Shl:
1612     case Instruction::LShr:
1613     case Instruction::AShr:
1614     case Instruction::Sub:
1615     case Instruction::SDiv:
1616     case Instruction::UDiv:
1617     case Instruction::FDiv:
1618     case Instruction::URem:
1619     case Instruction::SRem:
1620     case Instruction::FRem:
1621     default:  // These instructions cannot be flopped around.
1622       break;
1623     }
1624   }
1625   return 0;
1626 }
1627
1628 Constant *llvm::ConstantFoldCompare(
1629     unsigned opcode, Constant *C1, Constant  *C2, unsigned short predicate)
1630 {
1631   // Place holder for future folding of ICmp and FCmp instructions
1632   return 0;
1633 }
1634
1635 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1636                                           const std::vector<Value*> &IdxList) {
1637   if (IdxList.size() == 0 ||
1638       (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
1639     return const_cast<Constant*>(C);
1640
1641   if (isa<UndefValue>(C)) {
1642     const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1643                                                        true);
1644     assert(Ty != 0 && "Invalid indices for GEP!");
1645     return UndefValue::get(PointerType::get(Ty));
1646   }
1647
1648   Constant *Idx0 = cast<Constant>(IdxList[0]);
1649   if (C->isNullValue()) {
1650     bool isNull = true;
1651     for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1652       if (!cast<Constant>(IdxList[i])->isNullValue()) {
1653         isNull = false;
1654         break;
1655       }
1656     if (isNull) {
1657       const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1658                                                          true);
1659       assert(Ty != 0 && "Invalid indices for GEP!");
1660       return ConstantPointerNull::get(PointerType::get(Ty));
1661     }
1662
1663     if (IdxList.size() == 1) {
1664       const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
1665       if (uint32_t ElSize = ElTy->getPrimitiveSize()) {
1666         // gep null, C is equal to C*sizeof(nullty).  If nullty is a known llvm
1667         // type, we can statically fold this.
1668         Constant *R = ConstantInt::get(Type::UIntTy, ElSize);
1669         // We know R is unsigned, Idx0 is signed because it must be an index
1670         // through a sequential type (gep pointer operand) which is always
1671         // signed.
1672         R = ConstantExpr::getSExtOrBitCast(R, Idx0->getType());
1673         R = ConstantExpr::getMul(R, Idx0); // signed multiply
1674         // R is a signed integer, C is the GEP pointer so -> IntToPtr
1675         return ConstantExpr::getCast(Instruction::IntToPtr, R, C->getType());
1676       }
1677     }
1678   }
1679
1680   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1681     // Combine Indices - If the source pointer to this getelementptr instruction
1682     // is a getelementptr instruction, combine the indices of the two
1683     // getelementptr instructions into a single instruction.
1684     //
1685     if (CE->getOpcode() == Instruction::GetElementPtr) {
1686       const Type *LastTy = 0;
1687       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1688            I != E; ++I)
1689         LastTy = *I;
1690
1691       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1692         std::vector<Value*> NewIndices;
1693         NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1694         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1695           NewIndices.push_back(CE->getOperand(i));
1696
1697         // Add the last index of the source with the first index of the new GEP.
1698         // Make sure to handle the case when they are actually different types.
1699         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1700         // Otherwise it must be an array.
1701         if (!Idx0->isNullValue()) {
1702           const Type *IdxTy = Combined->getType();
1703           if (IdxTy != Idx0->getType()) {
1704             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::LongTy);
1705             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
1706                                                           Type::LongTy);
1707             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1708           } else {
1709             Combined =
1710               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1711           }
1712         }
1713
1714         NewIndices.push_back(Combined);
1715         NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1716         return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1717       }
1718     }
1719
1720     // Implement folding of:
1721     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1722     //                        long 0, long 0)
1723     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1724     //
1725     if (CE->isCast() && IdxList.size() > 1 && Idx0->isNullValue())
1726       if (const PointerType *SPT =
1727           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1728         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1729           if (const ArrayType *CAT =
1730         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1731             if (CAT->getElementType() == SAT->getElementType())
1732               return ConstantExpr::getGetElementPtr(
1733                       (Constant*)CE->getOperand(0), IdxList);
1734   }
1735   return 0;
1736 }
1737