25c756ab6e5b78b41c774370abb9233e978650fd
[oota-llvm.git] / lib / VMCore / ConstantFold.cpp
1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements folding of constants for LLVM.  This implements the
11 // (internal) ConstantFold.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 "ConstantFold.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <limits>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //                ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
38
39 /// BitCastConstantVector - Convert the specified ConstantVector node to the
40 /// specified vector type.  At this point, we know that the elements of the
41 /// input vector constant are all simple integer or FP values.
42 static Constant *BitCastConstantVector(ConstantVector *CV,
43                                        const VectorType *DstTy) {
44   // If this cast changes element count then we can't handle it here:
45   // doing so requires endianness information.  This should be handled by
46   // Analysis/ConstantFolding.cpp
47   unsigned NumElts = DstTy->getNumElements();
48   if (NumElts != CV->getNumOperands())
49     return 0;
50   
51   // Check to verify that all elements of the input are simple.
52   for (unsigned i = 0; i != NumElts; ++i) {
53     if (!isa<ConstantInt>(CV->getOperand(i)) &&
54         !isa<ConstantFP>(CV->getOperand(i)))
55       return 0;
56   }
57
58   // Bitcast each element now.
59   std::vector<Constant*> Result;
60   const Type *DstEltTy = DstTy->getElementType();
61   for (unsigned i = 0; i != NumElts; ++i)
62     Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63   return ConstantVector::get(Result);
64 }
65
66 /// This function determines which opcode to use to fold two constant cast 
67 /// expressions together. It uses CastInst::isEliminableCastPair to determine
68 /// the opcode. Consequently its just a wrapper around that function.
69 /// @brief Determine if it is valid to fold a cast of a cast
70 static unsigned
71 foldConstantCastPair(
72   unsigned opc,          ///< opcode of the second cast constant expression
73   const ConstantExpr*Op, ///< the first cast constant expression
74   const Type *DstTy      ///< desintation type of the first cast
75 ) {
76   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78   assert(CastInst::isCast(opc) && "Invalid cast opcode");
79   
80   // The the types and opcodes for the two Cast constant expressions
81   const Type *SrcTy = Op->getOperand(0)->getType();
82   const Type *MidTy = Op->getType();
83   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84   Instruction::CastOps secondOp = Instruction::CastOps(opc);
85
86   // Let CastInst::isEliminableCastPair do the heavy lifting.
87   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
88                                         Type::Int64Ty);
89 }
90
91 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92   const Type *SrcTy = V->getType();
93   if (SrcTy == DestTy)
94     return V; // no-op cast
95   
96   // Check to see if we are casting a pointer to an aggregate to a pointer to
97   // the first element.  If so, return the appropriate GEP instruction.
98   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
100       if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
101         SmallVector<Value*, 8> IdxList;
102         IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
103         const Type *ElTy = PTy->getElementType();
104         while (ElTy != DPTy->getElementType()) {
105           if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
106             if (STy->getNumElements() == 0) break;
107             ElTy = STy->getElementType(0);
108             IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
109           } else if (const SequentialType *STy = 
110                      dyn_cast<SequentialType>(ElTy)) {
111             if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
112             ElTy = STy->getElementType();
113             IdxList.push_back(IdxList[0]);
114           } else {
115             break;
116           }
117         }
118         
119         if (ElTy == DPTy->getElementType())
120           return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
121       }
122   
123   // Handle casts from one vector constant to another.  We know that the src 
124   // and dest type have the same size (otherwise its an illegal cast).
125   if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
126     if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
127       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
128              "Not cast between same sized vectors!");
129       // First, check for null.  Undef is already handled.
130       if (isa<ConstantAggregateZero>(V))
131         return Constant::getNullValue(DestTy);
132       
133       if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
134         return BitCastConstantVector(CV, DestPTy);
135     }
136   }
137   
138   // Finally, implement bitcast folding now.   The code below doesn't handle
139   // bitcast right.
140   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
141     return ConstantPointerNull::get(cast<PointerType>(DestTy));
142   
143   // Handle integral constant input.
144   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
145     if (DestTy->isInteger())
146       // Integral -> Integral. This is a no-op because the bit widths must
147       // be the same. Consequently, we just fold to V.
148       return V;
149     
150     if (DestTy->isFloatingPoint()) {
151       assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) && 
152              "Unknown FP type!");
153       return ConstantFP::get(APFloat(CI->getValue()));
154     }
155     // Otherwise, can't fold this (vector?)
156     return 0;
157   }
158   
159   // Handle ConstantFP input.
160   if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
161     // FP -> Integral.
162     if (DestTy == Type::Int32Ty) {
163       return ConstantInt::get(FP->getValueAPF().convertToAPInt());
164     } else {
165       assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
166       return ConstantInt::get(FP->getValueAPF().convertToAPInt());
167     }
168   }
169   return 0;
170 }
171
172
173 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
174                                             const Type *DestTy) {
175   if (isa<UndefValue>(V)) {
176     // zext(undef) = 0, because the top bits will be zero.
177     // sext(undef) = 0, because the top bits will all be the same.
178     // [us]itofp(undef) = 0, because the result value is bounded.
179     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
180         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
181       return Constant::getNullValue(DestTy);
182     return UndefValue::get(DestTy);
183   }
184   // No compile-time operations on this type yet.
185   if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
186     return 0;
187
188   // If the cast operand is a constant expression, there's a few things we can
189   // do to try to simplify it.
190   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
191     if (CE->isCast()) {
192       // Try hard to fold cast of cast because they are often eliminable.
193       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
194         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
195     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
196       // If all of the indexes in the GEP are null values, there is no pointer
197       // adjustment going on.  We might as well cast the source pointer.
198       bool isAllNull = true;
199       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
200         if (!CE->getOperand(i)->isNullValue()) {
201           isAllNull = false;
202           break;
203         }
204       if (isAllNull)
205         // This is casting one pointer type to another, always BitCast
206         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
207     }
208   }
209
210   // We actually have to do a cast now. Perform the cast according to the
211   // opcode specified.
212   switch (opc) {
213   case Instruction::FPTrunc:
214   case Instruction::FPExt:
215     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
216       APFloat Val = FPC->getValueAPF();
217       Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
218                   DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
219                   DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
220                   DestTy == Type::FP128Ty ? APFloat::IEEEquad :
221                   APFloat::Bogus,
222                   APFloat::rmNearestTiesToEven);
223       return ConstantFP::get(Val);
224     }
225     return 0; // Can't fold.
226   case Instruction::FPToUI: 
227   case Instruction::FPToSI:
228     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
229       const APFloat &V = FPC->getValueAPF();
230       uint64_t x[2]; 
231       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
232       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
233                                 APFloat::rmTowardZero);
234       APInt Val(DestBitWidth, 2, x);
235       return ConstantInt::get(Val);
236     }
237     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
238       std::vector<Constant*> res;
239       const VectorType *DestVecTy = cast<VectorType>(DestTy);
240       const Type *DstEltTy = DestVecTy->getElementType();
241       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) {
242         Constant *C = ConstantFoldCastInstruction(opc, CV->getOperand(i),
243                                                   DstEltTy);
244         if (!C) return 0;       // Can't fold operand.
245         res.push_back(C);
246       }
247       return ConstantVector::get(DestVecTy, res);
248     }
249     return 0; // Can't fold.
250   case Instruction::IntToPtr:   //always treated as unsigned
251     if (V->isNullValue())       // Is it an integral null value?
252       return ConstantPointerNull::get(cast<PointerType>(DestTy));
253     return 0;                   // Other pointer types cannot be casted
254   case Instruction::PtrToInt:   // always treated as unsigned
255     if (V->isNullValue())       // is it a null pointer value?
256       return ConstantInt::get(DestTy, 0);
257     return 0;                   // Other pointer types cannot be casted
258   case Instruction::UIToFP:
259   case Instruction::SIToFP:
260     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
261       APInt api = CI->getValue();
262       const uint64_t zero[] = {0, 0};
263       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
264                                   2, zero));
265       (void)apf.convertFromAPInt(api, 
266                                  opc==Instruction::SIToFP,
267                                  APFloat::rmNearestTiesToEven);
268       return ConstantFP::get(apf);
269     }
270     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
271       std::vector<Constant*> res;
272       const VectorType *DestVecTy = cast<VectorType>(DestTy);
273       const Type *DstEltTy = DestVecTy->getElementType();
274       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) {
275         Constant *C = ConstantFoldCastInstruction(opc, CV->getOperand(i),
276                                                   DstEltTy);
277         if (!C) return 0;       // Can't fold operand.
278         res.push_back(C);
279       }
280       return ConstantVector::get(DestVecTy, res);
281     }
282     return 0;
283   case Instruction::ZExt:
284     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
285       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
286       APInt Result(CI->getValue());
287       Result.zext(BitWidth);
288       return ConstantInt::get(Result);
289     }
290     return 0;
291   case Instruction::SExt:
292     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
293       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
294       APInt Result(CI->getValue());
295       Result.sext(BitWidth);
296       return ConstantInt::get(Result);
297     }
298     return 0;
299   case Instruction::Trunc:
300     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
301       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
302       APInt Result(CI->getValue());
303       Result.trunc(BitWidth);
304       return ConstantInt::get(Result);
305     }
306     return 0;
307   case Instruction::BitCast:
308     return FoldBitCast(const_cast<Constant*>(V), DestTy);
309   default:
310     assert(!"Invalid CE CastInst opcode");
311     break;
312   }
313
314   assert(0 && "Failed to cast constant expression");
315   return 0;
316 }
317
318 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
319                                               const Constant *V1,
320                                               const Constant *V2) {
321   if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
322     return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
323
324   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
325   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
326   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
327   if (V1 == V2) return const_cast<Constant*>(V1);
328   return 0;
329 }
330
331 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
332                                                       const Constant *Idx) {
333   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
334     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
335   if (Val->isNullValue())  // ee(zero, x) -> zero
336     return Constant::getNullValue(
337                           cast<VectorType>(Val->getType())->getElementType());
338   
339   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
340     if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
341       return CVal->getOperand(CIdx->getZExtValue());
342     } else if (isa<UndefValue>(Idx)) {
343       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
344       return CVal->getOperand(0);
345     }
346   }
347   return 0;
348 }
349
350 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
351                                                      const Constant *Elt,
352                                                      const Constant *Idx) {
353   const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
354   if (!CIdx) return 0;
355   APInt idxVal = CIdx->getValue();
356   if (isa<UndefValue>(Val)) { 
357     // Insertion of scalar constant into vector undef
358     // Optimize away insertion of undef
359     if (isa<UndefValue>(Elt))
360       return const_cast<Constant*>(Val);
361     // Otherwise break the aggregate undef into multiple undefs and do
362     // the insertion
363     unsigned numOps = 
364       cast<VectorType>(Val->getType())->getNumElements();
365     std::vector<Constant*> Ops; 
366     Ops.reserve(numOps);
367     for (unsigned i = 0; i < numOps; ++i) {
368       const Constant *Op =
369         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
370       Ops.push_back(const_cast<Constant*>(Op));
371     }
372     return ConstantVector::get(Ops);
373   }
374   if (isa<ConstantAggregateZero>(Val)) {
375     // Insertion of scalar constant into vector aggregate zero
376     // Optimize away insertion of zero
377     if (Elt->isNullValue())
378       return const_cast<Constant*>(Val);
379     // Otherwise break the aggregate zero into multiple zeros and do
380     // the insertion
381     unsigned numOps = 
382       cast<VectorType>(Val->getType())->getNumElements();
383     std::vector<Constant*> Ops; 
384     Ops.reserve(numOps);
385     for (unsigned i = 0; i < numOps; ++i) {
386       const Constant *Op =
387         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
388       Ops.push_back(const_cast<Constant*>(Op));
389     }
390     return ConstantVector::get(Ops);
391   }
392   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
393     // Insertion of scalar constant into vector constant
394     std::vector<Constant*> Ops; 
395     Ops.reserve(CVal->getNumOperands());
396     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
397       const Constant *Op =
398         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
399       Ops.push_back(const_cast<Constant*>(Op));
400     }
401     return ConstantVector::get(Ops);
402   }
403
404   return 0;
405 }
406
407 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
408 /// return the specified element value.  Otherwise return null.
409 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
410   if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
411     return CV->getOperand(EltNo);
412   
413   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
414   if (isa<ConstantAggregateZero>(C))
415     return Constant::getNullValue(EltTy);
416   if (isa<UndefValue>(C))
417     return UndefValue::get(EltTy);
418   return 0;
419 }
420
421 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
422                                                      const Constant *V2,
423                                                      const Constant *Mask) {
424   // Undefined shuffle mask -> undefined value.
425   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
426   
427   unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
428   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
429   
430   // Loop over the shuffle mask, evaluating each element.
431   SmallVector<Constant*, 32> Result;
432   for (unsigned i = 0; i != NumElts; ++i) {
433     Constant *InElt = GetVectorElement(Mask, i);
434     if (InElt == 0) return 0;
435     
436     if (isa<UndefValue>(InElt))
437       InElt = UndefValue::get(EltTy);
438     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
439       unsigned Elt = CI->getZExtValue();
440       if (Elt >= NumElts*2)
441         InElt = UndefValue::get(EltTy);
442       else if (Elt >= NumElts)
443         InElt = GetVectorElement(V2, Elt-NumElts);
444       else
445         InElt = GetVectorElement(V1, Elt);
446       if (InElt == 0) return 0;
447     } else {
448       // Unknown value.
449       return 0;
450     }
451     Result.push_back(InElt);
452   }
453   
454   return ConstantVector::get(&Result[0], Result.size());
455 }
456
457 Constant *llvm::ConstantFoldExtractValueInstruction(const Constant *Agg,
458                                                     const unsigned *Idxs,
459                                                     unsigned NumIdx) {
460   // Base case: no indices, so return the entire value.
461   if (NumIdx == 0)
462     return const_cast<Constant *>(Agg);
463
464   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
465     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
466                                                             Idxs,
467                                                             Idxs + NumIdx));
468
469   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
470     return
471       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
472                                                               Idxs,
473                                                               Idxs + NumIdx));
474
475   // Otherwise recurse.
476   return ConstantFoldExtractValueInstruction(Agg->getOperand(*Idxs),
477                                              Idxs+1, NumIdx-1);
478 }
479
480 Constant *llvm::ConstantFoldInsertValueInstruction(const Constant *Agg,
481                                                    const Constant *Val,
482                                                    const unsigned *Idxs,
483                                                    unsigned NumIdx) {
484   // Base case: no indices, so replace the entire value.
485   if (NumIdx == 0)
486     return const_cast<Constant *>(Val);
487
488   if (isa<UndefValue>(Agg)) {
489     // Insertion of constant into aggregate undef
490     // Optimize away insertion of undef
491     if (isa<UndefValue>(Val))
492       return const_cast<Constant*>(Agg);
493     // Otherwise break the aggregate undef into multiple undefs and do
494     // the insertion
495     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
496     unsigned numOps;
497     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
498       numOps = AR->getNumElements();
499     else
500       numOps = cast<StructType>(AggTy)->getNumElements();
501     std::vector<Constant*> Ops(numOps); 
502     for (unsigned i = 0; i < numOps; ++i) {
503       const Type *MemberTy = AggTy->getTypeAtIndex(i);
504       const Constant *Op =
505         (*Idxs == i) ?
506         ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
507                                            Val, Idxs+1, NumIdx-1) :
508         UndefValue::get(MemberTy);
509       Ops[i] = const_cast<Constant*>(Op);
510     }
511     if (isa<StructType>(AggTy))
512       return ConstantStruct::get(Ops);
513     else
514       return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
515   }
516   if (isa<ConstantAggregateZero>(Agg)) {
517     // Insertion of constant into aggregate zero
518     // Optimize away insertion of zero
519     if (Val->isNullValue())
520       return const_cast<Constant*>(Agg);
521     // Otherwise break the aggregate zero into multiple zeros and do
522     // the insertion
523     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
524     unsigned numOps;
525     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
526       numOps = AR->getNumElements();
527     else
528       numOps = cast<StructType>(AggTy)->getNumElements();
529     std::vector<Constant*> Ops(numOps);
530     for (unsigned i = 0; i < numOps; ++i) {
531       const Type *MemberTy = AggTy->getTypeAtIndex(i);
532       const Constant *Op =
533         (*Idxs == i) ?
534         ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
535                                            Val, Idxs+1, NumIdx-1) :
536         Constant::getNullValue(MemberTy);
537       Ops[i] = const_cast<Constant*>(Op);
538     }
539     if (isa<StructType>(AggTy))
540       return ConstantStruct::get(Ops);
541     else
542       return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
543   }
544   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
545     // Insertion of constant into aggregate constant
546     std::vector<Constant*> Ops(Agg->getNumOperands());
547     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
548       const Constant *Op =
549         (*Idxs == i) ?
550         ConstantFoldInsertValueInstruction(Agg->getOperand(i),
551                                            Val, Idxs+1, NumIdx-1) :
552         Agg->getOperand(i);
553       Ops[i] = const_cast<Constant*>(Op);
554     }
555     Constant *C;
556     if (isa<StructType>(Agg->getType()))
557       C = ConstantStruct::get(Ops);
558     else
559       C = ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
560     return C;
561   }
562
563   return 0;
564 }
565
566 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
567 /// function pointer to each element pair, producing a new ConstantVector
568 /// constant. Either or both of V1 and V2 may be NULL, meaning a
569 /// ConstantAggregateZero operand.
570 static Constant *EvalVectorOp(const ConstantVector *V1, 
571                               const ConstantVector *V2,
572                               const VectorType *VTy,
573                               Constant *(*FP)(Constant*, Constant*)) {
574   std::vector<Constant*> Res;
575   const Type *EltTy = VTy->getElementType();
576   for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
577     const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
578     const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
579     Res.push_back(FP(const_cast<Constant*>(C1),
580                      const_cast<Constant*>(C2)));
581   }
582   return ConstantVector::get(Res);
583 }
584
585 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
586                                               const Constant *C1,
587                                               const Constant *C2) {
588   // No compile-time operations on this type yet.
589   if (C1->getType() == Type::PPC_FP128Ty)
590     return 0;
591
592   // Handle UndefValue up front
593   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
594     switch (Opcode) {
595     case Instruction::Xor:
596       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
597         // Handle undef ^ undef -> 0 special case. This is a common
598         // idiom (misuse).
599         return Constant::getNullValue(C1->getType());
600       // Fallthrough
601     case Instruction::Add:
602     case Instruction::Sub:
603       return UndefValue::get(C1->getType());
604     case Instruction::Mul:
605     case Instruction::And:
606       return Constant::getNullValue(C1->getType());
607     case Instruction::UDiv:
608     case Instruction::SDiv:
609     case Instruction::FDiv:
610     case Instruction::URem:
611     case Instruction::SRem:
612     case Instruction::FRem:
613       if (!isa<UndefValue>(C2))                    // undef / X -> 0
614         return Constant::getNullValue(C1->getType());
615       return const_cast<Constant*>(C2);            // X / undef -> undef
616     case Instruction::Or:                          // X | undef -> -1
617       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
618         return ConstantVector::getAllOnesValue(PTy);
619       return ConstantInt::getAllOnesValue(C1->getType());
620     case Instruction::LShr:
621       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
622         return const_cast<Constant*>(C1);           // undef lshr undef -> undef
623       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
624                                                     // undef lshr X -> 0
625     case Instruction::AShr:
626       if (!isa<UndefValue>(C2))
627         return const_cast<Constant*>(C1);           // undef ashr X --> undef
628       else if (isa<UndefValue>(C1)) 
629         return const_cast<Constant*>(C1);           // undef ashr undef -> undef
630       else
631         return const_cast<Constant*>(C1);           // X ashr undef --> X
632     case Instruction::Shl:
633       // undef << X -> 0   or   X << undef -> 0
634       return Constant::getNullValue(C1->getType());
635     }
636   }
637
638   // Handle simplifications of the RHS when a constant int.
639   if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
640     switch (Opcode) {
641     case Instruction::Add:
642       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X + 0 == X
643       break;
644     case Instruction::Sub:
645       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X - 0 == X
646       break;
647     case Instruction::Mul:
648       if (CI2->equalsInt(0)) return const_cast<Constant*>(C2);  // X * 0 == 0
649       if (CI2->equalsInt(1))
650         return const_cast<Constant*>(C1);                       // X * 1 == X
651       break;
652     case Instruction::UDiv:
653     case Instruction::SDiv:
654       if (CI2->equalsInt(1))
655         return const_cast<Constant*>(C1);                     // X / 1 == X
656       break;
657     case Instruction::URem:
658     case Instruction::SRem:
659       if (CI2->equalsInt(1))
660         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
661       break;
662     case Instruction::And:
663       if (CI2->isZero()) return const_cast<Constant*>(C2);    // X & 0 == 0
664       if (CI2->isAllOnesValue())
665         return const_cast<Constant*>(C1);                     // X & -1 == X
666       
667       if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
668         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
669         if (CE1->getOpcode() == Instruction::ZExt) {
670           unsigned DstWidth = CI2->getType()->getBitWidth();
671           unsigned SrcWidth =
672             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
673           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
674           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
675             return const_cast<Constant*>(C1);
676         }
677         
678         // If and'ing the address of a global with a constant, fold it.
679         if (CE1->getOpcode() == Instruction::PtrToInt && 
680             isa<GlobalValue>(CE1->getOperand(0))) {
681           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
682         
683           // Functions are at least 4-byte aligned.
684           unsigned GVAlign = GV->getAlignment();
685           if (isa<Function>(GV))
686             GVAlign = std::max(GVAlign, 4U);
687           
688           if (GVAlign > 1) {
689             unsigned DstWidth = CI2->getType()->getBitWidth();
690             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
691             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
692
693             // If checking bits we know are clear, return zero.
694             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
695               return Constant::getNullValue(CI2->getType());
696           }
697         }
698       }
699       break;
700     case Instruction::Or:
701       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X | 0 == X
702       if (CI2->isAllOnesValue())
703         return const_cast<Constant*>(C2);  // X | -1 == -1
704       break;
705     case Instruction::Xor:
706       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X ^ 0 == X
707       break;
708     case Instruction::AShr:
709       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
710       if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
711         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
712           return ConstantExpr::getLShr(const_cast<Constant*>(C1),
713                                        const_cast<Constant*>(C2));
714       break;
715     }
716   }
717   
718   // At this point we know neither constant is an UndefValue.
719   if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
720     if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
721       using namespace APIntOps;
722       const APInt &C1V = CI1->getValue();
723       const APInt &C2V = CI2->getValue();
724       switch (Opcode) {
725       default:
726         break;
727       case Instruction::Add:     
728         return ConstantInt::get(C1V + C2V);
729       case Instruction::Sub:     
730         return ConstantInt::get(C1V - C2V);
731       case Instruction::Mul:     
732         return ConstantInt::get(C1V * C2V);
733       case Instruction::UDiv:
734         if (CI2->isNullValue())                  
735           return 0;        // X / 0 -> can't fold
736         return ConstantInt::get(C1V.udiv(C2V));
737       case Instruction::SDiv:
738         if (CI2->isNullValue()) 
739           return 0;        // X / 0 -> can't fold
740         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
741           return 0;        // MIN_INT / -1 -> overflow
742         return ConstantInt::get(C1V.sdiv(C2V));
743       case Instruction::URem:
744         if (C2->isNullValue()) 
745           return 0;        // X / 0 -> can't fold
746         return ConstantInt::get(C1V.urem(C2V));
747       case Instruction::SRem:    
748         if (CI2->isNullValue()) 
749           return 0;        // X % 0 -> can't fold
750         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
751           return 0;        // MIN_INT % -1 -> overflow
752         return ConstantInt::get(C1V.srem(C2V));
753       case Instruction::And:
754         return ConstantInt::get(C1V & C2V);
755       case Instruction::Or:
756         return ConstantInt::get(C1V | C2V);
757       case Instruction::Xor:
758         return ConstantInt::get(C1V ^ C2V);
759       case Instruction::Shl: {
760         uint32_t shiftAmt = C2V.getZExtValue();
761         if (shiftAmt < C1V.getBitWidth())
762           return ConstantInt::get(C1V.shl(shiftAmt));
763         else
764           return UndefValue::get(C1->getType()); // too big shift is undef
765       }
766       case Instruction::LShr: {
767         uint32_t shiftAmt = C2V.getZExtValue();
768         if (shiftAmt < C1V.getBitWidth())
769           return ConstantInt::get(C1V.lshr(shiftAmt));
770         else
771           return UndefValue::get(C1->getType()); // too big shift is undef
772       }
773       case Instruction::AShr: {
774         uint32_t shiftAmt = C2V.getZExtValue();
775         if (shiftAmt < C1V.getBitWidth())
776           return ConstantInt::get(C1V.ashr(shiftAmt));
777         else
778           return UndefValue::get(C1->getType()); // too big shift is undef
779       }
780       }
781     }
782   } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
783     if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
784       APFloat C1V = CFP1->getValueAPF();
785       APFloat C2V = CFP2->getValueAPF();
786       APFloat C3V = C1V;  // copy for modification
787       switch (Opcode) {
788       default:                   
789         break;
790       case Instruction::Add:
791         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
792         return ConstantFP::get(C3V);
793       case Instruction::Sub:     
794         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
795         return ConstantFP::get(C3V);
796       case Instruction::Mul:
797         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
798         return ConstantFP::get(C3V);
799       case Instruction::FDiv:
800         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
801         return ConstantFP::get(C3V);
802       case Instruction::FRem:
803         if (C2V.isZero()) {
804           // IEEE 754, Section 7.1, #5
805           if (CFP1->getType() == Type::DoubleTy)
806             return ConstantFP::get(APFloat(std::numeric_limits<double>::
807                                            quiet_NaN()));
808           if (CFP1->getType() == Type::FloatTy)
809             return ConstantFP::get(APFloat(std::numeric_limits<float>::
810                                            quiet_NaN()));
811           break;
812         }
813         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
814         return ConstantFP::get(C3V);
815       }
816     }
817   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
818     const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
819     const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
820     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
821         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
822       switch (Opcode) {
823       default:
824         break;
825       case Instruction::Add: 
826         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
827       case Instruction::Sub: 
828         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
829       case Instruction::Mul: 
830         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
831       case Instruction::UDiv:
832         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
833       case Instruction::SDiv:
834         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
835       case Instruction::FDiv:
836         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
837       case Instruction::URem:
838         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
839       case Instruction::SRem:
840         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
841       case Instruction::FRem:
842         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
843       case Instruction::And: 
844         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
845       case Instruction::Or:  
846         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
847       case Instruction::Xor: 
848         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
849       }
850     }
851   }
852
853   if (isa<ConstantExpr>(C1)) {
854     // There are many possible foldings we could do here.  We should probably
855     // at least fold add of a pointer with an integer into the appropriate
856     // getelementptr.  This will improve alias analysis a bit.
857   } else if (isa<ConstantExpr>(C2)) {
858     // If C2 is a constant expr and C1 isn't, flop them around and fold the
859     // other way if possible.
860     switch (Opcode) {
861     case Instruction::Add:
862     case Instruction::Mul:
863     case Instruction::And:
864     case Instruction::Or:
865     case Instruction::Xor:
866       // No change of opcode required.
867       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
868       
869     case Instruction::Shl:
870     case Instruction::LShr:
871     case Instruction::AShr:
872     case Instruction::Sub:
873     case Instruction::SDiv:
874     case Instruction::UDiv:
875     case Instruction::FDiv:
876     case Instruction::URem:
877     case Instruction::SRem:
878     case Instruction::FRem:
879     default:  // These instructions cannot be flopped around.
880       break;
881     }
882   }
883   
884   // We don't know how to fold this.
885   return 0;
886 }
887
888 /// isZeroSizedType - This type is zero sized if its an array or structure of
889 /// zero sized types.  The only leaf zero sized type is an empty structure.
890 static bool isMaybeZeroSizedType(const Type *Ty) {
891   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
892   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
893
894     // If all of elements have zero size, this does too.
895     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
896       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
897     return true;
898
899   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
900     return isMaybeZeroSizedType(ATy->getElementType());
901   }
902   return false;
903 }
904
905 /// IdxCompare - Compare the two constants as though they were getelementptr
906 /// indices.  This allows coersion of the types to be the same thing.
907 ///
908 /// If the two constants are the "same" (after coersion), return 0.  If the
909 /// first is less than the second, return -1, if the second is less than the
910 /// first, return 1.  If the constants are not integral, return -2.
911 ///
912 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
913   if (C1 == C2) return 0;
914
915   // Ok, we found a different index.  If they are not ConstantInt, we can't do
916   // anything with them.
917   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
918     return -2; // don't know!
919
920   // Ok, we have two differing integer indices.  Sign extend them to be the same
921   // type.  Long is always big enough, so we use it.
922   if (C1->getType() != Type::Int64Ty)
923     C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
924
925   if (C2->getType() != Type::Int64Ty)
926     C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
927
928   if (C1 == C2) return 0;  // They are equal
929
930   // If the type being indexed over is really just a zero sized type, there is
931   // no pointer difference being made here.
932   if (isMaybeZeroSizedType(ElTy))
933     return -2; // dunno.
934
935   // If they are really different, now that they are the same type, then we
936   // found a difference!
937   if (cast<ConstantInt>(C1)->getSExtValue() < 
938       cast<ConstantInt>(C2)->getSExtValue())
939     return -1;
940   else
941     return 1;
942 }
943
944 /// evaluateFCmpRelation - This function determines if there is anything we can
945 /// decide about the two constants provided.  This doesn't need to handle simple
946 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
947 /// If we can determine that the two constants have a particular relation to 
948 /// each other, we should return the corresponding FCmpInst predicate, 
949 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
950 /// ConstantFoldCompareInstruction.
951 ///
952 /// To simplify this code we canonicalize the relation so that the first
953 /// operand is always the most "complex" of the two.  We consider ConstantFP
954 /// to be the simplest, and ConstantExprs to be the most complex.
955 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1, 
956                                                 const Constant *V2) {
957   assert(V1->getType() == V2->getType() &&
958          "Cannot compare values of different types!");
959
960   // No compile-time operations on this type yet.
961   if (V1->getType() == Type::PPC_FP128Ty)
962     return FCmpInst::BAD_FCMP_PREDICATE;
963
964   // Handle degenerate case quickly
965   if (V1 == V2) return FCmpInst::FCMP_OEQ;
966
967   if (!isa<ConstantExpr>(V1)) {
968     if (!isa<ConstantExpr>(V2)) {
969       // We distilled thisUse the standard constant folder for a few cases
970       ConstantInt *R = 0;
971       Constant *C1 = const_cast<Constant*>(V1);
972       Constant *C2 = const_cast<Constant*>(V2);
973       R = dyn_cast<ConstantInt>(
974                              ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
975       if (R && !R->isZero()) 
976         return FCmpInst::FCMP_OEQ;
977       R = dyn_cast<ConstantInt>(
978                              ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
979       if (R && !R->isZero()) 
980         return FCmpInst::FCMP_OLT;
981       R = dyn_cast<ConstantInt>(
982                              ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
983       if (R && !R->isZero()) 
984         return FCmpInst::FCMP_OGT;
985
986       // Nothing more we can do
987       return FCmpInst::BAD_FCMP_PREDICATE;
988     }
989     
990     // If the first operand is simple and second is ConstantExpr, swap operands.
991     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
992     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
993       return FCmpInst::getSwappedPredicate(SwappedRelation);
994   } else {
995     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
996     // constantexpr or a simple constant.
997     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
998     switch (CE1->getOpcode()) {
999     case Instruction::FPTrunc:
1000     case Instruction::FPExt:
1001     case Instruction::UIToFP:
1002     case Instruction::SIToFP:
1003       // We might be able to do something with these but we don't right now.
1004       break;
1005     default:
1006       break;
1007     }
1008   }
1009   // There are MANY other foldings that we could perform here.  They will
1010   // probably be added on demand, as they seem needed.
1011   return FCmpInst::BAD_FCMP_PREDICATE;
1012 }
1013
1014 /// evaluateICmpRelation - This function determines if there is anything we can
1015 /// decide about the two constants provided.  This doesn't need to handle simple
1016 /// things like integer comparisons, but should instead handle ConstantExprs
1017 /// and GlobalValues.  If we can determine that the two constants have a
1018 /// particular relation to each other, we should return the corresponding ICmp
1019 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1020 ///
1021 /// To simplify this code we canonicalize the relation so that the first
1022 /// operand is always the most "complex" of the two.  We consider simple
1023 /// constants (like ConstantInt) to be the simplest, followed by
1024 /// GlobalValues, followed by ConstantExpr's (the most complex).
1025 ///
1026 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1, 
1027                                                 const Constant *V2,
1028                                                 bool isSigned) {
1029   assert(V1->getType() == V2->getType() &&
1030          "Cannot compare different types of values!");
1031   if (V1 == V2) return ICmpInst::ICMP_EQ;
1032
1033   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1034     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1035       // We distilled this down to a simple case, use the standard constant
1036       // folder.
1037       ConstantInt *R = 0;
1038       Constant *C1 = const_cast<Constant*>(V1);
1039       Constant *C2 = const_cast<Constant*>(V2);
1040       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1041       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1042       if (R && !R->isZero()) 
1043         return pred;
1044       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1045       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1046       if (R && !R->isZero())
1047         return pred;
1048       pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1049       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1050       if (R && !R->isZero())
1051         return pred;
1052       
1053       // If we couldn't figure it out, bail.
1054       return ICmpInst::BAD_ICMP_PREDICATE;
1055     }
1056     
1057     // If the first operand is simple, swap operands.
1058     ICmpInst::Predicate SwappedRelation = 
1059       evaluateICmpRelation(V2, V1, isSigned);
1060     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1061       return ICmpInst::getSwappedPredicate(SwappedRelation);
1062
1063   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1064     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1065       ICmpInst::Predicate SwappedRelation = 
1066         evaluateICmpRelation(V2, V1, isSigned);
1067       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1068         return ICmpInst::getSwappedPredicate(SwappedRelation);
1069       else
1070         return ICmpInst::BAD_ICMP_PREDICATE;
1071     }
1072
1073     // Now we know that the RHS is a GlobalValue or simple constant,
1074     // which (since the types must match) means that it's a ConstantPointerNull.
1075     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1076       // Don't try to decide equality of aliases.
1077       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1078         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1079           return ICmpInst::ICMP_NE;
1080     } else {
1081       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1082       // GlobalVals can never be null.  Don't try to evaluate aliases.
1083       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
1084         return ICmpInst::ICMP_NE;
1085     }
1086   } else {
1087     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1088     // constantexpr, a CPR, or a simple constant.
1089     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1090     const Constant *CE1Op0 = CE1->getOperand(0);
1091
1092     switch (CE1->getOpcode()) {
1093     case Instruction::Trunc:
1094     case Instruction::FPTrunc:
1095     case Instruction::FPExt:
1096     case Instruction::FPToUI:
1097     case Instruction::FPToSI:
1098       break; // We can't evaluate floating point casts or truncations.
1099
1100     case Instruction::UIToFP:
1101     case Instruction::SIToFP:
1102     case Instruction::BitCast:
1103     case Instruction::ZExt:
1104     case Instruction::SExt:
1105       // If the cast is not actually changing bits, and the second operand is a
1106       // null pointer, do the comparison with the pre-casted value.
1107       if (V2->isNullValue() &&
1108           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1109         bool sgnd = isSigned;
1110         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1111         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1112         return evaluateICmpRelation(CE1Op0,
1113                                     Constant::getNullValue(CE1Op0->getType()), 
1114                                     sgnd);
1115       }
1116
1117       // If the dest type is a pointer type, and the RHS is a constantexpr cast
1118       // from the same type as the src of the LHS, evaluate the inputs.  This is
1119       // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
1120       // which happens a lot in compilers with tagged integers.
1121       if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1122         if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
1123             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1124             CE1->getOperand(0)->getType()->isInteger()) {
1125           bool sgnd = isSigned;
1126           if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1127           if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1128           return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1129                                       sgnd);
1130         }
1131       break;
1132
1133     case Instruction::GetElementPtr:
1134       // Ok, since this is a getelementptr, we know that the constant has a
1135       // pointer type.  Check the various cases.
1136       if (isa<ConstantPointerNull>(V2)) {
1137         // If we are comparing a GEP to a null pointer, check to see if the base
1138         // of the GEP equals the null pointer.
1139         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1140           if (GV->hasExternalWeakLinkage())
1141             // Weak linkage GVals could be zero or not. We're comparing that
1142             // to null pointer so its greater-or-equal
1143             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1144           else 
1145             // If its not weak linkage, the GVal must have a non-zero address
1146             // so the result is greater-than
1147             return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
1148         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1149           // If we are indexing from a null pointer, check to see if we have any
1150           // non-zero indices.
1151           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1152             if (!CE1->getOperand(i)->isNullValue())
1153               // Offsetting from null, must not be equal.
1154               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1155           // Only zero indexes from null, must still be zero.
1156           return ICmpInst::ICMP_EQ;
1157         }
1158         // Otherwise, we can't really say if the first operand is null or not.
1159       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1160         if (isa<ConstantPointerNull>(CE1Op0)) {
1161           if (CPR2->hasExternalWeakLinkage())
1162             // Weak linkage GVals could be zero or not. We're comparing it to
1163             // a null pointer, so its less-or-equal
1164             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1165           else
1166             // If its not weak linkage, the GVal must have a non-zero address
1167             // so the result is less-than
1168             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1169         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1170           if (CPR1 == CPR2) {
1171             // If this is a getelementptr of the same global, then it must be
1172             // different.  Because the types must match, the getelementptr could
1173             // only have at most one index, and because we fold getelementptr's
1174             // with a single zero index, it must be nonzero.
1175             assert(CE1->getNumOperands() == 2 &&
1176                    !CE1->getOperand(1)->isNullValue() &&
1177                    "Suprising getelementptr!");
1178             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1179           } else {
1180             // If they are different globals, we don't know what the value is,
1181             // but they can't be equal.
1182             return ICmpInst::ICMP_NE;
1183           }
1184         }
1185       } else {
1186         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1187         const Constant *CE2Op0 = CE2->getOperand(0);
1188
1189         // There are MANY other foldings that we could perform here.  They will
1190         // probably be added on demand, as they seem needed.
1191         switch (CE2->getOpcode()) {
1192         default: break;
1193         case Instruction::GetElementPtr:
1194           // By far the most common case to handle is when the base pointers are
1195           // obviously to the same or different globals.
1196           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1197             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1198               return ICmpInst::ICMP_NE;
1199             // Ok, we know that both getelementptr instructions are based on the
1200             // same global.  From this, we can precisely determine the relative
1201             // ordering of the resultant pointers.
1202             unsigned i = 1;
1203
1204             // Compare all of the operands the GEP's have in common.
1205             gep_type_iterator GTI = gep_type_begin(CE1);
1206             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1207                  ++i, ++GTI)
1208               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1209                                  GTI.getIndexedType())) {
1210               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1211               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1212               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1213               }
1214
1215             // Ok, we ran out of things they have in common.  If any leftovers
1216             // are non-zero then we have a difference, otherwise we are equal.
1217             for (; i < CE1->getNumOperands(); ++i)
1218               if (!CE1->getOperand(i)->isNullValue()) {
1219                 if (isa<ConstantInt>(CE1->getOperand(i)))
1220                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1221                 else
1222                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1223               }
1224
1225             for (; i < CE2->getNumOperands(); ++i)
1226               if (!CE2->getOperand(i)->isNullValue()) {
1227                 if (isa<ConstantInt>(CE2->getOperand(i)))
1228                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1229                 else
1230                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1231               }
1232             return ICmpInst::ICMP_EQ;
1233           }
1234         }
1235       }
1236     default:
1237       break;
1238     }
1239   }
1240
1241   return ICmpInst::BAD_ICMP_PREDICATE;
1242 }
1243
1244 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1245                                                const Constant *C1, 
1246                                                const Constant *C2) {
1247   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1248   if (pred == FCmpInst::FCMP_FALSE) {
1249     if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1250       return Constant::getNullValue(VectorType::getInteger(VT));
1251     else
1252       return ConstantInt::getFalse();
1253   }
1254   
1255   if (pred == FCmpInst::FCMP_TRUE) {
1256     if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1257       return Constant::getAllOnesValue(VectorType::getInteger(VT));
1258     else
1259       return ConstantInt::getTrue();
1260   }
1261       
1262   // Handle some degenerate cases first
1263   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1264     // vicmp/vfcmp -> [vector] undef
1265     if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType()))
1266       return UndefValue::get(VectorType::getInteger(VTy));
1267     
1268     // icmp/fcmp -> i1 undef
1269     return UndefValue::get(Type::Int1Ty);
1270   }
1271
1272   // No compile-time operations on this type yet.
1273   if (C1->getType() == Type::PPC_FP128Ty)
1274     return 0;
1275
1276   // icmp eq/ne(null,GV) -> false/true
1277   if (C1->isNullValue()) {
1278     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1279       // Don't try to evaluate aliases.  External weak GV can be null.
1280       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1281         if (pred == ICmpInst::ICMP_EQ)
1282           return ConstantInt::getFalse();
1283         else if (pred == ICmpInst::ICMP_NE)
1284           return ConstantInt::getTrue();
1285       }
1286   // icmp eq/ne(GV,null) -> false/true
1287   } else if (C2->isNullValue()) {
1288     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1289       // Don't try to evaluate aliases.  External weak GV can be null.
1290       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1291         if (pred == ICmpInst::ICMP_EQ)
1292           return ConstantInt::getFalse();
1293         else if (pred == ICmpInst::ICMP_NE)
1294           return ConstantInt::getTrue();
1295       }
1296   }
1297
1298   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1299     APInt V1 = cast<ConstantInt>(C1)->getValue();
1300     APInt V2 = cast<ConstantInt>(C2)->getValue();
1301     switch (pred) {
1302     default: assert(0 && "Invalid ICmp Predicate"); return 0;
1303     case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1304     case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1305     case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1306     case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1307     case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1308     case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1309     case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1310     case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1311     case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1312     case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1313     }
1314   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1315     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1316     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1317     APFloat::cmpResult R = C1V.compare(C2V);
1318     switch (pred) {
1319     default: assert(0 && "Invalid FCmp Predicate"); return 0;
1320     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1321     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1322     case FCmpInst::FCMP_UNO:
1323       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1324     case FCmpInst::FCMP_ORD:
1325       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1326     case FCmpInst::FCMP_UEQ:
1327       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1328                                             R==APFloat::cmpEqual);
1329     case FCmpInst::FCMP_OEQ:   
1330       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1331     case FCmpInst::FCMP_UNE:
1332       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1333     case FCmpInst::FCMP_ONE:   
1334       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1335                                             R==APFloat::cmpGreaterThan);
1336     case FCmpInst::FCMP_ULT: 
1337       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1338                                             R==APFloat::cmpLessThan);
1339     case FCmpInst::FCMP_OLT:   
1340       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1341     case FCmpInst::FCMP_UGT:
1342       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1343                                             R==APFloat::cmpGreaterThan);
1344     case FCmpInst::FCMP_OGT:
1345       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1346     case FCmpInst::FCMP_ULE:
1347       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1348     case FCmpInst::FCMP_OLE: 
1349       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1350                                             R==APFloat::cmpEqual);
1351     case FCmpInst::FCMP_UGE:
1352       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1353     case FCmpInst::FCMP_OGE: 
1354       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1355                                             R==APFloat::cmpEqual);
1356     }
1357   } else if (isa<VectorType>(C1->getType())) {
1358     SmallVector<Constant*, 16> C1Elts, C2Elts;
1359     C1->getVectorElements(C1Elts);
1360     C2->getVectorElements(C2Elts);
1361     
1362     // If we can constant fold the comparison of each element, constant fold
1363     // the whole vector comparison.
1364     SmallVector<Constant*, 4> ResElts;
1365     const Type *InEltTy = C1Elts[0]->getType();
1366     bool isFP = InEltTy->isFloatingPoint();
1367     const Type *ResEltTy = InEltTy;
1368     if (isFP)
1369       ResEltTy = IntegerType::get(InEltTy->getPrimitiveSizeInBits());
1370     
1371     for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1372       // Compare the elements, producing an i1 result or constant expr.
1373       Constant *C;
1374       if (isFP)
1375         C = ConstantExpr::getFCmp(pred, C1Elts[i], C2Elts[i]);
1376       else
1377         C = ConstantExpr::getICmp(pred, C1Elts[i], C2Elts[i]);
1378
1379       // If it is a bool or undef result, convert to the dest type.
1380       if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1381         if (CI->isZero())
1382           ResElts.push_back(Constant::getNullValue(ResEltTy));
1383         else
1384           ResElts.push_back(Constant::getAllOnesValue(ResEltTy));
1385       } else if (isa<UndefValue>(C)) {
1386         ResElts.push_back(UndefValue::get(ResEltTy));
1387       } else {
1388         break;
1389       }
1390     }
1391     
1392     if (ResElts.size() == C1Elts.size())
1393       return ConstantVector::get(&ResElts[0], ResElts.size());
1394   }
1395
1396   if (C1->getType()->isFloatingPoint()) {
1397     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1398     switch (evaluateFCmpRelation(C1, C2)) {
1399     default: assert(0 && "Unknown relation!");
1400     case FCmpInst::FCMP_UNO:
1401     case FCmpInst::FCMP_ORD:
1402     case FCmpInst::FCMP_UEQ:
1403     case FCmpInst::FCMP_UNE:
1404     case FCmpInst::FCMP_ULT:
1405     case FCmpInst::FCMP_UGT:
1406     case FCmpInst::FCMP_ULE:
1407     case FCmpInst::FCMP_UGE:
1408     case FCmpInst::FCMP_TRUE:
1409     case FCmpInst::FCMP_FALSE:
1410     case FCmpInst::BAD_FCMP_PREDICATE:
1411       break; // Couldn't determine anything about these constants.
1412     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1413       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1414                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1415                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1416       break;
1417     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1418       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1419                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1420                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1421       break;
1422     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1423       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1424                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1425                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1426       break;
1427     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1428       // We can only partially decide this relation.
1429       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1430         Result = 0;
1431       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1432         Result = 1;
1433       break;
1434     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1435       // We can only partially decide this relation.
1436       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1437         Result = 0;
1438       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1439         Result = 1;
1440       break;
1441     case ICmpInst::ICMP_NE: // We know that C1 != C2
1442       // We can only partially decide this relation.
1443       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1444         Result = 0;
1445       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1446         Result = 1;
1447       break;
1448     }
1449     
1450     // If we evaluated the result, return it now.
1451     if (Result != -1) {
1452       if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
1453         if (Result == 0)
1454           return Constant::getNullValue(VectorType::getInteger(VT));
1455         else
1456           return Constant::getAllOnesValue(VectorType::getInteger(VT));
1457       }
1458       return ConstantInt::get(Type::Int1Ty, Result);
1459     }
1460     
1461   } else {
1462     // Evaluate the relation between the two constants, per the predicate.
1463     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1464     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1465     default: assert(0 && "Unknown relational!");
1466     case ICmpInst::BAD_ICMP_PREDICATE:
1467       break;  // Couldn't determine anything about these constants.
1468     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1469       // If we know the constants are equal, we can decide the result of this
1470       // computation precisely.
1471       Result = (pred == ICmpInst::ICMP_EQ  ||
1472                 pred == ICmpInst::ICMP_ULE ||
1473                 pred == ICmpInst::ICMP_SLE ||
1474                 pred == ICmpInst::ICMP_UGE ||
1475                 pred == ICmpInst::ICMP_SGE);
1476       break;
1477     case ICmpInst::ICMP_ULT:
1478       // If we know that C1 < C2, we can decide the result of this computation
1479       // precisely.
1480       Result = (pred == ICmpInst::ICMP_ULT ||
1481                 pred == ICmpInst::ICMP_NE  ||
1482                 pred == ICmpInst::ICMP_ULE);
1483       break;
1484     case ICmpInst::ICMP_SLT:
1485       // If we know that C1 < C2, we can decide the result of this computation
1486       // precisely.
1487       Result = (pred == ICmpInst::ICMP_SLT ||
1488                 pred == ICmpInst::ICMP_NE  ||
1489                 pred == ICmpInst::ICMP_SLE);
1490       break;
1491     case ICmpInst::ICMP_UGT:
1492       // If we know that C1 > C2, we can decide the result of this computation
1493       // precisely.
1494       Result = (pred == ICmpInst::ICMP_UGT ||
1495                 pred == ICmpInst::ICMP_NE  ||
1496                 pred == ICmpInst::ICMP_UGE);
1497       break;
1498     case ICmpInst::ICMP_SGT:
1499       // If we know that C1 > C2, we can decide the result of this computation
1500       // precisely.
1501       Result = (pred == ICmpInst::ICMP_SGT ||
1502                 pred == ICmpInst::ICMP_NE  ||
1503                 pred == ICmpInst::ICMP_SGE);
1504       break;
1505     case ICmpInst::ICMP_ULE:
1506       // If we know that C1 <= C2, we can only partially decide this relation.
1507       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1508       if (pred == ICmpInst::ICMP_ULT) Result = 1;
1509       break;
1510     case ICmpInst::ICMP_SLE:
1511       // If we know that C1 <= C2, we can only partially decide this relation.
1512       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1513       if (pred == ICmpInst::ICMP_SLT) Result = 1;
1514       break;
1515
1516     case ICmpInst::ICMP_UGE:
1517       // If we know that C1 >= C2, we can only partially decide this relation.
1518       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1519       if (pred == ICmpInst::ICMP_UGT) Result = 1;
1520       break;
1521     case ICmpInst::ICMP_SGE:
1522       // If we know that C1 >= C2, we can only partially decide this relation.
1523       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1524       if (pred == ICmpInst::ICMP_SGT) Result = 1;
1525       break;
1526
1527     case ICmpInst::ICMP_NE:
1528       // If we know that C1 != C2, we can only partially decide this relation.
1529       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1530       if (pred == ICmpInst::ICMP_NE) Result = 1;
1531       break;
1532     }
1533     
1534     // If we evaluated the result, return it now.
1535     if (Result != -1) {
1536       if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
1537         if (Result == 0)
1538           return Constant::getNullValue(VT);
1539         else
1540           return Constant::getAllOnesValue(VT);
1541       }
1542       return ConstantInt::get(Type::Int1Ty, Result);
1543     }
1544     
1545     if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1546       // If C2 is a constant expr and C1 isn't, flop them around and fold the
1547       // other way if possible.
1548       switch (pred) {
1549       case ICmpInst::ICMP_EQ:
1550       case ICmpInst::ICMP_NE:
1551         // No change of predicate required.
1552         return ConstantFoldCompareInstruction(pred, C2, C1);
1553
1554       case ICmpInst::ICMP_ULT:
1555       case ICmpInst::ICMP_SLT:
1556       case ICmpInst::ICMP_UGT:
1557       case ICmpInst::ICMP_SGT:
1558       case ICmpInst::ICMP_ULE:
1559       case ICmpInst::ICMP_SLE:
1560       case ICmpInst::ICMP_UGE:
1561       case ICmpInst::ICMP_SGE:
1562         // Change the predicate as necessary to swap the operands.
1563         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1564         return ConstantFoldCompareInstruction(pred, C2, C1);
1565
1566       default:  // These predicates cannot be flopped around.
1567         break;
1568       }
1569     }
1570   }
1571   return 0;
1572 }
1573
1574 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1575                                           Constant* const *Idxs,
1576                                           unsigned NumIdx) {
1577   if (NumIdx == 0 ||
1578       (NumIdx == 1 && Idxs[0]->isNullValue()))
1579     return const_cast<Constant*>(C);
1580
1581   if (isa<UndefValue>(C)) {
1582     const PointerType *Ptr = cast<PointerType>(C->getType());
1583     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1584                                                        (Value **)Idxs,
1585                                                        (Value **)Idxs+NumIdx);
1586     assert(Ty != 0 && "Invalid indices for GEP!");
1587     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1588   }
1589
1590   Constant *Idx0 = Idxs[0];
1591   if (C->isNullValue()) {
1592     bool isNull = true;
1593     for (unsigned i = 0, e = NumIdx; i != e; ++i)
1594       if (!Idxs[i]->isNullValue()) {
1595         isNull = false;
1596         break;
1597       }
1598     if (isNull) {
1599       const PointerType *Ptr = cast<PointerType>(C->getType());
1600       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1601                                                          (Value**)Idxs,
1602                                                          (Value**)Idxs+NumIdx);
1603       assert(Ty != 0 && "Invalid indices for GEP!");
1604       return 
1605         ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1606     }
1607   }
1608
1609   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1610     // Combine Indices - If the source pointer to this getelementptr instruction
1611     // is a getelementptr instruction, combine the indices of the two
1612     // getelementptr instructions into a single instruction.
1613     //
1614     if (CE->getOpcode() == Instruction::GetElementPtr) {
1615       const Type *LastTy = 0;
1616       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1617            I != E; ++I)
1618         LastTy = *I;
1619
1620       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1621         SmallVector<Value*, 16> NewIndices;
1622         NewIndices.reserve(NumIdx + CE->getNumOperands());
1623         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1624           NewIndices.push_back(CE->getOperand(i));
1625
1626         // Add the last index of the source with the first index of the new GEP.
1627         // Make sure to handle the case when they are actually different types.
1628         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1629         // Otherwise it must be an array.
1630         if (!Idx0->isNullValue()) {
1631           const Type *IdxTy = Combined->getType();
1632           if (IdxTy != Idx0->getType()) {
1633             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1634             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
1635                                                           Type::Int64Ty);
1636             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1637           } else {
1638             Combined =
1639               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1640           }
1641         }
1642
1643         NewIndices.push_back(Combined);
1644         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1645         return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1646                                               NewIndices.size());
1647       }
1648     }
1649
1650     // Implement folding of:
1651     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1652     //                        long 0, long 0)
1653     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1654     //
1655     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1656       if (const PointerType *SPT =
1657           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1658         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1659           if (const ArrayType *CAT =
1660         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1661             if (CAT->getElementType() == SAT->getElementType())
1662               return ConstantExpr::getGetElementPtr(
1663                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
1664     }
1665     
1666     // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1667     // Into: inttoptr (i64 0 to i8*)
1668     // This happens with pointers to member functions in C++.
1669     if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1670         isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1671         cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1672       Constant *Base = CE->getOperand(0);
1673       Constant *Offset = Idxs[0];
1674       
1675       // Convert the smaller integer to the larger type.
1676       if (Offset->getType()->getPrimitiveSizeInBits() < 
1677           Base->getType()->getPrimitiveSizeInBits())
1678         Offset = ConstantExpr::getSExt(Offset, Base->getType());
1679       else if (Base->getType()->getPrimitiveSizeInBits() <
1680                Offset->getType()->getPrimitiveSizeInBits())
1681         Base = ConstantExpr::getZExt(Base, Base->getType());
1682       
1683       Base = ConstantExpr::getAdd(Base, Offset);
1684       return ConstantExpr::getIntToPtr(Base, CE->getType());
1685     }
1686   }
1687   return 0;
1688 }
1689