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