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