IntegerValType holds a uint32_t, so its constructor should take a uint32_t. This...
[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 // pieces that don't need TargetData, and the pieces that do. This is to avoid
16 // a dependence in VMCore on Target.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "ConstantFold.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MathExtras.h"
33 #include <limits>
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 //                ConstantFold*Instruction Implementations
38 //===----------------------------------------------------------------------===//
39
40 /// BitCastConstantVector - Convert the specified ConstantVector node to the
41 /// specified vector type.  At this point, we know that the elements of the
42 /// input vector constant are all simple integer or FP values.
43 static Constant *BitCastConstantVector(ConstantVector *CV,
44                                        const VectorType *DstTy) {
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),
64                                                     DstEltTy));
65   return ConstantVector::get(Result);
66 }
67
68 /// This function determines which opcode to use to fold two constant cast 
69 /// expressions together. It uses CastInst::isEliminableCastPair to determine
70 /// the opcode. Consequently its just a wrapper around that function.
71 /// @brief Determine if it is valid to fold a cast of a cast
72 static unsigned
73 foldConstantCastPair(
74   unsigned opc,          ///< opcode of the second cast constant expression
75   ConstantExpr *Op,      ///< the first cast constant expression
76   const Type *DstTy      ///< desintation type of the first cast
77 ) {
78   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
79   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
80   assert(CastInst::isCast(opc) && "Invalid cast opcode");
81
82   // The the types and opcodes for the two Cast constant expressions
83   const Type *SrcTy = Op->getOperand(0)->getType();
84   const Type *MidTy = Op->getType();
85   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
86   Instruction::CastOps secondOp = Instruction::CastOps(opc);
87
88   // Let CastInst::isEliminableCastPair do the heavy lifting.
89   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
90                                         Type::getInt64Ty(DstTy->getContext()));
91 }
92
93 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
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         Value *Zero =
105           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
106         IdxList.push_back(Zero);
107         const Type *ElTy = PTy->getElementType();
108         while (ElTy != DPTy->getElementType()) {
109           if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
110             if (STy->getNumElements() == 0) break;
111             ElTy = STy->getElementType(0);
112             IdxList.push_back(Zero);
113           } else if (const SequentialType *STy = 
114                      dyn_cast<SequentialType>(ElTy)) {
115             if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
116             ElTy = STy->getElementType();
117             IdxList.push_back(Zero);
118           } else {
119             break;
120           }
121         }
122
123         if (ElTy == DPTy->getElementType())
124           // This GEP is inbounds because all indices are zero.
125           return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
126                                                         IdxList.size());
127       }
128
129   // Handle casts from one vector constant to another.  We know that the src 
130   // and dest type have the same size (otherwise its an illegal cast).
131   if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
132     if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
133       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
134              "Not cast between same sized vectors!");
135       SrcTy = NULL;
136       // First, check for null.  Undef is already handled.
137       if (isa<ConstantAggregateZero>(V))
138         return Constant::getNullValue(DestTy);
139
140       if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
141         return BitCastConstantVector(CV, DestPTy);
142     }
143
144     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
145     // This allows for other simplifications (although some of them
146     // can only be handled by Analysis/ConstantFolding.cpp).
147     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
148       return ConstantExpr::getBitCast(ConstantVector::get(&V, 1), DestPTy);
149   }
150
151   // Finally, implement bitcast folding now.   The code below doesn't handle
152   // bitcast right.
153   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
154     return ConstantPointerNull::get(cast<PointerType>(DestTy));
155
156   // Handle integral constant input.
157   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
158     if (DestTy->isInteger())
159       // Integral -> Integral. This is a no-op because the bit widths must
160       // be the same. Consequently, we just fold to V.
161       return V;
162
163     if (DestTy->isFloatingPoint())
164       return ConstantFP::get(DestTy->getContext(),
165                              APFloat(CI->getValue(),
166                                      !DestTy->isPPC_FP128Ty()));
167
168     // Otherwise, can't fold this (vector?)
169     return 0;
170   }
171
172   // Handle ConstantFP input: FP -> Integral.
173   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
174     return ConstantInt::get(FP->getContext(),
175                             FP->getValueAPF().bitcastToAPInt());
176
177   return 0;
178 }
179
180
181 /// ExtractConstantBytes - V is an integer constant which only has a subset of
182 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
183 /// first byte used, counting from the least significant byte) and ByteSize,
184 /// which is the number of bytes used.
185 ///
186 /// This function analyzes the specified constant to see if the specified byte
187 /// range can be returned as a simplified constant.  If so, the constant is
188 /// returned, otherwise null is returned.
189 /// 
190 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
191                                       unsigned ByteSize) {
192   assert(isa<IntegerType>(C->getType()) &&
193          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
194          "Non-byte sized integer input");
195   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
196   assert(ByteSize && "Must be accessing some piece");
197   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
198   assert(ByteSize != CSize && "Should not extract everything");
199   
200   // Constant Integers are simple.
201   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
202     APInt V = CI->getValue();
203     if (ByteStart)
204       V = V.lshr(ByteStart*8);
205     V.trunc(ByteSize*8);
206     return ConstantInt::get(CI->getContext(), V);
207   }
208   
209   // In the input is a constant expr, we might be able to recursively simplify.
210   // If not, we definitely can't do anything.
211   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
212   if (CE == 0) return 0;
213   
214   switch (CE->getOpcode()) {
215   default: return 0;
216   case Instruction::Or: {
217     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
218     if (RHS == 0)
219       return 0;
220     
221     // X | -1 -> -1.
222     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
223       if (RHSC->isAllOnesValue())
224         return RHSC;
225     
226     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
227     if (LHS == 0)
228       return 0;
229     return ConstantExpr::getOr(LHS, RHS);
230   }
231   case Instruction::And: {
232     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
233     if (RHS == 0)
234       return 0;
235     
236     // X & 0 -> 0.
237     if (RHS->isNullValue())
238       return RHS;
239     
240     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
241     if (LHS == 0)
242       return 0;
243     return ConstantExpr::getAnd(LHS, RHS);
244   }
245   case Instruction::LShr: {
246     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
247     if (Amt == 0)
248       return 0;
249     unsigned ShAmt = Amt->getZExtValue();
250     // Cannot analyze non-byte shifts.
251     if ((ShAmt & 7) != 0)
252       return 0;
253     ShAmt >>= 3;
254     
255     // If the extract is known to be all zeros, return zero.
256     if (ByteStart >= CSize-ShAmt)
257       return Constant::getNullValue(IntegerType::get(CE->getContext(),
258                                                      ByteSize*8));
259     // If the extract is known to be fully in the input, extract it.
260     if (ByteStart+ByteSize+ShAmt <= CSize)
261       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
262     
263     // TODO: Handle the 'partially zero' case.
264     return 0;
265   }
266     
267   case Instruction::Shl: {
268     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
269     if (Amt == 0)
270       return 0;
271     unsigned ShAmt = Amt->getZExtValue();
272     // Cannot analyze non-byte shifts.
273     if ((ShAmt & 7) != 0)
274       return 0;
275     ShAmt >>= 3;
276     
277     // If the extract is known to be all zeros, return zero.
278     if (ByteStart+ByteSize <= ShAmt)
279       return Constant::getNullValue(IntegerType::get(CE->getContext(),
280                                                      ByteSize*8));
281     // If the extract is known to be fully in the input, extract it.
282     if (ByteStart >= ShAmt)
283       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
284     
285     // TODO: Handle the 'partially zero' case.
286     return 0;
287   }
288       
289   case Instruction::ZExt: {
290     unsigned SrcBitSize =
291       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
292     
293     // If extracting something that is completely zero, return 0.
294     if (ByteStart*8 >= SrcBitSize)
295       return Constant::getNullValue(IntegerType::get(CE->getContext(),
296                                                      ByteSize*8));
297
298     // If exactly extracting the input, return it.
299     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
300       return CE->getOperand(0);
301     
302     // If extracting something completely in the input, if if the input is a
303     // multiple of 8 bits, recurse.
304     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
305       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
306       
307     // Otherwise, if extracting a subset of the input, which is not multiple of
308     // 8 bits, do a shift and trunc to get the bits.
309     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
310       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
311       Constant *Res = CE->getOperand(0);
312       if (ByteStart)
313         Res = ConstantExpr::getLShr(Res, 
314                                  ConstantInt::get(Res->getType(), ByteStart*8));
315       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
316                                                           ByteSize*8));
317     }
318     
319     // TODO: Handle the 'partially zero' case.
320     return 0;
321   }
322   }
323 }
324
325 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
326 /// on Ty, with any known factors factored out. If Folded is false,
327 /// return null if no factoring was possible, to avoid endlessly
328 /// bouncing an unfoldable expression back into the top-level folder.
329 ///
330 static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
331                                  bool Folded) {
332   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
333     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
334     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
335     return ConstantExpr::getNUWMul(E, N);
336   }
337   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
338     Constant *N = ConstantInt::get(DestTy, VTy->getNumElements());
339     Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
340     return ConstantExpr::getNUWMul(E, N);
341   }
342   if (const StructType *STy = dyn_cast<StructType>(Ty))
343     if (!STy->isPacked()) {
344       unsigned NumElems = STy->getNumElements();
345       // An empty struct has size zero.
346       if (NumElems == 0)
347         return ConstantExpr::getNullValue(DestTy);
348       // Check for a struct with all members having the same size.
349       Constant *MemberSize =
350         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
351       bool AllSame = true;
352       for (unsigned i = 1; i != NumElems; ++i)
353         if (MemberSize !=
354             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
355           AllSame = false;
356           break;
357         }
358       if (AllSame) {
359         Constant *N = ConstantInt::get(DestTy, NumElems);
360         return ConstantExpr::getNUWMul(MemberSize, N);
361       }
362     }
363
364   // If there's no interesting folding happening, bail so that we don't create
365   // a constant that looks like it needs folding but really doesn't.
366   if (!Folded)
367     return 0;
368
369   // Base case: Get a regular sizeof expression.
370   Constant *C = ConstantExpr::getSizeOf(Ty);
371   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
372                                                     DestTy, false),
373                             C, DestTy);
374   return C;
375 }
376
377 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
378 /// on Ty, with any known factors factored out. If Folded is false,
379 /// return null if no factoring was possible, to avoid endlessly
380 /// bouncing an unfoldable expression back into the top-level folder.
381 ///
382 static Constant *getFoldedAlignOf(const Type *Ty, const Type *DestTy,
383                                   bool Folded) {
384   // The alignment of an array is equal to the alignment of the
385   // array element. Note that this is not always true for vectors.
386   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
387     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
388     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
389                                                       DestTy,
390                                                       false),
391                               C, DestTy);
392     return C;
393   }
394
395   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
396     // Packed structs always have an alignment of 1.
397     if (STy->isPacked())
398       return ConstantInt::get(DestTy, 1);
399
400     // Otherwise, struct alignment is the maximum alignment of any member.
401     // Without target data, we can't compare much, but we can check to see
402     // if all the members have the same alignment.
403     unsigned NumElems = STy->getNumElements();
404     // An empty struct has minimal alignment.
405     if (NumElems == 0)
406       return ConstantInt::get(DestTy, 1);
407     // Check for a struct with all members having the same alignment.
408     Constant *MemberAlign =
409       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
410     bool AllSame = true;
411     for (unsigned i = 1; i != NumElems; ++i)
412       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
413         AllSame = false;
414         break;
415       }
416     if (AllSame)
417       return MemberAlign;
418   }
419
420   // If there's no interesting folding happening, bail so that we don't create
421   // a constant that looks like it needs folding but really doesn't.
422   if (!Folded)
423     return 0;
424
425   // Base case: Get a regular alignof expression.
426   Constant *C = ConstantExpr::getAlignOf(Ty);
427   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
428                                                     DestTy, false),
429                             C, DestTy);
430   return C;
431 }
432
433 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
434 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
435 /// return null if no factoring was possible, to avoid endlessly
436 /// bouncing an unfoldable expression back into the top-level folder.
437 ///
438 static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
439                                    const Type *DestTy,
440                                    bool Folded) {
441   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
442     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
443                                                                 DestTy, false),
444                                         FieldNo, DestTy);
445     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
446     return ConstantExpr::getNUWMul(E, N);
447   }
448   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
449     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
450                                                                 DestTy, false),
451                                         FieldNo, DestTy);
452     Constant *E = getFoldedSizeOf(VTy->getElementType(), DestTy, true);
453     return ConstantExpr::getNUWMul(E, N);
454   }
455   if (const StructType *STy = dyn_cast<StructType>(Ty))
456     if (!STy->isPacked()) {
457       unsigned NumElems = STy->getNumElements();
458       // An empty struct has no members.
459       if (NumElems == 0)
460         return 0;
461       // Check for a struct with all members having the same size.
462       Constant *MemberSize =
463         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
464       bool AllSame = true;
465       for (unsigned i = 1; i != NumElems; ++i)
466         if (MemberSize !=
467             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
468           AllSame = false;
469           break;
470         }
471       if (AllSame) {
472         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
473                                                                     false,
474                                                                     DestTy,
475                                                                     false),
476                                             FieldNo, DestTy);
477         return ConstantExpr::getNUWMul(MemberSize, N);
478       }
479     }
480
481   // If there's no interesting folding happening, bail so that we don't create
482   // a constant that looks like it needs folding but really doesn't.
483   if (!Folded)
484     return 0;
485
486   // Base case: Get a regular offsetof expression.
487   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
488   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
489                                                     DestTy, false),
490                             C, DestTy);
491   return C;
492 }
493
494 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
495                                             const Type *DestTy) {
496   if (isa<UndefValue>(V)) {
497     // zext(undef) = 0, because the top bits will be zero.
498     // sext(undef) = 0, because the top bits will all be the same.
499     // [us]itofp(undef) = 0, because the result value is bounded.
500     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
501         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
502       return Constant::getNullValue(DestTy);
503     return UndefValue::get(DestTy);
504   }
505   // No compile-time operations on this type yet.
506   if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
507     return 0;
508
509   // If the cast operand is a constant expression, there's a few things we can
510   // do to try to simplify it.
511   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
512     if (CE->isCast()) {
513       // Try hard to fold cast of cast because they are often eliminable.
514       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
515         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
516     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
517       // If all of the indexes in the GEP are null values, there is no pointer
518       // adjustment going on.  We might as well cast the source pointer.
519       bool isAllNull = true;
520       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
521         if (!CE->getOperand(i)->isNullValue()) {
522           isAllNull = false;
523           break;
524         }
525       if (isAllNull)
526         // This is casting one pointer type to another, always BitCast
527         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
528     }
529   }
530
531   // If the cast operand is a constant vector, perform the cast by
532   // operating on each element. In the cast of bitcasts, the element
533   // count may be mismatched; don't attempt to handle that here.
534   if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
535     if (isa<VectorType>(DestTy) &&
536         cast<VectorType>(DestTy)->getNumElements() ==
537         CV->getType()->getNumElements()) {
538       std::vector<Constant*> res;
539       const VectorType *DestVecTy = cast<VectorType>(DestTy);
540       const Type *DstEltTy = DestVecTy->getElementType();
541       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
542         res.push_back(ConstantExpr::getCast(opc,
543                                             CV->getOperand(i), DstEltTy));
544       return ConstantVector::get(DestVecTy, res);
545     }
546
547   // We actually have to do a cast now. Perform the cast according to the
548   // opcode specified.
549   switch (opc) {
550   default:
551     llvm_unreachable("Failed to cast constant expression");
552   case Instruction::FPTrunc:
553   case Instruction::FPExt:
554     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
555       bool ignored;
556       APFloat Val = FPC->getValueAPF();
557       Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
558                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
559                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
560                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
561                   APFloat::Bogus,
562                   APFloat::rmNearestTiesToEven, &ignored);
563       return ConstantFP::get(V->getContext(), Val);
564     }
565     return 0; // Can't fold.
566   case Instruction::FPToUI: 
567   case Instruction::FPToSI:
568     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
569       const APFloat &V = FPC->getValueAPF();
570       bool ignored;
571       uint64_t x[2]; 
572       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
573       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
574                                 APFloat::rmTowardZero, &ignored);
575       APInt Val(DestBitWidth, 2, x);
576       return ConstantInt::get(FPC->getContext(), Val);
577     }
578     return 0; // Can't fold.
579   case Instruction::IntToPtr:   //always treated as unsigned
580     if (V->isNullValue())       // Is it an integral null value?
581       return ConstantPointerNull::get(cast<PointerType>(DestTy));
582     return 0;                   // Other pointer types cannot be casted
583   case Instruction::PtrToInt:   // always treated as unsigned
584     // Is it a null pointer value?
585     if (V->isNullValue())
586       return ConstantInt::get(DestTy, 0);
587     // If this is a sizeof-like expression, pull out multiplications by
588     // known factors to expose them to subsequent folding. If it's an
589     // alignof-like expression, factor out known factors.
590     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
591       if (CE->getOpcode() == Instruction::GetElementPtr &&
592           CE->getOperand(0)->isNullValue()) {
593         const Type *Ty =
594           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
595         if (CE->getNumOperands() == 2) {
596           // Handle a sizeof-like expression.
597           Constant *Idx = CE->getOperand(1);
598           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
599           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
600             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
601                                                                 DestTy, false),
602                                         Idx, DestTy);
603             return ConstantExpr::getMul(C, Idx);
604           }
605         } else if (CE->getNumOperands() == 3 &&
606                    CE->getOperand(1)->isNullValue()) {
607           // Handle an alignof-like expression.
608           if (const StructType *STy = dyn_cast<StructType>(Ty))
609             if (!STy->isPacked()) {
610               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
611               if (CI->isOne() &&
612                   STy->getNumElements() == 2 &&
613                   STy->getElementType(0)->isInteger(1)) {
614                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
615               }
616             }
617           // Handle an offsetof-like expression.
618           if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)){
619             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
620                                                 DestTy, false))
621               return C;
622           }
623         }
624       }
625     // Other pointer types cannot be casted
626     return 0;
627   case Instruction::UIToFP:
628   case Instruction::SIToFP:
629     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
630       APInt api = CI->getValue();
631       const uint64_t zero[] = {0, 0};
632       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
633                                   2, zero));
634       (void)apf.convertFromAPInt(api, 
635                                  opc==Instruction::SIToFP,
636                                  APFloat::rmNearestTiesToEven);
637       return ConstantFP::get(V->getContext(), apf);
638     }
639     return 0;
640   case Instruction::ZExt:
641     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
642       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
643       APInt Result(CI->getValue());
644       Result.zext(BitWidth);
645       return ConstantInt::get(V->getContext(), Result);
646     }
647     return 0;
648   case Instruction::SExt:
649     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
650       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
651       APInt Result(CI->getValue());
652       Result.sext(BitWidth);
653       return ConstantInt::get(V->getContext(), Result);
654     }
655     return 0;
656   case Instruction::Trunc: {
657     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
658     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
659       APInt Result(CI->getValue());
660       Result.trunc(DestBitWidth);
661       return ConstantInt::get(V->getContext(), Result);
662     }
663     
664     // The input must be a constantexpr.  See if we can simplify this based on
665     // the bytes we are demanding.  Only do this if the source and dest are an
666     // even multiple of a byte.
667     if ((DestBitWidth & 7) == 0 &&
668         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
669       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
670         return Res;
671       
672     return 0;
673   }
674   case Instruction::BitCast:
675     return FoldBitCast(V, DestTy);
676   }
677 }
678
679 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
680                                               Constant *V1, Constant *V2) {
681   if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
682     return CB->getZExtValue() ? V1 : V2;
683
684   if (isa<UndefValue>(V1)) return V2;
685   if (isa<UndefValue>(V2)) return V1;
686   if (isa<UndefValue>(Cond)) return V1;
687   if (V1 == V2) return V1;
688   return 0;
689 }
690
691 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
692                                                       Constant *Idx) {
693   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
694     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
695   if (Val->isNullValue())  // ee(zero, x) -> zero
696     return Constant::getNullValue(
697                           cast<VectorType>(Val->getType())->getElementType());
698
699   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
700     if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
701       return CVal->getOperand(CIdx->getZExtValue());
702     } else if (isa<UndefValue>(Idx)) {
703       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
704       return CVal->getOperand(0);
705     }
706   }
707   return 0;
708 }
709
710 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
711                                                      Constant *Elt,
712                                                      Constant *Idx) {
713   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
714   if (!CIdx) return 0;
715   APInt idxVal = CIdx->getValue();
716   if (isa<UndefValue>(Val)) { 
717     // Insertion of scalar constant into vector undef
718     // Optimize away insertion of undef
719     if (isa<UndefValue>(Elt))
720       return Val;
721     // Otherwise break the aggregate undef into multiple undefs and do
722     // the insertion
723     unsigned numOps = 
724       cast<VectorType>(Val->getType())->getNumElements();
725     std::vector<Constant*> Ops; 
726     Ops.reserve(numOps);
727     for (unsigned i = 0; i < numOps; ++i) {
728       Constant *Op =
729         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
730       Ops.push_back(Op);
731     }
732     return ConstantVector::get(Ops);
733   }
734   if (isa<ConstantAggregateZero>(Val)) {
735     // Insertion of scalar constant into vector aggregate zero
736     // Optimize away insertion of zero
737     if (Elt->isNullValue())
738       return Val;
739     // Otherwise break the aggregate zero into multiple zeros and do
740     // the insertion
741     unsigned numOps = 
742       cast<VectorType>(Val->getType())->getNumElements();
743     std::vector<Constant*> Ops; 
744     Ops.reserve(numOps);
745     for (unsigned i = 0; i < numOps; ++i) {
746       Constant *Op =
747         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
748       Ops.push_back(Op);
749     }
750     return ConstantVector::get(Ops);
751   }
752   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
753     // Insertion of scalar constant into vector constant
754     std::vector<Constant*> Ops; 
755     Ops.reserve(CVal->getNumOperands());
756     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
757       Constant *Op =
758         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
759       Ops.push_back(Op);
760     }
761     return ConstantVector::get(Ops);
762   }
763
764   return 0;
765 }
766
767 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
768 /// return the specified element value.  Otherwise return null.
769 static Constant *GetVectorElement(Constant *C, unsigned EltNo) {
770   if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
771     return CV->getOperand(EltNo);
772
773   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
774   if (isa<ConstantAggregateZero>(C))
775     return Constant::getNullValue(EltTy);
776   if (isa<UndefValue>(C))
777     return UndefValue::get(EltTy);
778   return 0;
779 }
780
781 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
782                                                      Constant *V2,
783                                                      Constant *Mask) {
784   // Undefined shuffle mask -> undefined value.
785   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
786
787   unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
788   unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
789   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
790
791   // Loop over the shuffle mask, evaluating each element.
792   SmallVector<Constant*, 32> Result;
793   for (unsigned i = 0; i != MaskNumElts; ++i) {
794     Constant *InElt = GetVectorElement(Mask, i);
795     if (InElt == 0) return 0;
796
797     if (isa<UndefValue>(InElt))
798       InElt = UndefValue::get(EltTy);
799     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
800       unsigned Elt = CI->getZExtValue();
801       if (Elt >= SrcNumElts*2)
802         InElt = UndefValue::get(EltTy);
803       else if (Elt >= SrcNumElts)
804         InElt = GetVectorElement(V2, Elt - SrcNumElts);
805       else
806         InElt = GetVectorElement(V1, Elt);
807       if (InElt == 0) return 0;
808     } else {
809       // Unknown value.
810       return 0;
811     }
812     Result.push_back(InElt);
813   }
814
815   return ConstantVector::get(&Result[0], Result.size());
816 }
817
818 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
819                                                     const unsigned *Idxs,
820                                                     unsigned NumIdx) {
821   // Base case: no indices, so return the entire value.
822   if (NumIdx == 0)
823     return Agg;
824
825   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
826     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
827                                                             Idxs,
828                                                             Idxs + NumIdx));
829
830   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
831     return
832       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
833                                                               Idxs,
834                                                               Idxs + NumIdx));
835
836   // Otherwise recurse.
837   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
838     return ConstantFoldExtractValueInstruction(CS->getOperand(*Idxs),
839                                                Idxs+1, NumIdx-1);
840
841   if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
842     return ConstantFoldExtractValueInstruction(CA->getOperand(*Idxs),
843                                                Idxs+1, NumIdx-1);
844   ConstantVector *CV = cast<ConstantVector>(Agg);
845   return ConstantFoldExtractValueInstruction(CV->getOperand(*Idxs),
846                                              Idxs+1, NumIdx-1);
847 }
848
849 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
850                                                    Constant *Val,
851                                                    const unsigned *Idxs,
852                                                    unsigned NumIdx) {
853   // Base case: no indices, so replace the entire value.
854   if (NumIdx == 0)
855     return Val;
856
857   if (isa<UndefValue>(Agg)) {
858     // Insertion of constant into aggregate undef
859     // Optimize away insertion of undef.
860     if (isa<UndefValue>(Val))
861       return Agg;
862     
863     // Otherwise break the aggregate undef into multiple undefs and do
864     // the insertion.
865     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
866     unsigned numOps;
867     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
868       numOps = AR->getNumElements();
869     else
870       numOps = cast<StructType>(AggTy)->getNumElements();
871     
872     std::vector<Constant*> Ops(numOps); 
873     for (unsigned i = 0; i < numOps; ++i) {
874       const Type *MemberTy = AggTy->getTypeAtIndex(i);
875       Constant *Op =
876         (*Idxs == i) ?
877         ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
878                                            Val, Idxs+1, NumIdx-1) :
879         UndefValue::get(MemberTy);
880       Ops[i] = Op;
881     }
882     
883     if (const StructType* ST = dyn_cast<StructType>(AggTy))
884       return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
885     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
886   }
887   
888   if (isa<ConstantAggregateZero>(Agg)) {
889     // Insertion of constant into aggregate zero
890     // Optimize away insertion of zero.
891     if (Val->isNullValue())
892       return Agg;
893     
894     // Otherwise break the aggregate zero into multiple zeros and do
895     // the insertion.
896     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
897     unsigned numOps;
898     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
899       numOps = AR->getNumElements();
900     else
901       numOps = cast<StructType>(AggTy)->getNumElements();
902     
903     std::vector<Constant*> Ops(numOps);
904     for (unsigned i = 0; i < numOps; ++i) {
905       const Type *MemberTy = AggTy->getTypeAtIndex(i);
906       Constant *Op =
907         (*Idxs == i) ?
908         ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
909                                            Val, Idxs+1, NumIdx-1) :
910         Constant::getNullValue(MemberTy);
911       Ops[i] = Op;
912     }
913     
914     if (const StructType *ST = dyn_cast<StructType>(AggTy))
915       return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
916     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
917   }
918   
919   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
920     // Insertion of constant into aggregate constant.
921     std::vector<Constant*> Ops(Agg->getNumOperands());
922     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
923       Constant *Op = cast<Constant>(Agg->getOperand(i));
924       if (*Idxs == i)
925         Op = ConstantFoldInsertValueInstruction(Op, Val, Idxs+1, NumIdx-1);
926       Ops[i] = Op;
927     }
928     
929     if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
930       return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
931     return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
932   }
933
934   return 0;
935 }
936
937
938 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
939                                               Constant *C1, Constant *C2) {
940   // No compile-time operations on this type yet.
941   if (C1->getType()->isPPC_FP128Ty())
942     return 0;
943
944   // Handle UndefValue up front.
945   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
946     switch (Opcode) {
947     case Instruction::Xor:
948       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
949         // Handle undef ^ undef -> 0 special case. This is a common
950         // idiom (misuse).
951         return Constant::getNullValue(C1->getType());
952       // Fallthrough
953     case Instruction::Add:
954     case Instruction::Sub:
955       return UndefValue::get(C1->getType());
956     case Instruction::Mul:
957     case Instruction::And:
958       return Constant::getNullValue(C1->getType());
959     case Instruction::UDiv:
960     case Instruction::SDiv:
961     case Instruction::URem:
962     case Instruction::SRem:
963       if (!isa<UndefValue>(C2))                    // undef / X -> 0
964         return Constant::getNullValue(C1->getType());
965       return C2;                                   // X / undef -> undef
966     case Instruction::Or:                          // X | undef -> -1
967       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
968         return Constant::getAllOnesValue(PTy);
969       return Constant::getAllOnesValue(C1->getType());
970     case Instruction::LShr:
971       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
972         return C1;                                  // undef lshr undef -> undef
973       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
974                                                     // undef lshr X -> 0
975     case Instruction::AShr:
976       if (!isa<UndefValue>(C2))
977         return C1;                                  // undef ashr X --> undef
978       else if (isa<UndefValue>(C1)) 
979         return C1;                                  // undef ashr undef -> undef
980       else
981         return C1;                                  // X ashr undef --> X
982     case Instruction::Shl:
983       // undef << X -> 0   or   X << undef -> 0
984       return Constant::getNullValue(C1->getType());
985     }
986   }
987
988   // Handle simplifications when the RHS is a constant int.
989   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
990     switch (Opcode) {
991     case Instruction::Add:
992       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
993       break;
994     case Instruction::Sub:
995       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
996       break;
997     case Instruction::Mul:
998       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
999       if (CI2->equalsInt(1))
1000         return C1;                                              // X * 1 == X
1001       break;
1002     case Instruction::UDiv:
1003     case Instruction::SDiv:
1004       if (CI2->equalsInt(1))
1005         return C1;                                            // X / 1 == X
1006       if (CI2->equalsInt(0))
1007         return UndefValue::get(CI2->getType());               // X / 0 == undef
1008       break;
1009     case Instruction::URem:
1010     case Instruction::SRem:
1011       if (CI2->equalsInt(1))
1012         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
1013       if (CI2->equalsInt(0))
1014         return UndefValue::get(CI2->getType());               // X % 0 == undef
1015       break;
1016     case Instruction::And:
1017       if (CI2->isZero()) return C2;                           // X & 0 == 0
1018       if (CI2->isAllOnesValue())
1019         return C1;                                            // X & -1 == X
1020
1021       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1022         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1023         if (CE1->getOpcode() == Instruction::ZExt) {
1024           unsigned DstWidth = CI2->getType()->getBitWidth();
1025           unsigned SrcWidth =
1026             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1027           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1028           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1029             return C1;
1030         }
1031
1032         // If and'ing the address of a global with a constant, fold it.
1033         if (CE1->getOpcode() == Instruction::PtrToInt && 
1034             isa<GlobalValue>(CE1->getOperand(0))) {
1035           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1036
1037           // Functions are at least 4-byte aligned.
1038           unsigned GVAlign = GV->getAlignment();
1039           if (isa<Function>(GV))
1040             GVAlign = std::max(GVAlign, 4U);
1041
1042           if (GVAlign > 1) {
1043             unsigned DstWidth = CI2->getType()->getBitWidth();
1044             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1045             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1046
1047             // If checking bits we know are clear, return zero.
1048             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1049               return Constant::getNullValue(CI2->getType());
1050           }
1051         }
1052       }
1053       break;
1054     case Instruction::Or:
1055       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1056       if (CI2->isAllOnesValue())
1057         return C2;                         // X | -1 == -1
1058       break;
1059     case Instruction::Xor:
1060       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1061
1062       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1063         switch (CE1->getOpcode()) {
1064         default: break;
1065         case Instruction::ICmp:
1066         case Instruction::FCmp:
1067           // cmp pred ^ true -> cmp !pred
1068           assert(CI2->equalsInt(1));
1069           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1070           pred = CmpInst::getInversePredicate(pred);
1071           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1072                                           CE1->getOperand(1));
1073         }
1074       }
1075       break;
1076     case Instruction::AShr:
1077       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1078       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1079         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1080           return ConstantExpr::getLShr(C1, C2);
1081       break;
1082     }
1083   }
1084
1085   // At this point we know neither constant is an UndefValue.
1086   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1087     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1088       using namespace APIntOps;
1089       const APInt &C1V = CI1->getValue();
1090       const APInt &C2V = CI2->getValue();
1091       switch (Opcode) {
1092       default:
1093         break;
1094       case Instruction::Add:     
1095         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1096       case Instruction::Sub:     
1097         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1098       case Instruction::Mul:     
1099         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1100       case Instruction::UDiv:
1101         assert(!CI2->isNullValue() && "Div by zero handled above");
1102         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1103       case Instruction::SDiv:
1104         assert(!CI2->isNullValue() && "Div by zero handled above");
1105         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1106           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1107         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1108       case Instruction::URem:
1109         assert(!CI2->isNullValue() && "Div by zero handled above");
1110         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1111       case Instruction::SRem:
1112         assert(!CI2->isNullValue() && "Div by zero handled above");
1113         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1114           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1115         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1116       case Instruction::And:
1117         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1118       case Instruction::Or:
1119         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1120       case Instruction::Xor:
1121         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1122       case Instruction::Shl: {
1123         uint32_t shiftAmt = C2V.getZExtValue();
1124         if (shiftAmt < C1V.getBitWidth())
1125           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1126         else
1127           return UndefValue::get(C1->getType()); // too big shift is undef
1128       }
1129       case Instruction::LShr: {
1130         uint32_t shiftAmt = C2V.getZExtValue();
1131         if (shiftAmt < C1V.getBitWidth())
1132           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1133         else
1134           return UndefValue::get(C1->getType()); // too big shift is undef
1135       }
1136       case Instruction::AShr: {
1137         uint32_t shiftAmt = C2V.getZExtValue();
1138         if (shiftAmt < C1V.getBitWidth())
1139           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1140         else
1141           return UndefValue::get(C1->getType()); // too big shift is undef
1142       }
1143       }
1144     }
1145
1146     switch (Opcode) {
1147     case Instruction::SDiv:
1148     case Instruction::UDiv:
1149     case Instruction::URem:
1150     case Instruction::SRem:
1151     case Instruction::LShr:
1152     case Instruction::AShr:
1153     case Instruction::Shl:
1154       if (CI1->equalsInt(0)) return C1;
1155       break;
1156     default:
1157       break;
1158     }
1159   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1160     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1161       APFloat C1V = CFP1->getValueAPF();
1162       APFloat C2V = CFP2->getValueAPF();
1163       APFloat C3V = C1V;  // copy for modification
1164       switch (Opcode) {
1165       default:                   
1166         break;
1167       case Instruction::FAdd:
1168         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1169         return ConstantFP::get(C1->getContext(), C3V);
1170       case Instruction::FSub:
1171         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1172         return ConstantFP::get(C1->getContext(), C3V);
1173       case Instruction::FMul:
1174         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1175         return ConstantFP::get(C1->getContext(), C3V);
1176       case Instruction::FDiv:
1177         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1178         return ConstantFP::get(C1->getContext(), C3V);
1179       case Instruction::FRem:
1180         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1181         return ConstantFP::get(C1->getContext(), C3V);
1182       }
1183     }
1184   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1185     ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1186     ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
1187     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1188         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
1189       std::vector<Constant*> Res;
1190       const Type* EltTy = VTy->getElementType();  
1191       Constant *C1 = 0;
1192       Constant *C2 = 0;
1193       switch (Opcode) {
1194       default:
1195         break;
1196       case Instruction::Add:
1197         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1198           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1199           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1200           Res.push_back(ConstantExpr::getAdd(C1, C2));
1201         }
1202         return ConstantVector::get(Res);
1203       case Instruction::FAdd:
1204         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1205           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1206           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1207           Res.push_back(ConstantExpr::getFAdd(C1, C2));
1208         }
1209         return ConstantVector::get(Res);
1210       case Instruction::Sub:
1211         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1212           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1213           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1214           Res.push_back(ConstantExpr::getSub(C1, C2));
1215         }
1216         return ConstantVector::get(Res);
1217       case Instruction::FSub:
1218         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1219           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1220           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1221           Res.push_back(ConstantExpr::getFSub(C1, C2));
1222         }
1223         return ConstantVector::get(Res);
1224       case Instruction::Mul:
1225         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1226           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1227           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1228           Res.push_back(ConstantExpr::getMul(C1, C2));
1229         }
1230         return ConstantVector::get(Res);
1231       case Instruction::FMul:
1232         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1233           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1234           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1235           Res.push_back(ConstantExpr::getFMul(C1, C2));
1236         }
1237         return ConstantVector::get(Res);
1238       case Instruction::UDiv:
1239         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1240           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1241           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1242           Res.push_back(ConstantExpr::getUDiv(C1, C2));
1243         }
1244         return ConstantVector::get(Res);
1245       case Instruction::SDiv:
1246         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1247           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1248           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1249           Res.push_back(ConstantExpr::getSDiv(C1, C2));
1250         }
1251         return ConstantVector::get(Res);
1252       case Instruction::FDiv:
1253         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1254           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1255           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1256           Res.push_back(ConstantExpr::getFDiv(C1, C2));
1257         }
1258         return ConstantVector::get(Res);
1259       case Instruction::URem:
1260         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1261           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1262           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1263           Res.push_back(ConstantExpr::getURem(C1, C2));
1264         }
1265         return ConstantVector::get(Res);
1266       case Instruction::SRem:
1267         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1268           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1269           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1270           Res.push_back(ConstantExpr::getSRem(C1, C2));
1271         }
1272         return ConstantVector::get(Res);
1273       case Instruction::FRem:
1274         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1275           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1276           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1277           Res.push_back(ConstantExpr::getFRem(C1, C2));
1278         }
1279         return ConstantVector::get(Res);
1280       case Instruction::And: 
1281         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1282           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1283           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1284           Res.push_back(ConstantExpr::getAnd(C1, C2));
1285         }
1286         return ConstantVector::get(Res);
1287       case Instruction::Or:
1288         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1289           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1290           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1291           Res.push_back(ConstantExpr::getOr(C1, C2));
1292         }
1293         return ConstantVector::get(Res);
1294       case Instruction::Xor:
1295         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1296           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1297           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1298           Res.push_back(ConstantExpr::getXor(C1, C2));
1299         }
1300         return ConstantVector::get(Res);
1301       case Instruction::LShr:
1302         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1303           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1304           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1305           Res.push_back(ConstantExpr::getLShr(C1, C2));
1306         }
1307         return ConstantVector::get(Res);
1308       case Instruction::AShr:
1309         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1310           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1311           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1312           Res.push_back(ConstantExpr::getAShr(C1, C2));
1313         }
1314         return ConstantVector::get(Res);
1315       case Instruction::Shl:
1316         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1317           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1318           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1319           Res.push_back(ConstantExpr::getShl(C1, C2));
1320         }
1321         return ConstantVector::get(Res);
1322       }
1323     }
1324   }
1325
1326   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1327     // There are many possible foldings we could do here.  We should probably
1328     // at least fold add of a pointer with an integer into the appropriate
1329     // getelementptr.  This will improve alias analysis a bit.
1330
1331     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1332     // (a + (b + c)).
1333     if (Instruction::isAssociative(Opcode, C1->getType()) &&
1334         CE1->getOpcode() == Opcode) {
1335       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1336       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1337         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1338     }
1339   } else if (isa<ConstantExpr>(C2)) {
1340     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1341     // other way if possible.
1342     switch (Opcode) {
1343     case Instruction::Add:
1344     case Instruction::FAdd:
1345     case Instruction::Mul:
1346     case Instruction::FMul:
1347     case Instruction::And:
1348     case Instruction::Or:
1349     case Instruction::Xor:
1350       // No change of opcode required.
1351       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1352
1353     case Instruction::Shl:
1354     case Instruction::LShr:
1355     case Instruction::AShr:
1356     case Instruction::Sub:
1357     case Instruction::FSub:
1358     case Instruction::SDiv:
1359     case Instruction::UDiv:
1360     case Instruction::FDiv:
1361     case Instruction::URem:
1362     case Instruction::SRem:
1363     case Instruction::FRem:
1364     default:  // These instructions cannot be flopped around.
1365       break;
1366     }
1367   }
1368
1369   // i1 can be simplified in many cases.
1370   if (C1->getType()->isInteger(1)) {
1371     switch (Opcode) {
1372     case Instruction::Add:
1373     case Instruction::Sub:
1374       return ConstantExpr::getXor(C1, C2);
1375     case Instruction::Mul:
1376       return ConstantExpr::getAnd(C1, C2);
1377     case Instruction::Shl:
1378     case Instruction::LShr:
1379     case Instruction::AShr:
1380       // We can assume that C2 == 0.  If it were one the result would be
1381       // undefined because the shift value is as large as the bitwidth.
1382       return C1;
1383     case Instruction::SDiv:
1384     case Instruction::UDiv:
1385       // We can assume that C2 == 1.  If it were zero the result would be
1386       // undefined through division by zero.
1387       return C1;
1388     case Instruction::URem:
1389     case Instruction::SRem:
1390       // We can assume that C2 == 1.  If it were zero the result would be
1391       // undefined through division by zero.
1392       return ConstantInt::getFalse(C1->getContext());
1393     default:
1394       break;
1395     }
1396   }
1397
1398   // We don't know how to fold this.
1399   return 0;
1400 }
1401
1402 /// isZeroSizedType - This type is zero sized if its an array or structure of
1403 /// zero sized types.  The only leaf zero sized type is an empty structure.
1404 static bool isMaybeZeroSizedType(const Type *Ty) {
1405   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
1406   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1407
1408     // If all of elements have zero size, this does too.
1409     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1410       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1411     return true;
1412
1413   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1414     return isMaybeZeroSizedType(ATy->getElementType());
1415   }
1416   return false;
1417 }
1418
1419 /// IdxCompare - Compare the two constants as though they were getelementptr
1420 /// indices.  This allows coersion of the types to be the same thing.
1421 ///
1422 /// If the two constants are the "same" (after coersion), return 0.  If the
1423 /// first is less than the second, return -1, if the second is less than the
1424 /// first, return 1.  If the constants are not integral, return -2.
1425 ///
1426 static int IdxCompare(Constant *C1, Constant *C2,  const Type *ElTy) {
1427   if (C1 == C2) return 0;
1428
1429   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1430   // anything with them.
1431   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1432     return -2; // don't know!
1433
1434   // Ok, we have two differing integer indices.  Sign extend them to be the same
1435   // type.  Long is always big enough, so we use it.
1436   if (!C1->getType()->isInteger(64))
1437     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1438
1439   if (!C2->getType()->isInteger(64))
1440     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1441
1442   if (C1 == C2) return 0;  // They are equal
1443
1444   // If the type being indexed over is really just a zero sized type, there is
1445   // no pointer difference being made here.
1446   if (isMaybeZeroSizedType(ElTy))
1447     return -2; // dunno.
1448
1449   // If they are really different, now that they are the same type, then we
1450   // found a difference!
1451   if (cast<ConstantInt>(C1)->getSExtValue() < 
1452       cast<ConstantInt>(C2)->getSExtValue())
1453     return -1;
1454   else
1455     return 1;
1456 }
1457
1458 /// evaluateFCmpRelation - This function determines if there is anything we can
1459 /// decide about the two constants provided.  This doesn't need to handle simple
1460 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1461 /// If we can determine that the two constants have a particular relation to 
1462 /// each other, we should return the corresponding FCmpInst predicate, 
1463 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1464 /// ConstantFoldCompareInstruction.
1465 ///
1466 /// To simplify this code we canonicalize the relation so that the first
1467 /// operand is always the most "complex" of the two.  We consider ConstantFP
1468 /// to be the simplest, and ConstantExprs to be the most complex.
1469 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1470   assert(V1->getType() == V2->getType() &&
1471          "Cannot compare values of different types!");
1472
1473   // No compile-time operations on this type yet.
1474   if (V1->getType()->isPPC_FP128Ty())
1475     return FCmpInst::BAD_FCMP_PREDICATE;
1476
1477   // Handle degenerate case quickly
1478   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1479
1480   if (!isa<ConstantExpr>(V1)) {
1481     if (!isa<ConstantExpr>(V2)) {
1482       // We distilled thisUse the standard constant folder for a few cases
1483       ConstantInt *R = 0;
1484       R = dyn_cast<ConstantInt>(
1485                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1486       if (R && !R->isZero()) 
1487         return FCmpInst::FCMP_OEQ;
1488       R = dyn_cast<ConstantInt>(
1489                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1490       if (R && !R->isZero()) 
1491         return FCmpInst::FCMP_OLT;
1492       R = dyn_cast<ConstantInt>(
1493                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1494       if (R && !R->isZero()) 
1495         return FCmpInst::FCMP_OGT;
1496
1497       // Nothing more we can do
1498       return FCmpInst::BAD_FCMP_PREDICATE;
1499     }
1500
1501     // If the first operand is simple and second is ConstantExpr, swap operands.
1502     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1503     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1504       return FCmpInst::getSwappedPredicate(SwappedRelation);
1505   } else {
1506     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1507     // constantexpr or a simple constant.
1508     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1509     switch (CE1->getOpcode()) {
1510     case Instruction::FPTrunc:
1511     case Instruction::FPExt:
1512     case Instruction::UIToFP:
1513     case Instruction::SIToFP:
1514       // We might be able to do something with these but we don't right now.
1515       break;
1516     default:
1517       break;
1518     }
1519   }
1520   // There are MANY other foldings that we could perform here.  They will
1521   // probably be added on demand, as they seem needed.
1522   return FCmpInst::BAD_FCMP_PREDICATE;
1523 }
1524
1525 /// evaluateICmpRelation - This function determines if there is anything we can
1526 /// decide about the two constants provided.  This doesn't need to handle simple
1527 /// things like integer comparisons, but should instead handle ConstantExprs
1528 /// and GlobalValues.  If we can determine that the two constants have a
1529 /// particular relation to each other, we should return the corresponding ICmp
1530 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1531 ///
1532 /// To simplify this code we canonicalize the relation so that the first
1533 /// operand is always the most "complex" of the two.  We consider simple
1534 /// constants (like ConstantInt) to be the simplest, followed by
1535 /// GlobalValues, followed by ConstantExpr's (the most complex).
1536 ///
1537 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1538                                                 bool isSigned) {
1539   assert(V1->getType() == V2->getType() &&
1540          "Cannot compare different types of values!");
1541   if (V1 == V2) return ICmpInst::ICMP_EQ;
1542
1543   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1544       !isa<BlockAddress>(V1)) {
1545     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1546         !isa<BlockAddress>(V2)) {
1547       // We distilled this down to a simple case, use the standard constant
1548       // folder.
1549       ConstantInt *R = 0;
1550       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1551       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1552       if (R && !R->isZero()) 
1553         return pred;
1554       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1555       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1556       if (R && !R->isZero())
1557         return pred;
1558       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1559       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1560       if (R && !R->isZero())
1561         return pred;
1562
1563       // If we couldn't figure it out, bail.
1564       return ICmpInst::BAD_ICMP_PREDICATE;
1565     }
1566
1567     // If the first operand is simple, swap operands.
1568     ICmpInst::Predicate SwappedRelation = 
1569       evaluateICmpRelation(V2, V1, isSigned);
1570     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1571       return ICmpInst::getSwappedPredicate(SwappedRelation);
1572
1573   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1574     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1575       ICmpInst::Predicate SwappedRelation = 
1576         evaluateICmpRelation(V2, V1, isSigned);
1577       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1578         return ICmpInst::getSwappedPredicate(SwappedRelation);
1579       return ICmpInst::BAD_ICMP_PREDICATE;
1580     }
1581
1582     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1583     // constant (which, since the types must match, means that it's a
1584     // ConstantPointerNull).
1585     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1586       // Don't try to decide equality of aliases.
1587       if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1588         if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1589           return ICmpInst::ICMP_NE;
1590     } else if (isa<BlockAddress>(V2)) {
1591       return ICmpInst::ICMP_NE; // Globals never equal labels.
1592     } else {
1593       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1594       // GlobalVals can never be null unless they have external weak linkage.
1595       // We don't try to evaluate aliases here.
1596       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1597         return ICmpInst::ICMP_NE;
1598     }
1599   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1600     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1601       ICmpInst::Predicate SwappedRelation = 
1602         evaluateICmpRelation(V2, V1, isSigned);
1603       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1604         return ICmpInst::getSwappedPredicate(SwappedRelation);
1605       return ICmpInst::BAD_ICMP_PREDICATE;
1606     }
1607     
1608     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1609     // constant (which, since the types must match, means that it is a
1610     // ConstantPointerNull).
1611     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1612       // Block address in another function can't equal this one, but block
1613       // addresses in the current function might be the same if blocks are
1614       // empty.
1615       if (BA2->getFunction() != BA->getFunction())
1616         return ICmpInst::ICMP_NE;
1617     } else {
1618       // Block addresses aren't null, don't equal the address of globals.
1619       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1620              "Canonicalization guarantee!");
1621       return ICmpInst::ICMP_NE;
1622     }
1623   } else {
1624     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1625     // constantexpr, a global, block address, or a simple constant.
1626     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1627     Constant *CE1Op0 = CE1->getOperand(0);
1628
1629     switch (CE1->getOpcode()) {
1630     case Instruction::Trunc:
1631     case Instruction::FPTrunc:
1632     case Instruction::FPExt:
1633     case Instruction::FPToUI:
1634     case Instruction::FPToSI:
1635       break; // We can't evaluate floating point casts or truncations.
1636
1637     case Instruction::UIToFP:
1638     case Instruction::SIToFP:
1639     case Instruction::BitCast:
1640     case Instruction::ZExt:
1641     case Instruction::SExt:
1642       // If the cast is not actually changing bits, and the second operand is a
1643       // null pointer, do the comparison with the pre-casted value.
1644       if (V2->isNullValue() &&
1645           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1646         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1647         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1648         return evaluateICmpRelation(CE1Op0,
1649                                     Constant::getNullValue(CE1Op0->getType()), 
1650                                     isSigned);
1651       }
1652       break;
1653
1654     case Instruction::GetElementPtr:
1655       // Ok, since this is a getelementptr, we know that the constant has a
1656       // pointer type.  Check the various cases.
1657       if (isa<ConstantPointerNull>(V2)) {
1658         // If we are comparing a GEP to a null pointer, check to see if the base
1659         // of the GEP equals the null pointer.
1660         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1661           if (GV->hasExternalWeakLinkage())
1662             // Weak linkage GVals could be zero or not. We're comparing that
1663             // to null pointer so its greater-or-equal
1664             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1665           else 
1666             // If its not weak linkage, the GVal must have a non-zero address
1667             // so the result is greater-than
1668             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1669         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1670           // If we are indexing from a null pointer, check to see if we have any
1671           // non-zero indices.
1672           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1673             if (!CE1->getOperand(i)->isNullValue())
1674               // Offsetting from null, must not be equal.
1675               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1676           // Only zero indexes from null, must still be zero.
1677           return ICmpInst::ICMP_EQ;
1678         }
1679         // Otherwise, we can't really say if the first operand is null or not.
1680       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1681         if (isa<ConstantPointerNull>(CE1Op0)) {
1682           if (GV2->hasExternalWeakLinkage())
1683             // Weak linkage GVals could be zero or not. We're comparing it to
1684             // a null pointer, so its less-or-equal
1685             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1686           else
1687             // If its not weak linkage, the GVal must have a non-zero address
1688             // so the result is less-than
1689             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1690         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1691           if (GV == GV2) {
1692             // If this is a getelementptr of the same global, then it must be
1693             // different.  Because the types must match, the getelementptr could
1694             // only have at most one index, and because we fold getelementptr's
1695             // with a single zero index, it must be nonzero.
1696             assert(CE1->getNumOperands() == 2 &&
1697                    !CE1->getOperand(1)->isNullValue() &&
1698                    "Suprising getelementptr!");
1699             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1700           } else {
1701             // If they are different globals, we don't know what the value is,
1702             // but they can't be equal.
1703             return ICmpInst::ICMP_NE;
1704           }
1705         }
1706       } else {
1707         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1708         Constant *CE2Op0 = CE2->getOperand(0);
1709
1710         // There are MANY other foldings that we could perform here.  They will
1711         // probably be added on demand, as they seem needed.
1712         switch (CE2->getOpcode()) {
1713         default: break;
1714         case Instruction::GetElementPtr:
1715           // By far the most common case to handle is when the base pointers are
1716           // obviously to the same or different globals.
1717           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1718             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1719               return ICmpInst::ICMP_NE;
1720             // Ok, we know that both getelementptr instructions are based on the
1721             // same global.  From this, we can precisely determine the relative
1722             // ordering of the resultant pointers.
1723             unsigned i = 1;
1724
1725             // The logic below assumes that the result of the comparison
1726             // can be determined by finding the first index that differs.
1727             // This doesn't work if there is over-indexing in any
1728             // subsequent indices, so check for that case first.
1729             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1730                 !CE2->isGEPWithNoNotionalOverIndexing())
1731                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1732
1733             // Compare all of the operands the GEP's have in common.
1734             gep_type_iterator GTI = gep_type_begin(CE1);
1735             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1736                  ++i, ++GTI)
1737               switch (IdxCompare(CE1->getOperand(i),
1738                                  CE2->getOperand(i), GTI.getIndexedType())) {
1739               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1740               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1741               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1742               }
1743
1744             // Ok, we ran out of things they have in common.  If any leftovers
1745             // are non-zero then we have a difference, otherwise we are equal.
1746             for (; i < CE1->getNumOperands(); ++i)
1747               if (!CE1->getOperand(i)->isNullValue()) {
1748                 if (isa<ConstantInt>(CE1->getOperand(i)))
1749                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1750                 else
1751                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1752               }
1753
1754             for (; i < CE2->getNumOperands(); ++i)
1755               if (!CE2->getOperand(i)->isNullValue()) {
1756                 if (isa<ConstantInt>(CE2->getOperand(i)))
1757                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1758                 else
1759                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1760               }
1761             return ICmpInst::ICMP_EQ;
1762           }
1763         }
1764       }
1765     default:
1766       break;
1767     }
1768   }
1769
1770   return ICmpInst::BAD_ICMP_PREDICATE;
1771 }
1772
1773 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1774                                                Constant *C1, Constant *C2) {
1775   const Type *ResultTy;
1776   if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1777     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1778                                VT->getNumElements());
1779   else
1780     ResultTy = Type::getInt1Ty(C1->getContext());
1781
1782   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1783   if (pred == FCmpInst::FCMP_FALSE)
1784     return Constant::getNullValue(ResultTy);
1785
1786   if (pred == FCmpInst::FCMP_TRUE)
1787     return Constant::getAllOnesValue(ResultTy);
1788
1789   // Handle some degenerate cases first
1790   if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1791     return UndefValue::get(ResultTy);
1792
1793   // No compile-time operations on this type yet.
1794   if (C1->getType()->isPPC_FP128Ty())
1795     return 0;
1796
1797   // icmp eq/ne(null,GV) -> false/true
1798   if (C1->isNullValue()) {
1799     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1800       // Don't try to evaluate aliases.  External weak GV can be null.
1801       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1802         if (pred == ICmpInst::ICMP_EQ)
1803           return ConstantInt::getFalse(C1->getContext());
1804         else if (pred == ICmpInst::ICMP_NE)
1805           return ConstantInt::getTrue(C1->getContext());
1806       }
1807   // icmp eq/ne(GV,null) -> false/true
1808   } else if (C2->isNullValue()) {
1809     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1810       // Don't try to evaluate aliases.  External weak GV can be null.
1811       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1812         if (pred == ICmpInst::ICMP_EQ)
1813           return ConstantInt::getFalse(C1->getContext());
1814         else if (pred == ICmpInst::ICMP_NE)
1815           return ConstantInt::getTrue(C1->getContext());
1816       }
1817   }
1818
1819   // If the comparison is a comparison between two i1's, simplify it.
1820   if (C1->getType()->isInteger(1)) {
1821     switch(pred) {
1822     case ICmpInst::ICMP_EQ:
1823       if (isa<ConstantInt>(C2))
1824         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1825       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1826     case ICmpInst::ICMP_NE:
1827       return ConstantExpr::getXor(C1, C2);
1828     default:
1829       break;
1830     }
1831   }
1832
1833   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1834     APInt V1 = cast<ConstantInt>(C1)->getValue();
1835     APInt V2 = cast<ConstantInt>(C2)->getValue();
1836     switch (pred) {
1837     default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1838     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1839     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1840     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1841     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1842     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1843     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1844     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1845     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1846     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1847     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1848     }
1849   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1850     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1851     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1852     APFloat::cmpResult R = C1V.compare(C2V);
1853     switch (pred) {
1854     default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1855     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1856     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1857     case FCmpInst::FCMP_UNO:
1858       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1859     case FCmpInst::FCMP_ORD:
1860       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1861     case FCmpInst::FCMP_UEQ:
1862       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1863                                         R==APFloat::cmpEqual);
1864     case FCmpInst::FCMP_OEQ:   
1865       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1866     case FCmpInst::FCMP_UNE:
1867       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1868     case FCmpInst::FCMP_ONE:   
1869       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1870                                         R==APFloat::cmpGreaterThan);
1871     case FCmpInst::FCMP_ULT: 
1872       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1873                                         R==APFloat::cmpLessThan);
1874     case FCmpInst::FCMP_OLT:   
1875       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1876     case FCmpInst::FCMP_UGT:
1877       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1878                                         R==APFloat::cmpGreaterThan);
1879     case FCmpInst::FCMP_OGT:
1880       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1881     case FCmpInst::FCMP_ULE:
1882       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1883     case FCmpInst::FCMP_OLE: 
1884       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1885                                         R==APFloat::cmpEqual);
1886     case FCmpInst::FCMP_UGE:
1887       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1888     case FCmpInst::FCMP_OGE: 
1889       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1890                                         R==APFloat::cmpEqual);
1891     }
1892   } else if (isa<VectorType>(C1->getType())) {
1893     SmallVector<Constant*, 16> C1Elts, C2Elts;
1894     C1->getVectorElements(C1Elts);
1895     C2->getVectorElements(C2Elts);
1896     if (C1Elts.empty() || C2Elts.empty())
1897       return 0;
1898
1899     // If we can constant fold the comparison of each element, constant fold
1900     // the whole vector comparison.
1901     SmallVector<Constant*, 4> ResElts;
1902     for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1903       // Compare the elements, producing an i1 result or constant expr.
1904       ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1905     }
1906     return ConstantVector::get(&ResElts[0], ResElts.size());
1907   }
1908
1909   if (C1->getType()->isFloatingPoint()) {
1910     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1911     switch (evaluateFCmpRelation(C1, C2)) {
1912     default: llvm_unreachable("Unknown relation!");
1913     case FCmpInst::FCMP_UNO:
1914     case FCmpInst::FCMP_ORD:
1915     case FCmpInst::FCMP_UEQ:
1916     case FCmpInst::FCMP_UNE:
1917     case FCmpInst::FCMP_ULT:
1918     case FCmpInst::FCMP_UGT:
1919     case FCmpInst::FCMP_ULE:
1920     case FCmpInst::FCMP_UGE:
1921     case FCmpInst::FCMP_TRUE:
1922     case FCmpInst::FCMP_FALSE:
1923     case FCmpInst::BAD_FCMP_PREDICATE:
1924       break; // Couldn't determine anything about these constants.
1925     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1926       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1927                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1928                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1929       break;
1930     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1931       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1932                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1933                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1934       break;
1935     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1936       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1937                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1938                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1939       break;
1940     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1941       // We can only partially decide this relation.
1942       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1943         Result = 0;
1944       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1945         Result = 1;
1946       break;
1947     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1948       // We can only partially decide this relation.
1949       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1950         Result = 0;
1951       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1952         Result = 1;
1953       break;
1954     case ICmpInst::ICMP_NE: // We know that C1 != C2
1955       // We can only partially decide this relation.
1956       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1957         Result = 0;
1958       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1959         Result = 1;
1960       break;
1961     }
1962
1963     // If we evaluated the result, return it now.
1964     if (Result != -1)
1965       return ConstantInt::get(ResultTy, Result);
1966
1967   } else {
1968     // Evaluate the relation between the two constants, per the predicate.
1969     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1970     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1971     default: llvm_unreachable("Unknown relational!");
1972     case ICmpInst::BAD_ICMP_PREDICATE:
1973       break;  // Couldn't determine anything about these constants.
1974     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1975       // If we know the constants are equal, we can decide the result of this
1976       // computation precisely.
1977       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1978       break;
1979     case ICmpInst::ICMP_ULT:
1980       switch (pred) {
1981       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1982         Result = 1; break;
1983       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1984         Result = 0; break;
1985       }
1986       break;
1987     case ICmpInst::ICMP_SLT:
1988       switch (pred) {
1989       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1990         Result = 1; break;
1991       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1992         Result = 0; break;
1993       }
1994       break;
1995     case ICmpInst::ICMP_UGT:
1996       switch (pred) {
1997       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1998         Result = 1; break;
1999       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
2000         Result = 0; break;
2001       }
2002       break;
2003     case ICmpInst::ICMP_SGT:
2004       switch (pred) {
2005       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
2006         Result = 1; break;
2007       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
2008         Result = 0; break;
2009       }
2010       break;
2011     case ICmpInst::ICMP_ULE:
2012       if (pred == ICmpInst::ICMP_UGT) Result = 0;
2013       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
2014       break;
2015     case ICmpInst::ICMP_SLE:
2016       if (pred == ICmpInst::ICMP_SGT) Result = 0;
2017       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2018       break;
2019     case ICmpInst::ICMP_UGE:
2020       if (pred == ICmpInst::ICMP_ULT) Result = 0;
2021       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2022       break;
2023     case ICmpInst::ICMP_SGE:
2024       if (pred == ICmpInst::ICMP_SLT) Result = 0;
2025       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2026       break;
2027     case ICmpInst::ICMP_NE:
2028       if (pred == ICmpInst::ICMP_EQ) Result = 0;
2029       if (pred == ICmpInst::ICMP_NE) Result = 1;
2030       break;
2031     }
2032
2033     // If we evaluated the result, return it now.
2034     if (Result != -1)
2035       return ConstantInt::get(ResultTy, Result);
2036
2037     // If the right hand side is a bitcast, try using its inverse to simplify
2038     // it by moving it to the left hand side.  We can't do this if it would turn
2039     // a vector compare into a scalar compare or visa versa.
2040     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2041       Constant *CE2Op0 = CE2->getOperand(0);
2042       if (CE2->getOpcode() == Instruction::BitCast &&
2043           isa<VectorType>(CE2->getType())==isa<VectorType>(CE2Op0->getType())) {
2044         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2045         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2046       }
2047     }
2048
2049     // If the left hand side is an extension, try eliminating it.
2050     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2051       if (CE1->getOpcode() == Instruction::SExt ||
2052           CE1->getOpcode() == Instruction::ZExt) {
2053         Constant *CE1Op0 = CE1->getOperand(0);
2054         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2055         if (CE1Inverse == CE1Op0) {
2056           // Check whether we can safely truncate the right hand side.
2057           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2058           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2059             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2060           }
2061         }
2062       }
2063     }
2064
2065     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2066         (C1->isNullValue() && !C2->isNullValue())) {
2067       // If C2 is a constant expr and C1 isn't, flip them around and fold the
2068       // other way if possible.
2069       // Also, if C1 is null and C2 isn't, flip them around.
2070       switch (pred) {
2071       case ICmpInst::ICMP_EQ:
2072       case ICmpInst::ICMP_NE:
2073         // No change of predicate required.
2074         return ConstantExpr::getICmp(pred, C2, C1);
2075
2076       case ICmpInst::ICMP_ULT:
2077       case ICmpInst::ICMP_SLT:
2078       case ICmpInst::ICMP_UGT:
2079       case ICmpInst::ICMP_SGT:
2080       case ICmpInst::ICMP_ULE:
2081       case ICmpInst::ICMP_SLE:
2082       case ICmpInst::ICMP_UGE:
2083       case ICmpInst::ICMP_SGE:
2084         // Change the predicate as necessary to swap the operands.
2085         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2086         return ConstantExpr::getICmp(pred, C2, C1);
2087
2088       default:  // These predicates cannot be flopped around.
2089         break;
2090       }
2091     }
2092   }
2093   return 0;
2094 }
2095
2096 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2097 /// is "inbounds".
2098 static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
2099   // No indices means nothing that could be out of bounds.
2100   if (NumIdx == 0) return true;
2101
2102   // If the first index is zero, it's in bounds.
2103   if (Idxs[0]->isNullValue()) return true;
2104
2105   // If the first index is one and all the rest are zero, it's in bounds,
2106   // by the one-past-the-end rule.
2107   if (!cast<ConstantInt>(Idxs[0])->isOne())
2108     return false;
2109   for (unsigned i = 1, e = NumIdx; i != e; ++i)
2110     if (!Idxs[i]->isNullValue())
2111       return false;
2112   return true;
2113 }
2114
2115 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2116                                           bool inBounds,
2117                                           Constant* const *Idxs,
2118                                           unsigned NumIdx) {
2119   if (NumIdx == 0 ||
2120       (NumIdx == 1 && Idxs[0]->isNullValue()))
2121     return C;
2122
2123   if (isa<UndefValue>(C)) {
2124     const PointerType *Ptr = cast<PointerType>(C->getType());
2125     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2126                                                        (Value **)Idxs,
2127                                                        (Value **)Idxs+NumIdx);
2128     assert(Ty != 0 && "Invalid indices for GEP!");
2129     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2130   }
2131
2132   Constant *Idx0 = Idxs[0];
2133   if (C->isNullValue()) {
2134     bool isNull = true;
2135     for (unsigned i = 0, e = NumIdx; i != e; ++i)
2136       if (!Idxs[i]->isNullValue()) {
2137         isNull = false;
2138         break;
2139       }
2140     if (isNull) {
2141       const PointerType *Ptr = cast<PointerType>(C->getType());
2142       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
2143                                                          (Value**)Idxs,
2144                                                          (Value**)Idxs+NumIdx);
2145       assert(Ty != 0 && "Invalid indices for GEP!");
2146       return  ConstantPointerNull::get(
2147                             PointerType::get(Ty,Ptr->getAddressSpace()));
2148     }
2149   }
2150
2151   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2152     // Combine Indices - If the source pointer to this getelementptr instruction
2153     // is a getelementptr instruction, combine the indices of the two
2154     // getelementptr instructions into a single instruction.
2155     //
2156     if (CE->getOpcode() == Instruction::GetElementPtr) {
2157       const Type *LastTy = 0;
2158       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2159            I != E; ++I)
2160         LastTy = *I;
2161
2162       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
2163         SmallVector<Value*, 16> NewIndices;
2164         NewIndices.reserve(NumIdx + CE->getNumOperands());
2165         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2166           NewIndices.push_back(CE->getOperand(i));
2167
2168         // Add the last index of the source with the first index of the new GEP.
2169         // Make sure to handle the case when they are actually different types.
2170         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2171         // Otherwise it must be an array.
2172         if (!Idx0->isNullValue()) {
2173           const Type *IdxTy = Combined->getType();
2174           if (IdxTy != Idx0->getType()) {
2175             const Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2176             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2177             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2178             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2179           } else {
2180             Combined =
2181               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2182           }
2183         }
2184
2185         NewIndices.push_back(Combined);
2186         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
2187         return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2188           ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2189                                                  &NewIndices[0],
2190                                                  NewIndices.size()) :
2191           ConstantExpr::getGetElementPtr(CE->getOperand(0),
2192                                          &NewIndices[0],
2193                                          NewIndices.size());
2194       }
2195     }
2196
2197     // Implement folding of:
2198     //    int* getelementptr ([2 x int]* bitcast ([3 x int]* %X to [2 x int]*),
2199     //                        long 0, long 0)
2200     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2201     //
2202     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
2203       if (const PointerType *SPT =
2204           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2205         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2206           if (const ArrayType *CAT =
2207         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2208             if (CAT->getElementType() == SAT->getElementType())
2209               return inBounds ?
2210                 ConstantExpr::getInBoundsGetElementPtr(
2211                       (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2212                 ConstantExpr::getGetElementPtr(
2213                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
2214     }
2215   }
2216
2217   // Check to see if any array indices are not within the corresponding
2218   // notional array bounds. If so, try to determine if they can be factored
2219   // out into preceding dimensions.
2220   bool Unknown = false;
2221   SmallVector<Constant *, 8> NewIdxs;
2222   const Type *Ty = C->getType();
2223   const Type *Prev = 0;
2224   for (unsigned i = 0; i != NumIdx;
2225        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2226     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2227       if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2228         if (ATy->getNumElements() <= INT64_MAX &&
2229             ATy->getNumElements() != 0 &&
2230             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2231           if (isa<SequentialType>(Prev)) {
2232             // It's out of range, but we can factor it into the prior
2233             // dimension.
2234             NewIdxs.resize(NumIdx);
2235             ConstantInt *Factor = ConstantInt::get(CI->getType(),
2236                                                    ATy->getNumElements());
2237             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2238
2239             Constant *PrevIdx = Idxs[i-1];
2240             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2241
2242             // Before adding, extend both operands to i64 to avoid
2243             // overflow trouble.
2244             if (!PrevIdx->getType()->isInteger(64))
2245               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2246                                            Type::getInt64Ty(Div->getContext()));
2247             if (!Div->getType()->isInteger(64))
2248               Div = ConstantExpr::getSExt(Div,
2249                                           Type::getInt64Ty(Div->getContext()));
2250
2251             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2252           } else {
2253             // It's out of range, but the prior dimension is a struct
2254             // so we can't do anything about it.
2255             Unknown = true;
2256           }
2257         }
2258     } else {
2259       // We don't know if it's in range or not.
2260       Unknown = true;
2261     }
2262   }
2263
2264   // If we did any factoring, start over with the adjusted indices.
2265   if (!NewIdxs.empty()) {
2266     for (unsigned i = 0; i != NumIdx; ++i)
2267       if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2268     return inBounds ?
2269       ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2270                                              NewIdxs.size()) :
2271       ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
2272   }
2273
2274   // If all indices are known integers and normalized, we can do a simple
2275   // check for the "inbounds" property.
2276   if (!Unknown && !inBounds &&
2277       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
2278     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
2279
2280   return 0;
2281 }