fold gep undef, ... -> undef
[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 <cmath>
28 using namespace llvm;
29
30 namespace {
31   struct ConstRules {
32     ConstRules() {}
33     
34     // Binary Operators...
35     virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
36     virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
37     virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
38     virtual Constant *div(const Constant *V1, const Constant *V2) const = 0;
39     virtual Constant *rem(const Constant *V1, const Constant *V2) const = 0;
40     virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
41     virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
42     virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
43     virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
44     virtual Constant *shr(const Constant *V1, const Constant *V2) const = 0;
45     virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
46     virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
47
48     // Casting operators.
49     virtual Constant *castToBool  (const Constant *V) const = 0;
50     virtual Constant *castToSByte (const Constant *V) const = 0;
51     virtual Constant *castToUByte (const Constant *V) const = 0;
52     virtual Constant *castToShort (const Constant *V) const = 0;
53     virtual Constant *castToUShort(const Constant *V) const = 0;
54     virtual Constant *castToInt   (const Constant *V) const = 0;
55     virtual Constant *castToUInt  (const Constant *V) const = 0;
56     virtual Constant *castToLong  (const Constant *V) const = 0;
57     virtual Constant *castToULong (const Constant *V) const = 0;
58     virtual Constant *castToFloat (const Constant *V) const = 0;
59     virtual Constant *castToDouble(const Constant *V) const = 0;
60     virtual Constant *castToPointer(const Constant *V,
61                                     const PointerType *Ty) const = 0;
62     
63     // ConstRules::get - Return an instance of ConstRules for the specified
64     // constant operands.
65     //
66     static ConstRules &get(const Constant *V1, const Constant *V2);
67   private:
68     ConstRules(const ConstRules &);             // Do not implement
69     ConstRules &operator=(const ConstRules &);  // Do not implement
70   };
71 }
72
73
74 //===----------------------------------------------------------------------===//
75 //                             TemplateRules Class
76 //===----------------------------------------------------------------------===//
77 //
78 // TemplateRules - Implement a subclass of ConstRules that provides all 
79 // operations as noops.  All other rules classes inherit from this class so 
80 // that if functionality is needed in the future, it can simply be added here 
81 // and to ConstRules without changing anything else...
82 // 
83 // This class also provides subclasses with typesafe implementations of methods
84 // so that don't have to do type casting.
85 //
86 template<class ArgType, class SubClassName>
87 class TemplateRules : public ConstRules {
88
89   //===--------------------------------------------------------------------===//
90   // Redirecting functions that cast to the appropriate types
91   //===--------------------------------------------------------------------===//
92
93   virtual Constant *add(const Constant *V1, const Constant *V2) const { 
94     return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);  
95   }
96   virtual Constant *sub(const Constant *V1, const Constant *V2) const { 
97     return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);  
98   }
99   virtual Constant *mul(const Constant *V1, const Constant *V2) const { 
100     return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);  
101   }
102   virtual Constant *div(const Constant *V1, const Constant *V2) const { 
103     return SubClassName::Div((const ArgType *)V1, (const ArgType *)V2);  
104   }
105   virtual Constant *rem(const Constant *V1, const Constant *V2) const { 
106     return SubClassName::Rem((const ArgType *)V1, (const ArgType *)V2);  
107   }
108   virtual Constant *op_and(const Constant *V1, const Constant *V2) const { 
109     return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);  
110   }
111   virtual Constant *op_or(const Constant *V1, const Constant *V2) const { 
112     return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);  
113   }
114   virtual Constant *op_xor(const Constant *V1, const Constant *V2) const { 
115     return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);  
116   }
117   virtual Constant *shl(const Constant *V1, const Constant *V2) const { 
118     return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);  
119   }
120   virtual Constant *shr(const Constant *V1, const Constant *V2) const { 
121     return SubClassName::Shr((const ArgType *)V1, (const ArgType *)V2);  
122   }
123
124   virtual Constant *lessthan(const Constant *V1, const Constant *V2) const { 
125     return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
126   }
127   virtual Constant *equalto(const Constant *V1, const Constant *V2) const { 
128     return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
129   }
130
131   // Casting operators.  ick
132   virtual Constant *castToBool(const Constant *V) const {
133     return SubClassName::CastToBool((const ArgType*)V);
134   }
135   virtual Constant *castToSByte(const Constant *V) const {
136     return SubClassName::CastToSByte((const ArgType*)V);
137   }
138   virtual Constant *castToUByte(const Constant *V) const {
139     return SubClassName::CastToUByte((const ArgType*)V);
140   }
141   virtual Constant *castToShort(const Constant *V) const {
142     return SubClassName::CastToShort((const ArgType*)V);
143   }
144   virtual Constant *castToUShort(const Constant *V) const {
145     return SubClassName::CastToUShort((const ArgType*)V);
146   }
147   virtual Constant *castToInt(const Constant *V) const {
148     return SubClassName::CastToInt((const ArgType*)V);
149   }
150   virtual Constant *castToUInt(const Constant *V) const {
151     return SubClassName::CastToUInt((const ArgType*)V);
152   }
153   virtual Constant *castToLong(const Constant *V) const {
154     return SubClassName::CastToLong((const ArgType*)V);
155   }
156   virtual Constant *castToULong(const Constant *V) const {
157     return SubClassName::CastToULong((const ArgType*)V);
158   }
159   virtual Constant *castToFloat(const Constant *V) const {
160     return SubClassName::CastToFloat((const ArgType*)V);
161   }
162   virtual Constant *castToDouble(const Constant *V) const {
163     return SubClassName::CastToDouble((const ArgType*)V);
164   }
165   virtual Constant *castToPointer(const Constant *V, 
166                                   const PointerType *Ty) const {
167     return SubClassName::CastToPointer((const ArgType*)V, Ty);
168   }
169
170   //===--------------------------------------------------------------------===//
171   // Default "noop" implementations
172   //===--------------------------------------------------------------------===//
173
174   static Constant *Add(const ArgType *V1, const ArgType *V2) { return 0; }
175   static Constant *Sub(const ArgType *V1, const ArgType *V2) { return 0; }
176   static Constant *Mul(const ArgType *V1, const ArgType *V2) { return 0; }
177   static Constant *Div(const ArgType *V1, const ArgType *V2) { return 0; }
178   static Constant *Rem(const ArgType *V1, const ArgType *V2) { return 0; }
179   static Constant *And(const ArgType *V1, const ArgType *V2) { return 0; }
180   static Constant *Or (const ArgType *V1, const ArgType *V2) { return 0; }
181   static Constant *Xor(const ArgType *V1, const ArgType *V2) { return 0; }
182   static Constant *Shl(const ArgType *V1, const ArgType *V2) { return 0; }
183   static Constant *Shr(const ArgType *V1, const ArgType *V2) { return 0; }
184   static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
185     return 0;
186   }
187   static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
188     return 0;
189   }
190
191   // Casting operators.  ick
192   static Constant *CastToBool  (const Constant *V) { return 0; }
193   static Constant *CastToSByte (const Constant *V) { return 0; }
194   static Constant *CastToUByte (const Constant *V) { return 0; }
195   static Constant *CastToShort (const Constant *V) { return 0; }
196   static Constant *CastToUShort(const Constant *V) { return 0; }
197   static Constant *CastToInt   (const Constant *V) { return 0; }
198   static Constant *CastToUInt  (const Constant *V) { return 0; }
199   static Constant *CastToLong  (const Constant *V) { return 0; }
200   static Constant *CastToULong (const Constant *V) { return 0; }
201   static Constant *CastToFloat (const Constant *V) { return 0; }
202   static Constant *CastToDouble(const Constant *V) { return 0; }
203   static Constant *CastToPointer(const Constant *,
204                                  const PointerType *) {return 0;}
205 };
206
207
208
209 //===----------------------------------------------------------------------===//
210 //                             EmptyRules Class
211 //===----------------------------------------------------------------------===//
212 //
213 // EmptyRules provides a concrete base class of ConstRules that does nothing
214 //
215 struct EmptyRules : public TemplateRules<Constant, EmptyRules> {
216   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
217     if (V1 == V2) return ConstantBool::True;
218     return 0;
219   }
220 };
221
222
223
224 //===----------------------------------------------------------------------===//
225 //                              BoolRules Class
226 //===----------------------------------------------------------------------===//
227 //
228 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
229 //
230 struct BoolRules : public TemplateRules<ConstantBool, BoolRules> {
231
232   static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2){
233     return ConstantBool::get(V1->getValue() < V2->getValue());
234   }
235
236   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
237     return ConstantBool::get(V1 == V2);
238   }
239
240   static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
241     return ConstantBool::get(V1->getValue() & V2->getValue());
242   }
243
244   static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
245     return ConstantBool::get(V1->getValue() | V2->getValue());
246   }
247
248   static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
249     return ConstantBool::get(V1->getValue() ^ V2->getValue());
250   }
251
252   // Casting operators.  ick
253 #define DEF_CAST(TYPE, CLASS, CTYPE) \
254   static Constant *CastTo##TYPE  (const ConstantBool *V) {    \
255     return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
256   }
257
258   DEF_CAST(Bool  , ConstantBool, bool)
259   DEF_CAST(SByte , ConstantSInt, signed char)
260   DEF_CAST(UByte , ConstantUInt, unsigned char)
261   DEF_CAST(Short , ConstantSInt, signed short)
262   DEF_CAST(UShort, ConstantUInt, unsigned short)
263   DEF_CAST(Int   , ConstantSInt, signed int)
264   DEF_CAST(UInt  , ConstantUInt, unsigned int)
265   DEF_CAST(Long  , ConstantSInt, int64_t)
266   DEF_CAST(ULong , ConstantUInt, uint64_t)
267   DEF_CAST(Float , ConstantFP  , float)
268   DEF_CAST(Double, ConstantFP  , double)
269 #undef DEF_CAST
270 };
271
272
273 //===----------------------------------------------------------------------===//
274 //                            NullPointerRules Class
275 //===----------------------------------------------------------------------===//
276 //
277 // NullPointerRules provides a concrete base class of ConstRules for null
278 // pointers.
279 //
280 struct NullPointerRules : public TemplateRules<ConstantPointerNull,
281                                                NullPointerRules> {
282   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
283     return ConstantBool::True;  // Null pointers are always equal
284   }
285   static Constant *CastToBool(const Constant *V) {
286     return ConstantBool::False;
287   }
288   static Constant *CastToSByte (const Constant *V) {
289     return ConstantSInt::get(Type::SByteTy, 0);
290   }
291   static Constant *CastToUByte (const Constant *V) {
292     return ConstantUInt::get(Type::UByteTy, 0);
293   }
294   static Constant *CastToShort (const Constant *V) {
295     return ConstantSInt::get(Type::ShortTy, 0);
296   }
297   static Constant *CastToUShort(const Constant *V) {
298     return ConstantUInt::get(Type::UShortTy, 0);
299   }
300   static Constant *CastToInt   (const Constant *V) {
301     return ConstantSInt::get(Type::IntTy, 0);
302   }
303   static Constant *CastToUInt  (const Constant *V) {
304     return ConstantUInt::get(Type::UIntTy, 0);
305   }
306   static Constant *CastToLong  (const Constant *V) {
307     return ConstantSInt::get(Type::LongTy, 0);
308   }
309   static Constant *CastToULong (const Constant *V) {
310     return ConstantUInt::get(Type::ULongTy, 0);
311   }
312   static Constant *CastToFloat (const Constant *V) {
313     return ConstantFP::get(Type::FloatTy, 0);
314   }
315   static Constant *CastToDouble(const Constant *V) {
316     return ConstantFP::get(Type::DoubleTy, 0);
317   }
318
319   static Constant *CastToPointer(const ConstantPointerNull *V,
320                                  const PointerType *PTy) {
321     return ConstantPointerNull::get(PTy);
322   }
323 };
324
325
326 //===----------------------------------------------------------------------===//
327 //                             DirectRules Class
328 //===----------------------------------------------------------------------===//
329 //
330 // DirectRules provides a concrete base classes of ConstRules for a variety of
331 // different types.  This allows the C++ compiler to automatically generate our
332 // constant handling operations in a typesafe and accurate manner.
333 //
334 template<class ConstantClass, class BuiltinType, Type **Ty, class SuperClass>
335 struct DirectRules : public TemplateRules<ConstantClass, SuperClass> {
336   static Constant *Add(const ConstantClass *V1, const ConstantClass *V2) {
337     BuiltinType R = (BuiltinType)V1->getValue() + (BuiltinType)V2->getValue();
338     return ConstantClass::get(*Ty, R);
339   }
340
341   static Constant *Sub(const ConstantClass *V1, const ConstantClass *V2) {
342     BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
343     return ConstantClass::get(*Ty, R);
344   }
345
346   static Constant *Mul(const ConstantClass *V1, const ConstantClass *V2) {
347     BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
348     return ConstantClass::get(*Ty, R);
349   }
350
351   static Constant *Div(const ConstantClass *V1, const ConstantClass *V2) {
352     if (V2->isNullValue()) return 0;
353     BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
354     return ConstantClass::get(*Ty, R);
355   }
356
357   static Constant *LessThan(const ConstantClass *V1, const ConstantClass *V2) {
358     bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
359     return ConstantBool::get(R);
360   } 
361
362   static Constant *EqualTo(const ConstantClass *V1, const ConstantClass *V2) {
363     bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
364     return ConstantBool::get(R);
365   }
366
367   static Constant *CastToPointer(const ConstantClass *V,
368                                  const PointerType *PTy) {
369     if (V->isNullValue())    // Is it a FP or Integral null value?
370       return ConstantPointerNull::get(PTy);
371     return 0;  // Can't const prop other types of pointers
372   }
373
374   // Casting operators.  ick
375 #define DEF_CAST(TYPE, CLASS, CTYPE) \
376   static Constant *CastTo##TYPE  (const ConstantClass *V) {    \
377     return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
378   }
379
380   DEF_CAST(Bool  , ConstantBool, bool)
381   DEF_CAST(SByte , ConstantSInt, signed char)
382   DEF_CAST(UByte , ConstantUInt, unsigned char)
383   DEF_CAST(Short , ConstantSInt, signed short)
384   DEF_CAST(UShort, ConstantUInt, unsigned short)
385   DEF_CAST(Int   , ConstantSInt, signed int)
386   DEF_CAST(UInt  , ConstantUInt, unsigned int)
387   DEF_CAST(Long  , ConstantSInt, int64_t)
388   DEF_CAST(ULong , ConstantUInt, uint64_t)
389   DEF_CAST(Float , ConstantFP  , float)
390   DEF_CAST(Double, ConstantFP  , double)
391 #undef DEF_CAST
392 };
393
394
395 //===----------------------------------------------------------------------===//
396 //                           DirectIntRules Class
397 //===----------------------------------------------------------------------===//
398 //
399 // DirectIntRules provides implementations of functions that are valid on
400 // integer types, but not all types in general.
401 //
402 template <class ConstantClass, class BuiltinType, Type **Ty>
403 struct DirectIntRules
404   : public DirectRules<ConstantClass, BuiltinType, Ty,
405                        DirectIntRules<ConstantClass, BuiltinType, Ty> > {
406
407   static Constant *Div(const ConstantClass *V1, const ConstantClass *V2) {
408     if (V2->isNullValue()) return 0;
409     if (V2->isAllOnesValue() &&              // MIN_INT / -1
410         (BuiltinType)V1->getValue() == -(BuiltinType)V1->getValue())
411       return 0;
412     BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
413     return ConstantClass::get(*Ty, R);
414   }
415
416   static Constant *Rem(const ConstantClass *V1,
417                        const ConstantClass *V2) {
418     if (V2->isNullValue()) return 0;         // X / 0
419     if (V2->isAllOnesValue() &&              // MIN_INT / -1
420         (BuiltinType)V1->getValue() == -(BuiltinType)V1->getValue())
421       return 0;
422     BuiltinType R = (BuiltinType)V1->getValue() % (BuiltinType)V2->getValue();
423     return ConstantClass::get(*Ty, R);
424   }
425
426   static Constant *And(const ConstantClass *V1, const ConstantClass *V2) {
427     BuiltinType R = (BuiltinType)V1->getValue() & (BuiltinType)V2->getValue();
428     return ConstantClass::get(*Ty, R);
429   }
430   static Constant *Or(const ConstantClass *V1, const ConstantClass *V2) {
431     BuiltinType R = (BuiltinType)V1->getValue() | (BuiltinType)V2->getValue();
432     return ConstantClass::get(*Ty, R);
433   }
434   static Constant *Xor(const ConstantClass *V1, const ConstantClass *V2) {
435     BuiltinType R = (BuiltinType)V1->getValue() ^ (BuiltinType)V2->getValue();
436     return ConstantClass::get(*Ty, R);
437   }
438
439   static Constant *Shl(const ConstantClass *V1, const ConstantClass *V2) {
440     BuiltinType R = (BuiltinType)V1->getValue() << (BuiltinType)V2->getValue();
441     return ConstantClass::get(*Ty, R);
442   }
443
444   static Constant *Shr(const ConstantClass *V1, const ConstantClass *V2) {
445     BuiltinType R = (BuiltinType)V1->getValue() >> (BuiltinType)V2->getValue();
446     return ConstantClass::get(*Ty, R);
447   }
448 };
449
450
451 //===----------------------------------------------------------------------===//
452 //                           DirectFPRules Class
453 //===----------------------------------------------------------------------===//
454 //
455 /// DirectFPRules provides implementations of functions that are valid on
456 /// floating point types, but not all types in general.
457 ///
458 template <class ConstantClass, class BuiltinType, Type **Ty>
459 struct DirectFPRules
460   : public DirectRules<ConstantClass, BuiltinType, Ty,
461                        DirectFPRules<ConstantClass, BuiltinType, Ty> > {
462   static Constant *Rem(const ConstantClass *V1, const ConstantClass *V2) {
463     if (V2->isNullValue()) return 0;
464     BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
465                                    (BuiltinType)V2->getValue());
466     return ConstantClass::get(*Ty, Result);
467   }
468 };
469
470
471 /// ConstRules::get - This method returns the constant rules implementation that
472 /// implements the semantics of the two specified constants.
473 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
474   static EmptyRules       EmptyR;
475   static BoolRules        BoolR;
476   static NullPointerRules NullPointerR;
477   static DirectIntRules<ConstantSInt,   signed char , &Type::SByteTy>  SByteR;
478   static DirectIntRules<ConstantUInt, unsigned char , &Type::UByteTy>  UByteR;
479   static DirectIntRules<ConstantSInt,   signed short, &Type::ShortTy>  ShortR;
480   static DirectIntRules<ConstantUInt, unsigned short, &Type::UShortTy> UShortR;
481   static DirectIntRules<ConstantSInt,   signed int  , &Type::IntTy>    IntR;
482   static DirectIntRules<ConstantUInt, unsigned int  , &Type::UIntTy>   UIntR;
483   static DirectIntRules<ConstantSInt,  int64_t      , &Type::LongTy>   LongR;
484   static DirectIntRules<ConstantUInt, uint64_t      , &Type::ULongTy>  ULongR;
485   static DirectFPRules <ConstantFP  , float         , &Type::FloatTy>  FloatR;
486   static DirectFPRules <ConstantFP  , double        , &Type::DoubleTy> DoubleR;
487
488   if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
489       isa<GlobalValue>(V1) || isa<GlobalValue>(V2) ||
490       isa<UndefValue>(V1) || isa<UndefValue>(V2))
491     return EmptyR;
492
493   switch (V1->getType()->getTypeID()) {
494   default: assert(0 && "Unknown value type for constant folding!");
495   case Type::BoolTyID:    return BoolR;
496   case Type::PointerTyID: return NullPointerR;
497   case Type::SByteTyID:   return SByteR;
498   case Type::UByteTyID:   return UByteR;
499   case Type::ShortTyID:   return ShortR;
500   case Type::UShortTyID:  return UShortR;
501   case Type::IntTyID:     return IntR;
502   case Type::UIntTyID:    return UIntR;
503   case Type::LongTyID:    return LongR;
504   case Type::ULongTyID:   return ULongR;
505   case Type::FloatTyID:   return FloatR;
506   case Type::DoubleTyID:  return DoubleR;
507   }
508 }
509
510
511 //===----------------------------------------------------------------------===//
512 //                ConstantFold*Instruction Implementations
513 //===----------------------------------------------------------------------===//
514 //
515 // These methods contain the special case hackery required to symbolically
516 // evaluate some constant expression cases, and use the ConstantRules class to
517 // evaluate normal constants.
518 //
519 static unsigned getSize(const Type *Ty) {
520   unsigned S = Ty->getPrimitiveSize();
521   return S ? S : 8;  // Treat pointers at 8 bytes
522 }
523
524 Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
525                                             const Type *DestTy) {
526   if (V->getType() == DestTy) return (Constant*)V;
527
528   // Cast of a global address to boolean is always true.
529   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
530     if (DestTy == Type::BoolTy)
531       // FIXME: When we support 'external weak' references, we have to prevent
532       // this transformation from happening.  In the meantime we avoid folding
533       // any cast of an external symbol.
534       if (!GV->isExternal())
535         return ConstantBool::True;
536   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
537     if (CE->getOpcode() == Instruction::Cast) {
538       Constant *Op = const_cast<Constant*>(CE->getOperand(0));
539       // Try to not produce a cast of a cast, which is almost always redundant.
540       if (!Op->getType()->isFloatingPoint() &&
541           !CE->getType()->isFloatingPoint() &&
542           !DestTy->isFloatingPoint()) {
543         unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
544         unsigned S3 = getSize(DestTy);
545         if (Op->getType() == DestTy && S3 >= S2)
546           return Op;
547         if (S1 >= S2 && S2 >= S3)
548           return ConstantExpr::getCast(Op, DestTy);
549         if (S1 <= S2 && S2 >= S3 && S1 <= S3)
550           return ConstantExpr::getCast(Op, DestTy);
551       }
552     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
553       // If all of the indexes in the GEP are null values, there is no pointer
554       // adjustment going on.  We might as well cast the source pointer.
555       bool isAllNull = true;
556       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
557         if (!CE->getOperand(i)->isNullValue()) {
558           isAllNull = false;
559           break;
560         }
561       if (isAllNull)
562         return ConstantExpr::getCast(CE->getOperand(0), DestTy);
563     }
564   } else if (isa<UndefValue>(V)) {
565     return UndefValue::get(DestTy);
566   }
567
568   // Check to see if we are casting an array of X to a pointer to X.  If so, use
569   // a GEP to get to the first element of the array instead of a cast!
570   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
571     if (const ArrayType *ATy = dyn_cast<ArrayType>(PTy->getElementType()))
572       if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
573         if (DPTy->getElementType() == ATy->getElementType()) {
574           std::vector<Constant*> IdxList(2,Constant::getNullValue(Type::IntTy));
575           return ConstantExpr::getGetElementPtr(const_cast<Constant*>(V),
576                                                 IdxList);
577         }
578
579   ConstRules &Rules = ConstRules::get(V, V);
580
581   switch (DestTy->getTypeID()) {
582   case Type::BoolTyID:    return Rules.castToBool(V);
583   case Type::UByteTyID:   return Rules.castToUByte(V);
584   case Type::SByteTyID:   return Rules.castToSByte(V);
585   case Type::UShortTyID:  return Rules.castToUShort(V);
586   case Type::ShortTyID:   return Rules.castToShort(V);
587   case Type::UIntTyID:    return Rules.castToUInt(V);
588   case Type::IntTyID:     return Rules.castToInt(V);
589   case Type::ULongTyID:   return Rules.castToULong(V);
590   case Type::LongTyID:    return Rules.castToLong(V);
591   case Type::FloatTyID:   return Rules.castToFloat(V);
592   case Type::DoubleTyID:  return Rules.castToDouble(V);
593   case Type::PointerTyID:
594     return Rules.castToPointer(V, cast<PointerType>(DestTy));
595   default: return 0;
596   }
597 }
598
599 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
600                                               const Constant *V1,
601                                               const Constant *V2) {
602   if (Cond == ConstantBool::True)
603     return const_cast<Constant*>(V1);
604   else if (Cond == ConstantBool::False)
605     return const_cast<Constant*>(V2);
606
607   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
608   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
609   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
610   return 0;
611 }
612
613
614 /// IdxCompare - Compare the two constants as though they were getelementptr
615 /// indices.  This allows coersion of the types to be the same thing.
616 ///
617 /// If the two constants are the "same" (after coersion), return 0.  If the
618 /// first is less than the second, return -1, if the second is less than the
619 /// first, return 1.  If the constants are not integral, return -2.
620 ///
621 static int IdxCompare(Constant *C1, Constant *C2) {
622   if (C1 == C2) return 0;
623
624   // Ok, we found a different index.  Are either of the operands
625   // ConstantExprs?  If so, we can't do anything with them.
626   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
627     return -2; // don't know!
628   
629   // Ok, we have two differing integer indices.  Sign extend them to be the same
630   // type.  Long is always big enough, so we use it.
631   C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
632   C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
633   if (C1 == C2) return 0;  // Are they just differing types?
634
635   // If they are really different, now that they are the same type, then we
636   // found a difference!
637   if (cast<ConstantSInt>(C1)->getValue() < cast<ConstantSInt>(C2)->getValue())
638     return -1;
639   else
640     return 1;
641 }
642
643 /// evaluateRelation - This function determines if there is anything we can
644 /// decide about the two constants provided.  This doesn't need to handle simple
645 /// things like integer comparisons, but should instead handle ConstantExprs
646 /// and GlobalValuess.  If we can determine that the two constants have a
647 /// particular relation to each other, we should return the corresponding SetCC
648 /// code, otherwise return Instruction::BinaryOpsEnd.
649 ///
650 /// To simplify this code we canonicalize the relation so that the first
651 /// operand is always the most "complex" of the two.  We consider simple
652 /// constants (like ConstantInt) to be the simplest, followed by
653 /// GlobalValues, followed by ConstantExpr's (the most complex).
654 ///
655 static Instruction::BinaryOps evaluateRelation(const Constant *V1,
656                                                const Constant *V2) {
657   assert(V1->getType() == V2->getType() &&
658          "Cannot compare different types of values!");
659   if (V1 == V2) return Instruction::SetEQ;
660
661   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
662     // If the first operand is simple, swap operands.
663     assert((isa<GlobalValue>(V2) || isa<ConstantExpr>(V2)) &&
664            "Simple cases should have been handled by caller!");
665     Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
666     if (SwappedRelation != Instruction::BinaryOpsEnd)
667       return SetCondInst::getSwappedCondition(SwappedRelation);
668
669   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)){
670     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
671     Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
672     if (SwappedRelation != Instruction::BinaryOpsEnd)
673       return SetCondInst::getSwappedCondition(SwappedRelation);
674     else
675       return Instruction::BinaryOpsEnd;
676     }
677
678     // Now we know that the RHS is a GlobalValue or simple constant,
679     // which (since the types must match) means that it's a ConstantPointerNull.
680     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
681       assert(CPR1 != CPR2 &&
682              "GVs for the same value exist at different addresses??");
683       // FIXME: If both globals are external weak, they might both be null!
684       return Instruction::SetNE;
685     } else {
686       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
687       // Global can never be null.  FIXME: if we implement external weak
688       // linkage, this is not necessarily true!
689       return Instruction::SetNE;
690     }
691
692   } else {
693     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
694     // constantexpr, a CPR, or a simple constant.
695     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
696     Constant *CE1Op0 = CE1->getOperand(0);
697
698     switch (CE1->getOpcode()) {
699     case Instruction::Cast:
700       // If the cast is not actually changing bits, and the second operand is a
701       // null pointer, do the comparison with the pre-casted value.
702       if (V2->isNullValue() &&
703           CE1->getType()->isLosslesslyConvertibleTo(CE1Op0->getType()))
704         return evaluateRelation(CE1Op0,
705                                 Constant::getNullValue(CE1Op0->getType()));
706       break;
707
708     case Instruction::GetElementPtr:
709       // Ok, since this is a getelementptr, we know that the constant has a
710       // pointer type.  Check the various cases.
711       if (isa<ConstantPointerNull>(V2)) {
712         // If we are comparing a GEP to a null pointer, check to see if the base
713         // of the GEP equals the null pointer.
714         if (isa<GlobalValue>(CE1Op0)) {
715           // FIXME: this is not true when we have external weak references!
716           // No offset can go from a global to a null pointer.
717           return Instruction::SetGT;
718         } else if (isa<ConstantPointerNull>(CE1Op0)) {
719           // If we are indexing from a null pointer, check to see if we have any
720           // non-zero indices.
721           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
722             if (!CE1->getOperand(i)->isNullValue())
723               // Offsetting from null, must not be equal.
724               return Instruction::SetGT;
725           // Only zero indexes from null, must still be zero.
726           return Instruction::SetEQ;
727         }
728         // Otherwise, we can't really say if the first operand is null or not.
729       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
730         if (isa<ConstantPointerNull>(CE1Op0)) {
731           // FIXME: This is not true with external weak references.
732           return Instruction::SetLT;
733         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
734           if (CPR1 == CPR2) {
735             // If this is a getelementptr of the same global, then it must be
736             // different.  Because the types must match, the getelementptr could
737             // only have at most one index, and because we fold getelementptr's
738             // with a single zero index, it must be nonzero.
739             assert(CE1->getNumOperands() == 2 &&
740                    !CE1->getOperand(1)->isNullValue() &&
741                    "Suprising getelementptr!");
742             return Instruction::SetGT;
743           } else {
744             // If they are different globals, we don't know what the value is,
745             // but they can't be equal.
746             return Instruction::SetNE;
747           }
748         }
749       } else {
750         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
751         const Constant *CE2Op0 = CE2->getOperand(0);
752
753         // There are MANY other foldings that we could perform here.  They will
754         // probably be added on demand, as they seem needed.
755         switch (CE2->getOpcode()) {
756         default: break;
757         case Instruction::GetElementPtr:
758           // By far the most common case to handle is when the base pointers are
759           // obviously to the same or different globals.
760           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
761             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
762               return Instruction::SetNE;
763             // Ok, we know that both getelementptr instructions are based on the
764             // same global.  From this, we can precisely determine the relative
765             // ordering of the resultant pointers.
766             unsigned i = 1;
767             
768             // Compare all of the operands the GEP's have in common.
769             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); ++i)
770               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i))) {
771               case -1: return Instruction::SetLT;
772               case 1:  return Instruction::SetGT;
773               case -2: return Instruction::BinaryOpsEnd;
774               }
775
776             // Ok, we ran out of things they have in common.  If any leftovers
777             // are non-zero then we have a difference, otherwise we are equal.
778             for (; i < CE1->getNumOperands(); ++i)
779               if (!CE1->getOperand(i)->isNullValue())
780                 return Instruction::SetGT;
781             for (; i < CE2->getNumOperands(); ++i)
782               if (!CE2->getOperand(i)->isNullValue())
783                 return Instruction::SetLT;
784             return Instruction::SetEQ;
785           }
786         }
787       }
788       
789     default:
790       break;
791     }
792   }
793
794   return Instruction::BinaryOpsEnd;
795 }
796
797 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
798                                               const Constant *V1,
799                                               const Constant *V2) {
800   Constant *C = 0;
801   switch (Opcode) {
802   default:                   break;
803   case Instruction::Add:     C = ConstRules::get(V1, V2).add(V1, V2); break;
804   case Instruction::Sub:     C = ConstRules::get(V1, V2).sub(V1, V2); break;
805   case Instruction::Mul:     C = ConstRules::get(V1, V2).mul(V1, V2); break;
806   case Instruction::Div:     C = ConstRules::get(V1, V2).div(V1, V2); break;
807   case Instruction::Rem:     C = ConstRules::get(V1, V2).rem(V1, V2); break;
808   case Instruction::And:     C = ConstRules::get(V1, V2).op_and(V1, V2); break;
809   case Instruction::Or:      C = ConstRules::get(V1, V2).op_or (V1, V2); break;
810   case Instruction::Xor:     C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
811   case Instruction::Shl:     C = ConstRules::get(V1, V2).shl(V1, V2); break;
812   case Instruction::Shr:     C = ConstRules::get(V1, V2).shr(V1, V2); break;
813   case Instruction::SetEQ:   C = ConstRules::get(V1, V2).equalto(V1, V2); break;
814   case Instruction::SetLT:   C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
815   case Instruction::SetGT:   C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
816   case Instruction::SetNE:   // V1 != V2  ===  !(V1 == V2)
817     C = ConstRules::get(V1, V2).equalto(V1, V2);
818     if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
819     break;
820   case Instruction::SetLE:   // V1 <= V2  ===  !(V2 < V1)
821     C = ConstRules::get(V1, V2).lessthan(V2, V1);
822     if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
823     break;
824   case Instruction::SetGE:   // V1 >= V2  ===  !(V1 < V2)
825     C = ConstRules::get(V1, V2).lessthan(V1, V2);
826     if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
827     break;
828   }
829
830   // If we successfully folded the expression, return it now.
831   if (C) return C;
832
833   if (SetCondInst::isRelational(Opcode)) {
834     if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
835       return UndefValue::get(Type::BoolTy);
836     switch (evaluateRelation(V1, V2)) {
837     default: assert(0 && "Unknown relational!");
838     case Instruction::BinaryOpsEnd:
839       break;  // Couldn't determine anything about these constants.
840     case Instruction::SetEQ:   // We know the constants are equal!
841       // If we know the constants are equal, we can decide the result of this
842       // computation precisely.
843       return ConstantBool::get(Opcode == Instruction::SetEQ ||
844                                Opcode == Instruction::SetLE ||
845                                Opcode == Instruction::SetGE);
846     case Instruction::SetLT:
847       // If we know that V1 < V2, we can decide the result of this computation
848       // precisely.
849       return ConstantBool::get(Opcode == Instruction::SetLT ||
850                                Opcode == Instruction::SetNE ||
851                                Opcode == Instruction::SetLE);
852     case Instruction::SetGT:
853       // If we know that V1 > V2, we can decide the result of this computation
854       // precisely.
855       return ConstantBool::get(Opcode == Instruction::SetGT ||
856                                Opcode == Instruction::SetNE ||
857                                Opcode == Instruction::SetGE);
858     case Instruction::SetLE:
859       // If we know that V1 <= V2, we can only partially decide this relation.
860       if (Opcode == Instruction::SetGT) return ConstantBool::False;
861       if (Opcode == Instruction::SetLT) return ConstantBool::True;
862       break;
863
864     case Instruction::SetGE:
865       // If we know that V1 >= V2, we can only partially decide this relation.
866       if (Opcode == Instruction::SetLT) return ConstantBool::False;
867       if (Opcode == Instruction::SetGT) return ConstantBool::True;
868       break;
869       
870     case Instruction::SetNE:
871       // If we know that V1 != V2, we can only partially decide this relation.
872       if (Opcode == Instruction::SetEQ) return ConstantBool::False;
873       if (Opcode == Instruction::SetNE) return ConstantBool::True;
874       break;
875     }
876   }
877
878   if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) {
879     switch (Opcode) {
880     case Instruction::Add:
881     case Instruction::Sub:
882     case Instruction::Xor:
883       return UndefValue::get(V1->getType());
884
885     case Instruction::Mul:
886     case Instruction::And:
887       return Constant::getNullValue(V1->getType());
888     case Instruction::Div:
889     case Instruction::Rem:
890       if (!isa<UndefValue>(V2))     // undef/X -> 0
891         return Constant::getNullValue(V1->getType());
892       return const_cast<Constant*>(V2);                // X/undef -> undef
893     case Instruction::Or:           // X|undef -> -1
894       return ConstantInt::getAllOnesValue(V1->getType());
895     case Instruction::Shr:
896       if (!isa<UndefValue>(V2)) {
897         if (V1->getType()->isSigned())
898           return const_cast<Constant*>(V1);  // undef >>s X -> undef
899         // undef >>u X -> 0
900       } else if (isa<UndefValue>(V1)) {
901         return const_cast<Constant*>(V1);   //  undef >> undef -> undef
902       } else {
903         if (V1->getType()->isSigned())
904           return const_cast<Constant*>(V1);  // X >>s undef -> X
905         // X >>u undef -> 0
906       }
907       return Constant::getNullValue(V1->getType());
908
909     case Instruction::Shl:
910       // undef << X -> 0   X << undef -> 0
911       return Constant::getNullValue(V1->getType());
912     }
913   }
914
915   if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
916     if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
917       // There are many possible foldings we could do here.  We should probably
918       // at least fold add of a pointer with an integer into the appropriate
919       // getelementptr.  This will improve alias analysis a bit.
920
921
922
923
924     } else {
925       // Just implement a couple of simple identities.
926       switch (Opcode) {
927       case Instruction::Add:
928         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X + 0 == X
929         break;
930       case Instruction::Sub:
931         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X - 0 == X
932         break;
933       case Instruction::Mul:
934         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X * 0 == 0
935         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
936           if (CI->getRawValue() == 1)
937             return const_cast<Constant*>(V1);                     // X * 1 == X
938         break;
939       case Instruction::Div:
940         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
941           if (CI->getRawValue() == 1)
942             return const_cast<Constant*>(V1);                     // X / 1 == X
943         break;
944       case Instruction::Rem:
945         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
946           if (CI->getRawValue() == 1)
947             return Constant::getNullValue(CI->getType()); // X % 1 == 0
948         break;
949       case Instruction::And:
950         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
951           return const_cast<Constant*>(V1);                       // X & -1 == X
952         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X & 0 == 0
953         if (CE1->getOpcode() == Instruction::Cast &&
954             isa<GlobalValue>(CE1->getOperand(0))) {
955           GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
956
957           // Functions are at least 4-byte aligned.  If and'ing the address of a
958           // function with a constant < 4, fold it to zero.
959           if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
960             if (CI->getRawValue() < 4 && isa<Function>(CPR))
961               return Constant::getNullValue(CI->getType());
962         }
963         break;
964       case Instruction::Or:
965         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X | 0 == X
966         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
967           return const_cast<Constant*>(V2);  // X | -1 == -1
968         break;
969       case Instruction::Xor:
970         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X ^ 0 == X
971         break;
972       }
973     }
974
975   } else if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
976     // If V2 is a constant expr and V1 isn't, flop them around and fold the
977     // other way if possible.
978     switch (Opcode) {
979     case Instruction::Add:
980     case Instruction::Mul:
981     case Instruction::And:
982     case Instruction::Or:
983     case Instruction::Xor:
984     case Instruction::SetEQ:
985     case Instruction::SetNE:
986       // No change of opcode required.
987       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
988
989     case Instruction::SetLT:
990     case Instruction::SetGT:
991     case Instruction::SetLE:
992     case Instruction::SetGE:
993       // Change the opcode as necessary to swap the operands.
994       Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
995       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
996
997     case Instruction::Shl:
998     case Instruction::Shr:
999     case Instruction::Sub:
1000     case Instruction::Div:
1001     case Instruction::Rem:
1002     default:  // These instructions cannot be flopped around.
1003       break;
1004     }
1005   }
1006   return 0;
1007 }
1008
1009 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1010                                           const std::vector<Value*> &IdxList) {
1011   if (IdxList.size() == 0 ||
1012       (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
1013     return const_cast<Constant*>(C);
1014
1015   if (isa<UndefValue>(C)) {
1016     const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1017                                                        true);
1018     assert(Ty != 0 && "Invalid indices for GEP!");
1019     return UndefValue::get(PointerType::get(Ty));
1020   }
1021
1022   Constant *Idx0 = cast<Constant>(IdxList[0]);
1023   if (C->isNullValue()) {
1024     bool isNull = true;
1025     for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1026       if (!cast<Constant>(IdxList[i])->isNullValue()) {
1027         isNull = false;
1028         break;
1029       }
1030     if (isNull) {
1031       const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1032                                                          true);
1033       assert(Ty != 0 && "Invalid indices for GEP!");
1034       return ConstantPointerNull::get(PointerType::get(Ty));
1035     }
1036
1037     if (IdxList.size() == 1) {
1038       const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
1039       if (unsigned ElSize = ElTy->getPrimitiveSize()) {
1040         // gep null, C is equal to C*sizeof(nullty).  If nullty is a known llvm
1041         // type, we can statically fold this.
1042         Constant *R = ConstantUInt::get(Type::UIntTy, ElSize);
1043         R = ConstantExpr::getCast(R, Idx0->getType());
1044         R = ConstantExpr::getMul(R, Idx0);
1045         return ConstantExpr::getCast(R, C->getType());
1046       }
1047     }
1048   }
1049
1050   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1051     // Combine Indices - If the source pointer to this getelementptr instruction
1052     // is a getelementptr instruction, combine the indices of the two
1053     // getelementptr instructions into a single instruction.
1054     //
1055     if (CE->getOpcode() == Instruction::GetElementPtr) {
1056       const Type *LastTy = 0;
1057       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1058            I != E; ++I)
1059         LastTy = *I;
1060
1061       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1062         std::vector<Value*> NewIndices;
1063         NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1064         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1065           NewIndices.push_back(CE->getOperand(i));
1066
1067         // Add the last index of the source with the first index of the new GEP.
1068         // Make sure to handle the case when they are actually different types.
1069         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1070         // Otherwise it must be an array.
1071         if (!Idx0->isNullValue()) {
1072           const Type *IdxTy = Combined->getType();
1073           if (IdxTy != Idx0->getType()) IdxTy = Type::LongTy;
1074           Combined = 
1075             ConstantExpr::get(Instruction::Add,
1076                               ConstantExpr::getCast(Idx0, IdxTy),
1077                               ConstantExpr::getCast(Combined, IdxTy));
1078         }
1079         
1080         NewIndices.push_back(Combined);
1081         NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1082         return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1083       }
1084     }
1085
1086     // Implement folding of:
1087     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1088     //                        long 0, long 0)
1089     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1090     //
1091     if (CE->getOpcode() == Instruction::Cast && IdxList.size() > 1 &&
1092         Idx0->isNullValue())
1093       if (const PointerType *SPT = 
1094           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1095         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1096           if (const ArrayType *CAT =
1097               dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1098             if (CAT->getElementType() == SAT->getElementType())
1099               return ConstantExpr::getGetElementPtr(
1100                       (Constant*)CE->getOperand(0), IdxList);
1101   }
1102   return 0;
1103 }
1104