Fix 'fcmp one' constant folding. Noticed by inspection.
[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 (ElTy->isPointerTy()) 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->isIntegerTy())
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->isFloatingPointTy())
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(C->getType()->isIntegerTy() &&
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 = 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
338   if (const StructType *STy = dyn_cast<StructType>(Ty))
339     if (!STy->isPacked()) {
340       unsigned NumElems = STy->getNumElements();
341       // An empty struct has size zero.
342       if (NumElems == 0)
343         return ConstantExpr::getNullValue(DestTy);
344       // Check for a struct with all members having the same size.
345       Constant *MemberSize =
346         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
347       bool AllSame = true;
348       for (unsigned i = 1; i != NumElems; ++i)
349         if (MemberSize !=
350             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
351           AllSame = false;
352           break;
353         }
354       if (AllSame) {
355         Constant *N = ConstantInt::get(DestTy, NumElems);
356         return ConstantExpr::getNUWMul(MemberSize, N);
357       }
358     }
359
360   // Pointer size doesn't depend on the pointee type, so canonicalize them
361   // to an arbitrary pointee.
362   if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
363     if (!PTy->getElementType()->isIntegerTy(1))
364       return
365         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
366                                          PTy->getAddressSpace()),
367                         DestTy, true);
368
369   // If there's no interesting folding happening, bail so that we don't create
370   // a constant that looks like it needs folding but really doesn't.
371   if (!Folded)
372     return 0;
373
374   // Base case: Get a regular sizeof expression.
375   Constant *C = ConstantExpr::getSizeOf(Ty);
376   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
377                                                     DestTy, false),
378                             C, DestTy);
379   return C;
380 }
381
382 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
383 /// on Ty, with any known factors factored out. If Folded is false,
384 /// return null if no factoring was possible, to avoid endlessly
385 /// bouncing an unfoldable expression back into the top-level folder.
386 ///
387 static Constant *getFoldedAlignOf(const Type *Ty, const Type *DestTy,
388                                   bool Folded) {
389   // The alignment of an array is equal to the alignment of the
390   // array element. Note that this is not always true for vectors.
391   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
392     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
393     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
394                                                       DestTy,
395                                                       false),
396                               C, DestTy);
397     return C;
398   }
399
400   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
401     // Packed structs always have an alignment of 1.
402     if (STy->isPacked())
403       return ConstantInt::get(DestTy, 1);
404
405     // Otherwise, struct alignment is the maximum alignment of any member.
406     // Without target data, we can't compare much, but we can check to see
407     // if all the members have the same alignment.
408     unsigned NumElems = STy->getNumElements();
409     // An empty struct has minimal alignment.
410     if (NumElems == 0)
411       return ConstantInt::get(DestTy, 1);
412     // Check for a struct with all members having the same alignment.
413     Constant *MemberAlign =
414       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
415     bool AllSame = true;
416     for (unsigned i = 1; i != NumElems; ++i)
417       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
418         AllSame = false;
419         break;
420       }
421     if (AllSame)
422       return MemberAlign;
423   }
424
425   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
426   // to an arbitrary pointee.
427   if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
428     if (!PTy->getElementType()->isIntegerTy(1))
429       return
430         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
431                                                            1),
432                                           PTy->getAddressSpace()),
433                          DestTy, true);
434
435   // If there's no interesting folding happening, bail so that we don't create
436   // a constant that looks like it needs folding but really doesn't.
437   if (!Folded)
438     return 0;
439
440   // Base case: Get a regular alignof expression.
441   Constant *C = ConstantExpr::getAlignOf(Ty);
442   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
443                                                     DestTy, false),
444                             C, DestTy);
445   return C;
446 }
447
448 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
449 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
450 /// return null if no factoring was possible, to avoid endlessly
451 /// bouncing an unfoldable expression back into the top-level folder.
452 ///
453 static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
454                                    const Type *DestTy,
455                                    bool Folded) {
456   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
457     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
458                                                                 DestTy, false),
459                                         FieldNo, DestTy);
460     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
461     return ConstantExpr::getNUWMul(E, N);
462   }
463
464   if (const StructType *STy = dyn_cast<StructType>(Ty))
465     if (!STy->isPacked()) {
466       unsigned NumElems = STy->getNumElements();
467       // An empty struct has no members.
468       if (NumElems == 0)
469         return 0;
470       // Check for a struct with all members having the same size.
471       Constant *MemberSize =
472         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
473       bool AllSame = true;
474       for (unsigned i = 1; i != NumElems; ++i)
475         if (MemberSize !=
476             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
477           AllSame = false;
478           break;
479         }
480       if (AllSame) {
481         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
482                                                                     false,
483                                                                     DestTy,
484                                                                     false),
485                                             FieldNo, DestTy);
486         return ConstantExpr::getNUWMul(MemberSize, N);
487       }
488     }
489
490   // If there's no interesting folding happening, bail so that we don't create
491   // a constant that looks like it needs folding but really doesn't.
492   if (!Folded)
493     return 0;
494
495   // Base case: Get a regular offsetof expression.
496   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
497   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
498                                                     DestTy, false),
499                             C, DestTy);
500   return C;
501 }
502
503 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
504                                             const Type *DestTy) {
505   if (isa<UndefValue>(V)) {
506     // zext(undef) = 0, because the top bits will be zero.
507     // sext(undef) = 0, because the top bits will all be the same.
508     // [us]itofp(undef) = 0, because the result value is bounded.
509     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
510         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
511       return Constant::getNullValue(DestTy);
512     return UndefValue::get(DestTy);
513   }
514
515   // No compile-time operations on this type yet.
516   if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
517     return 0;
518
519   if (V->isNullValue() && !DestTy->isX86_MMXTy())
520     return Constant::getNullValue(DestTy);
521
522   // If the cast operand is a constant expression, there's a few things we can
523   // do to try to simplify it.
524   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
525     if (CE->isCast()) {
526       // Try hard to fold cast of cast because they are often eliminable.
527       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
528         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
529     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
530       // If all of the indexes in the GEP are null values, there is no pointer
531       // adjustment going on.  We might as well cast the source pointer.
532       bool isAllNull = true;
533       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
534         if (!CE->getOperand(i)->isNullValue()) {
535           isAllNull = false;
536           break;
537         }
538       if (isAllNull)
539         // This is casting one pointer type to another, always BitCast
540         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
541     }
542   }
543
544   // If the cast operand is a constant vector, perform the cast by
545   // operating on each element. In the cast of bitcasts, the element
546   // count may be mismatched; don't attempt to handle that here.
547   if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
548     if (DestTy->isVectorTy() &&
549         cast<VectorType>(DestTy)->getNumElements() ==
550         CV->getType()->getNumElements()) {
551       std::vector<Constant*> res;
552       const VectorType *DestVecTy = cast<VectorType>(DestTy);
553       const Type *DstEltTy = DestVecTy->getElementType();
554       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
555         res.push_back(ConstantExpr::getCast(opc,
556                                             CV->getOperand(i), DstEltTy));
557       return ConstantVector::get(DestVecTy, res);
558     }
559
560   // We actually have to do a cast now. Perform the cast according to the
561   // opcode specified.
562   switch (opc) {
563   default:
564     llvm_unreachable("Failed to cast constant expression");
565   case Instruction::FPTrunc:
566   case Instruction::FPExt:
567     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
568       bool ignored;
569       APFloat Val = FPC->getValueAPF();
570       Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
571                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
572                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
573                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
574                   APFloat::Bogus,
575                   APFloat::rmNearestTiesToEven, &ignored);
576       return ConstantFP::get(V->getContext(), Val);
577     }
578     return 0; // Can't fold.
579   case Instruction::FPToUI: 
580   case Instruction::FPToSI:
581     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
582       const APFloat &V = FPC->getValueAPF();
583       bool ignored;
584       uint64_t x[2]; 
585       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
586       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
587                                 APFloat::rmTowardZero, &ignored);
588       APInt Val(DestBitWidth, 2, x);
589       return ConstantInt::get(FPC->getContext(), Val);
590     }
591     return 0; // Can't fold.
592   case Instruction::IntToPtr:   //always treated as unsigned
593     if (V->isNullValue())       // Is it an integral null value?
594       return ConstantPointerNull::get(cast<PointerType>(DestTy));
595     return 0;                   // Other pointer types cannot be casted
596   case Instruction::PtrToInt:   // always treated as unsigned
597     // Is it a null pointer value?
598     if (V->isNullValue())
599       return ConstantInt::get(DestTy, 0);
600     // If this is a sizeof-like expression, pull out multiplications by
601     // known factors to expose them to subsequent folding. If it's an
602     // alignof-like expression, factor out known factors.
603     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
604       if (CE->getOpcode() == Instruction::GetElementPtr &&
605           CE->getOperand(0)->isNullValue()) {
606         const Type *Ty =
607           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
608         if (CE->getNumOperands() == 2) {
609           // Handle a sizeof-like expression.
610           Constant *Idx = CE->getOperand(1);
611           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
612           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
613             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
614                                                                 DestTy, false),
615                                         Idx, DestTy);
616             return ConstantExpr::getMul(C, Idx);
617           }
618         } else if (CE->getNumOperands() == 3 &&
619                    CE->getOperand(1)->isNullValue()) {
620           // Handle an alignof-like expression.
621           if (const StructType *STy = dyn_cast<StructType>(Ty))
622             if (!STy->isPacked()) {
623               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
624               if (CI->isOne() &&
625                   STy->getNumElements() == 2 &&
626                   STy->getElementType(0)->isIntegerTy(1)) {
627                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
628               }
629             }
630           // Handle an offsetof-like expression.
631           if (Ty->isStructTy() || Ty->isArrayTy()) {
632             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
633                                                 DestTy, false))
634               return C;
635           }
636         }
637       }
638     // Other pointer types cannot be casted
639     return 0;
640   case Instruction::UIToFP:
641   case Instruction::SIToFP:
642     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
643       APInt api = CI->getValue();
644       APFloat apf(APInt::getNullValue(DestTy->getPrimitiveSizeInBits()), true);
645       (void)apf.convertFromAPInt(api, 
646                                  opc==Instruction::SIToFP,
647                                  APFloat::rmNearestTiesToEven);
648       return ConstantFP::get(V->getContext(), apf);
649     }
650     return 0;
651   case Instruction::ZExt:
652     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
653       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
654       return ConstantInt::get(V->getContext(),
655                               CI->getValue().zext(BitWidth));
656     }
657     return 0;
658   case Instruction::SExt:
659     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
660       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
661       return ConstantInt::get(V->getContext(),
662                               CI->getValue().sext(BitWidth));
663     }
664     return 0;
665   case Instruction::Trunc: {
666     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
667     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
668       return ConstantInt::get(V->getContext(),
669                               CI->getValue().trunc(DestBitWidth));
670     }
671     
672     // The input must be a constantexpr.  See if we can simplify this based on
673     // the bytes we are demanding.  Only do this if the source and dest are an
674     // even multiple of a byte.
675     if ((DestBitWidth & 7) == 0 &&
676         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
677       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
678         return Res;
679       
680     return 0;
681   }
682   case Instruction::BitCast:
683     return FoldBitCast(V, DestTy);
684   }
685 }
686
687 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
688                                               Constant *V1, Constant *V2) {
689   if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
690     return CB->getZExtValue() ? V1 : V2;
691
692   if (isa<UndefValue>(V1)) return V2;
693   if (isa<UndefValue>(V2)) return V1;
694   if (isa<UndefValue>(Cond)) return V1;
695   if (V1 == V2) return V1;
696
697   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
698     if (TrueVal->getOpcode() == Instruction::Select)
699       if (TrueVal->getOperand(0) == Cond)
700         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
701   }
702   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
703     if (FalseVal->getOpcode() == Instruction::Select)
704       if (FalseVal->getOperand(0) == Cond)
705         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
706   }
707
708   return 0;
709 }
710
711 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
712                                                       Constant *Idx) {
713   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
714     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
715   if (Val->isNullValue())  // ee(zero, x) -> zero
716     return Constant::getNullValue(
717                           cast<VectorType>(Val->getType())->getElementType());
718
719   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
720     if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
721       return CVal->getOperand(CIdx->getZExtValue());
722     } else if (isa<UndefValue>(Idx)) {
723       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
724       return CVal->getOperand(0);
725     }
726   }
727   return 0;
728 }
729
730 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
731                                                      Constant *Elt,
732                                                      Constant *Idx) {
733   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
734   if (!CIdx) return 0;
735   APInt idxVal = CIdx->getValue();
736   if (isa<UndefValue>(Val)) { 
737     // Insertion of scalar constant into vector undef
738     // Optimize away insertion of undef
739     if (isa<UndefValue>(Elt))
740       return Val;
741     // Otherwise break the aggregate undef into multiple undefs and do
742     // the insertion
743     unsigned numOps = 
744       cast<VectorType>(Val->getType())->getNumElements();
745     std::vector<Constant*> Ops; 
746     Ops.reserve(numOps);
747     for (unsigned i = 0; i < numOps; ++i) {
748       Constant *Op =
749         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
750       Ops.push_back(Op);
751     }
752     return ConstantVector::get(Ops);
753   }
754   if (isa<ConstantAggregateZero>(Val)) {
755     // Insertion of scalar constant into vector aggregate zero
756     // Optimize away insertion of zero
757     if (Elt->isNullValue())
758       return Val;
759     // Otherwise break the aggregate zero into multiple zeros and do
760     // the insertion
761     unsigned numOps = 
762       cast<VectorType>(Val->getType())->getNumElements();
763     std::vector<Constant*> Ops; 
764     Ops.reserve(numOps);
765     for (unsigned i = 0; i < numOps; ++i) {
766       Constant *Op =
767         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
768       Ops.push_back(Op);
769     }
770     return ConstantVector::get(Ops);
771   }
772   if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
773     // Insertion of scalar constant into vector constant
774     std::vector<Constant*> Ops; 
775     Ops.reserve(CVal->getNumOperands());
776     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
777       Constant *Op =
778         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
779       Ops.push_back(Op);
780     }
781     return ConstantVector::get(Ops);
782   }
783
784   return 0;
785 }
786
787 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
788 /// return the specified element value.  Otherwise return null.
789 static Constant *GetVectorElement(Constant *C, unsigned EltNo) {
790   if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
791     return CV->getOperand(EltNo);
792
793   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
794   if (isa<ConstantAggregateZero>(C))
795     return Constant::getNullValue(EltTy);
796   if (isa<UndefValue>(C))
797     return UndefValue::get(EltTy);
798   return 0;
799 }
800
801 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
802                                                      Constant *V2,
803                                                      Constant *Mask) {
804   // Undefined shuffle mask -> undefined value.
805   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
806
807   unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
808   unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
809   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
810
811   // Loop over the shuffle mask, evaluating each element.
812   SmallVector<Constant*, 32> Result;
813   for (unsigned i = 0; i != MaskNumElts; ++i) {
814     Constant *InElt = GetVectorElement(Mask, i);
815     if (InElt == 0) return 0;
816
817     if (isa<UndefValue>(InElt))
818       InElt = UndefValue::get(EltTy);
819     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
820       unsigned Elt = CI->getZExtValue();
821       if (Elt >= SrcNumElts*2)
822         InElt = UndefValue::get(EltTy);
823       else if (Elt >= SrcNumElts)
824         InElt = GetVectorElement(V2, Elt - SrcNumElts);
825       else
826         InElt = GetVectorElement(V1, Elt);
827       if (InElt == 0) return 0;
828     } else {
829       // Unknown value.
830       return 0;
831     }
832     Result.push_back(InElt);
833   }
834
835   return ConstantVector::get(&Result[0], Result.size());
836 }
837
838 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
839                                                     const unsigned *Idxs,
840                                                     unsigned NumIdx) {
841   // Base case: no indices, so return the entire value.
842   if (NumIdx == 0)
843     return Agg;
844
845   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
846     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
847                                                             Idxs,
848                                                             Idxs + NumIdx));
849
850   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
851     return
852       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
853                                                               Idxs,
854                                                               Idxs + NumIdx));
855
856   // Otherwise recurse.
857   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
858     return ConstantFoldExtractValueInstruction(CS->getOperand(*Idxs),
859                                                Idxs+1, NumIdx-1);
860
861   if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
862     return ConstantFoldExtractValueInstruction(CA->getOperand(*Idxs),
863                                                Idxs+1, NumIdx-1);
864   ConstantVector *CV = cast<ConstantVector>(Agg);
865   return ConstantFoldExtractValueInstruction(CV->getOperand(*Idxs),
866                                              Idxs+1, NumIdx-1);
867 }
868
869 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
870                                                    Constant *Val,
871                                                    const unsigned *Idxs,
872                                                    unsigned NumIdx) {
873   // Base case: no indices, so replace the entire value.
874   if (NumIdx == 0)
875     return Val;
876
877   if (isa<UndefValue>(Agg)) {
878     // Insertion of constant into aggregate undef
879     // Optimize away insertion of undef.
880     if (isa<UndefValue>(Val))
881       return Agg;
882     
883     // Otherwise break the aggregate undef into multiple undefs and do
884     // the insertion.
885     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
886     unsigned numOps;
887     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
888       numOps = AR->getNumElements();
889     else
890       numOps = cast<StructType>(AggTy)->getNumElements();
891     
892     std::vector<Constant*> Ops(numOps); 
893     for (unsigned i = 0; i < numOps; ++i) {
894       const Type *MemberTy = AggTy->getTypeAtIndex(i);
895       Constant *Op =
896         (*Idxs == i) ?
897         ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
898                                            Val, Idxs+1, NumIdx-1) :
899         UndefValue::get(MemberTy);
900       Ops[i] = Op;
901     }
902     
903     if (const StructType* ST = dyn_cast<StructType>(AggTy))
904       return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
905     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
906   }
907   
908   if (isa<ConstantAggregateZero>(Agg)) {
909     // Insertion of constant into aggregate zero
910     // Optimize away insertion of zero.
911     if (Val->isNullValue())
912       return Agg;
913     
914     // Otherwise break the aggregate zero into multiple zeros and do
915     // the insertion.
916     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
917     unsigned numOps;
918     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
919       numOps = AR->getNumElements();
920     else
921       numOps = cast<StructType>(AggTy)->getNumElements();
922     
923     std::vector<Constant*> Ops(numOps);
924     for (unsigned i = 0; i < numOps; ++i) {
925       const Type *MemberTy = AggTy->getTypeAtIndex(i);
926       Constant *Op =
927         (*Idxs == i) ?
928         ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
929                                            Val, Idxs+1, NumIdx-1) :
930         Constant::getNullValue(MemberTy);
931       Ops[i] = Op;
932     }
933     
934     if (const StructType *ST = dyn_cast<StructType>(AggTy))
935       return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
936     return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
937   }
938   
939   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
940     // Insertion of constant into aggregate constant.
941     std::vector<Constant*> Ops(Agg->getNumOperands());
942     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
943       Constant *Op = cast<Constant>(Agg->getOperand(i));
944       if (*Idxs == i)
945         Op = ConstantFoldInsertValueInstruction(Op, Val, Idxs+1, NumIdx-1);
946       Ops[i] = Op;
947     }
948     
949     if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
950       return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
951     return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
952   }
953
954   return 0;
955 }
956
957
958 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
959                                               Constant *C1, Constant *C2) {
960   // No compile-time operations on this type yet.
961   if (C1->getType()->isPPC_FP128Ty())
962     return 0;
963
964   // Handle UndefValue up front.
965   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
966     switch (Opcode) {
967     case Instruction::Xor:
968       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
969         // Handle undef ^ undef -> 0 special case. This is a common
970         // idiom (misuse).
971         return Constant::getNullValue(C1->getType());
972       // Fallthrough
973     case Instruction::Add:
974     case Instruction::Sub:
975       return UndefValue::get(C1->getType());
976     case Instruction::Mul:
977     case Instruction::And:
978       return Constant::getNullValue(C1->getType());
979     case Instruction::UDiv:
980     case Instruction::SDiv:
981     case Instruction::URem:
982     case Instruction::SRem:
983       if (!isa<UndefValue>(C2))                    // undef / X -> 0
984         return Constant::getNullValue(C1->getType());
985       return C2;                                   // X / undef -> undef
986     case Instruction::Or:                          // X | undef -> -1
987       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
988         return Constant::getAllOnesValue(PTy);
989       return Constant::getAllOnesValue(C1->getType());
990     case Instruction::LShr:
991       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
992         return C1;                                  // undef lshr undef -> undef
993       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
994                                                     // undef lshr X -> 0
995     case Instruction::AShr:
996       if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
997         return Constant::getAllOnesValue(C1->getType());
998       else if (isa<UndefValue>(C1)) 
999         return C1;                                  // undef ashr undef -> undef
1000       else
1001         return C1;                                  // X ashr undef --> X
1002     case Instruction::Shl:
1003       // undef << X -> 0   or   X << undef -> 0
1004       return Constant::getNullValue(C1->getType());
1005     }
1006   }
1007
1008   // Handle simplifications when the RHS is a constant int.
1009   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1010     switch (Opcode) {
1011     case Instruction::Add:
1012       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
1013       break;
1014     case Instruction::Sub:
1015       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
1016       break;
1017     case Instruction::Mul:
1018       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
1019       if (CI2->equalsInt(1))
1020         return C1;                                              // X * 1 == X
1021       break;
1022     case Instruction::UDiv:
1023     case Instruction::SDiv:
1024       if (CI2->equalsInt(1))
1025         return C1;                                            // X / 1 == X
1026       if (CI2->equalsInt(0))
1027         return UndefValue::get(CI2->getType());               // X / 0 == undef
1028       break;
1029     case Instruction::URem:
1030     case Instruction::SRem:
1031       if (CI2->equalsInt(1))
1032         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
1033       if (CI2->equalsInt(0))
1034         return UndefValue::get(CI2->getType());               // X % 0 == undef
1035       break;
1036     case Instruction::And:
1037       if (CI2->isZero()) return C2;                           // X & 0 == 0
1038       if (CI2->isAllOnesValue())
1039         return C1;                                            // X & -1 == X
1040
1041       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1042         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1043         if (CE1->getOpcode() == Instruction::ZExt) {
1044           unsigned DstWidth = CI2->getType()->getBitWidth();
1045           unsigned SrcWidth =
1046             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1047           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1048           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1049             return C1;
1050         }
1051
1052         // If and'ing the address of a global with a constant, fold it.
1053         if (CE1->getOpcode() == Instruction::PtrToInt && 
1054             isa<GlobalValue>(CE1->getOperand(0))) {
1055           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1056
1057           // Functions are at least 4-byte aligned.
1058           unsigned GVAlign = GV->getAlignment();
1059           if (isa<Function>(GV))
1060             GVAlign = std::max(GVAlign, 4U);
1061
1062           if (GVAlign > 1) {
1063             unsigned DstWidth = CI2->getType()->getBitWidth();
1064             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1065             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1066
1067             // If checking bits we know are clear, return zero.
1068             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1069               return Constant::getNullValue(CI2->getType());
1070           }
1071         }
1072       }
1073       break;
1074     case Instruction::Or:
1075       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1076       if (CI2->isAllOnesValue())
1077         return C2;                         // X | -1 == -1
1078       break;
1079     case Instruction::Xor:
1080       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1081
1082       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1083         switch (CE1->getOpcode()) {
1084         default: break;
1085         case Instruction::ICmp:
1086         case Instruction::FCmp:
1087           // cmp pred ^ true -> cmp !pred
1088           assert(CI2->equalsInt(1));
1089           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1090           pred = CmpInst::getInversePredicate(pred);
1091           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1092                                           CE1->getOperand(1));
1093         }
1094       }
1095       break;
1096     case Instruction::AShr:
1097       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1098       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1099         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1100           return ConstantExpr::getLShr(C1, C2);
1101       break;
1102     }
1103   } else if (isa<ConstantInt>(C1)) {
1104     // If C1 is a ConstantInt and C2 is not, swap the operands.
1105     if (Instruction::isCommutative(Opcode))
1106       return ConstantExpr::get(Opcode, C2, C1);
1107   }
1108
1109   // At this point we know neither constant is an UndefValue.
1110   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1111     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1112       using namespace APIntOps;
1113       const APInt &C1V = CI1->getValue();
1114       const APInt &C2V = CI2->getValue();
1115       switch (Opcode) {
1116       default:
1117         break;
1118       case Instruction::Add:     
1119         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1120       case Instruction::Sub:     
1121         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1122       case Instruction::Mul:     
1123         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1124       case Instruction::UDiv:
1125         assert(!CI2->isNullValue() && "Div by zero handled above");
1126         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1127       case Instruction::SDiv:
1128         assert(!CI2->isNullValue() && "Div by zero handled above");
1129         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1130           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1131         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1132       case Instruction::URem:
1133         assert(!CI2->isNullValue() && "Div by zero handled above");
1134         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1135       case Instruction::SRem:
1136         assert(!CI2->isNullValue() && "Div by zero handled above");
1137         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1138           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1139         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1140       case Instruction::And:
1141         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1142       case Instruction::Or:
1143         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1144       case Instruction::Xor:
1145         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1146       case Instruction::Shl: {
1147         uint32_t shiftAmt = C2V.getZExtValue();
1148         if (shiftAmt < C1V.getBitWidth())
1149           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1150         else
1151           return UndefValue::get(C1->getType()); // too big shift is undef
1152       }
1153       case Instruction::LShr: {
1154         uint32_t shiftAmt = C2V.getZExtValue();
1155         if (shiftAmt < C1V.getBitWidth())
1156           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1157         else
1158           return UndefValue::get(C1->getType()); // too big shift is undef
1159       }
1160       case Instruction::AShr: {
1161         uint32_t shiftAmt = C2V.getZExtValue();
1162         if (shiftAmt < C1V.getBitWidth())
1163           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1164         else
1165           return UndefValue::get(C1->getType()); // too big shift is undef
1166       }
1167       }
1168     }
1169
1170     switch (Opcode) {
1171     case Instruction::SDiv:
1172     case Instruction::UDiv:
1173     case Instruction::URem:
1174     case Instruction::SRem:
1175     case Instruction::LShr:
1176     case Instruction::AShr:
1177     case Instruction::Shl:
1178       if (CI1->equalsInt(0)) return C1;
1179       break;
1180     default:
1181       break;
1182     }
1183   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1184     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1185       APFloat C1V = CFP1->getValueAPF();
1186       APFloat C2V = CFP2->getValueAPF();
1187       APFloat C3V = C1V;  // copy for modification
1188       switch (Opcode) {
1189       default:                   
1190         break;
1191       case Instruction::FAdd:
1192         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1193         return ConstantFP::get(C1->getContext(), C3V);
1194       case Instruction::FSub:
1195         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1196         return ConstantFP::get(C1->getContext(), C3V);
1197       case Instruction::FMul:
1198         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1199         return ConstantFP::get(C1->getContext(), C3V);
1200       case Instruction::FDiv:
1201         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1202         return ConstantFP::get(C1->getContext(), C3V);
1203       case Instruction::FRem:
1204         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1205         return ConstantFP::get(C1->getContext(), C3V);
1206       }
1207     }
1208   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1209     ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1210     ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
1211     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1212         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
1213       std::vector<Constant*> Res;
1214       const Type* EltTy = VTy->getElementType();  
1215       Constant *C1 = 0;
1216       Constant *C2 = 0;
1217       switch (Opcode) {
1218       default:
1219         break;
1220       case Instruction::Add:
1221         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1222           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1223           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1224           Res.push_back(ConstantExpr::getAdd(C1, C2));
1225         }
1226         return ConstantVector::get(Res);
1227       case Instruction::FAdd:
1228         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1229           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1230           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1231           Res.push_back(ConstantExpr::getFAdd(C1, C2));
1232         }
1233         return ConstantVector::get(Res);
1234       case Instruction::Sub:
1235         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1236           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1237           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1238           Res.push_back(ConstantExpr::getSub(C1, C2));
1239         }
1240         return ConstantVector::get(Res);
1241       case Instruction::FSub:
1242         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1243           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1244           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1245           Res.push_back(ConstantExpr::getFSub(C1, C2));
1246         }
1247         return ConstantVector::get(Res);
1248       case Instruction::Mul:
1249         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1250           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1251           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1252           Res.push_back(ConstantExpr::getMul(C1, C2));
1253         }
1254         return ConstantVector::get(Res);
1255       case Instruction::FMul:
1256         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1257           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1258           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1259           Res.push_back(ConstantExpr::getFMul(C1, C2));
1260         }
1261         return ConstantVector::get(Res);
1262       case Instruction::UDiv:
1263         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1264           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1265           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1266           Res.push_back(ConstantExpr::getUDiv(C1, C2));
1267         }
1268         return ConstantVector::get(Res);
1269       case Instruction::SDiv:
1270         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1271           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1272           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1273           Res.push_back(ConstantExpr::getSDiv(C1, C2));
1274         }
1275         return ConstantVector::get(Res);
1276       case Instruction::FDiv:
1277         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1278           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1279           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1280           Res.push_back(ConstantExpr::getFDiv(C1, C2));
1281         }
1282         return ConstantVector::get(Res);
1283       case Instruction::URem:
1284         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1285           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1286           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1287           Res.push_back(ConstantExpr::getURem(C1, C2));
1288         }
1289         return ConstantVector::get(Res);
1290       case Instruction::SRem:
1291         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1292           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1293           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1294           Res.push_back(ConstantExpr::getSRem(C1, C2));
1295         }
1296         return ConstantVector::get(Res);
1297       case Instruction::FRem:
1298         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1299           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1300           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1301           Res.push_back(ConstantExpr::getFRem(C1, C2));
1302         }
1303         return ConstantVector::get(Res);
1304       case Instruction::And: 
1305         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1306           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1307           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1308           Res.push_back(ConstantExpr::getAnd(C1, C2));
1309         }
1310         return ConstantVector::get(Res);
1311       case Instruction::Or:
1312         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1313           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1314           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1315           Res.push_back(ConstantExpr::getOr(C1, C2));
1316         }
1317         return ConstantVector::get(Res);
1318       case Instruction::Xor:
1319         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1320           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1321           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1322           Res.push_back(ConstantExpr::getXor(C1, C2));
1323         }
1324         return ConstantVector::get(Res);
1325       case Instruction::LShr:
1326         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1327           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1328           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1329           Res.push_back(ConstantExpr::getLShr(C1, C2));
1330         }
1331         return ConstantVector::get(Res);
1332       case Instruction::AShr:
1333         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1334           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1335           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1336           Res.push_back(ConstantExpr::getAShr(C1, C2));
1337         }
1338         return ConstantVector::get(Res);
1339       case Instruction::Shl:
1340         for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1341           C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1342           C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
1343           Res.push_back(ConstantExpr::getShl(C1, C2));
1344         }
1345         return ConstantVector::get(Res);
1346       }
1347     }
1348   }
1349
1350   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1351     // There are many possible foldings we could do here.  We should probably
1352     // at least fold add of a pointer with an integer into the appropriate
1353     // getelementptr.  This will improve alias analysis a bit.
1354
1355     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1356     // (a + (b + c)).
1357     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1358       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1359       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1360         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1361     }
1362   } else if (isa<ConstantExpr>(C2)) {
1363     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1364     // other way if possible.
1365     if (Instruction::isCommutative(Opcode))
1366       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1367   }
1368
1369   // i1 can be simplified in many cases.
1370   if (C1->getType()->isIntegerTy(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 (Ty->isOpaqueTy()) 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()->isIntegerTy(64))
1437     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1438
1439   if (!C2->getType()->isIntegerTy(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           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
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     // For EQ and NE, we can always pick a value for the undef to make the
1792     // predicate pass or fail, so we can return undef.
1793     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)))
1794       return UndefValue::get(ResultTy);
1795     // Otherwise, pick the same value as the non-undef operand, and fold
1796     // it to true or false.
1797     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1798   }
1799
1800   // No compile-time operations on this type yet.
1801   if (C1->getType()->isPPC_FP128Ty())
1802     return 0;
1803
1804   // icmp eq/ne(null,GV) -> false/true
1805   if (C1->isNullValue()) {
1806     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1807       // Don't try to evaluate aliases.  External weak GV can be null.
1808       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1809         if (pred == ICmpInst::ICMP_EQ)
1810           return ConstantInt::getFalse(C1->getContext());
1811         else if (pred == ICmpInst::ICMP_NE)
1812           return ConstantInt::getTrue(C1->getContext());
1813       }
1814   // icmp eq/ne(GV,null) -> false/true
1815   } else if (C2->isNullValue()) {
1816     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1817       // Don't try to evaluate aliases.  External weak GV can be null.
1818       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1819         if (pred == ICmpInst::ICMP_EQ)
1820           return ConstantInt::getFalse(C1->getContext());
1821         else if (pred == ICmpInst::ICMP_NE)
1822           return ConstantInt::getTrue(C1->getContext());
1823       }
1824   }
1825
1826   // If the comparison is a comparison between two i1's, simplify it.
1827   if (C1->getType()->isIntegerTy(1)) {
1828     switch(pred) {
1829     case ICmpInst::ICMP_EQ:
1830       if (isa<ConstantInt>(C2))
1831         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1832       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1833     case ICmpInst::ICMP_NE:
1834       return ConstantExpr::getXor(C1, C2);
1835     default:
1836       break;
1837     }
1838   }
1839
1840   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1841     APInt V1 = cast<ConstantInt>(C1)->getValue();
1842     APInt V2 = cast<ConstantInt>(C2)->getValue();
1843     switch (pred) {
1844     default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
1845     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1846     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1847     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1848     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1849     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1850     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1851     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1852     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1853     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1854     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1855     }
1856   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1857     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1858     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1859     APFloat::cmpResult R = C1V.compare(C2V);
1860     switch (pred) {
1861     default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
1862     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1863     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1864     case FCmpInst::FCMP_UNO:
1865       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1866     case FCmpInst::FCMP_ORD:
1867       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1868     case FCmpInst::FCMP_UEQ:
1869       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1870                                         R==APFloat::cmpEqual);
1871     case FCmpInst::FCMP_OEQ:   
1872       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1873     case FCmpInst::FCMP_UNE:
1874       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1875     case FCmpInst::FCMP_ONE:   
1876       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1877                                         R==APFloat::cmpGreaterThan);
1878     case FCmpInst::FCMP_ULT: 
1879       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1880                                         R==APFloat::cmpLessThan);
1881     case FCmpInst::FCMP_OLT:   
1882       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1883     case FCmpInst::FCMP_UGT:
1884       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1885                                         R==APFloat::cmpGreaterThan);
1886     case FCmpInst::FCMP_OGT:
1887       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1888     case FCmpInst::FCMP_ULE:
1889       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1890     case FCmpInst::FCMP_OLE: 
1891       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1892                                         R==APFloat::cmpEqual);
1893     case FCmpInst::FCMP_UGE:
1894       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1895     case FCmpInst::FCMP_OGE: 
1896       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1897                                         R==APFloat::cmpEqual);
1898     }
1899   } else if (C1->getType()->isVectorTy()) {
1900     SmallVector<Constant*, 16> C1Elts, C2Elts;
1901     C1->getVectorElements(C1Elts);
1902     C2->getVectorElements(C2Elts);
1903     if (C1Elts.empty() || C2Elts.empty())
1904       return 0;
1905
1906     // If we can constant fold the comparison of each element, constant fold
1907     // the whole vector comparison.
1908     SmallVector<Constant*, 4> ResElts;
1909     for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1910       // Compare the elements, producing an i1 result or constant expr.
1911       ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
1912     }
1913     return ConstantVector::get(&ResElts[0], ResElts.size());
1914   }
1915
1916   if (C1->getType()->isFloatingPointTy()) {
1917     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1918     switch (evaluateFCmpRelation(C1, C2)) {
1919     default: llvm_unreachable("Unknown relation!");
1920     case FCmpInst::FCMP_UNO:
1921     case FCmpInst::FCMP_ORD:
1922     case FCmpInst::FCMP_UEQ:
1923     case FCmpInst::FCMP_UNE:
1924     case FCmpInst::FCMP_ULT:
1925     case FCmpInst::FCMP_UGT:
1926     case FCmpInst::FCMP_ULE:
1927     case FCmpInst::FCMP_UGE:
1928     case FCmpInst::FCMP_TRUE:
1929     case FCmpInst::FCMP_FALSE:
1930     case FCmpInst::BAD_FCMP_PREDICATE:
1931       break; // Couldn't determine anything about these constants.
1932     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1933       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1934                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1935                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1936       break;
1937     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1938       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1939                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1940                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1941       break;
1942     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1943       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1944                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1945                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1946       break;
1947     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1948       // We can only partially decide this relation.
1949       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1950         Result = 0;
1951       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1952         Result = 1;
1953       break;
1954     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1955       // We can only partially decide this relation.
1956       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1957         Result = 0;
1958       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1959         Result = 1;
1960       break;
1961     case FCmpInst::FCMP_ONE: // We know that C1 != C2
1962       // We can only partially decide this relation.
1963       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1964         Result = 0;
1965       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1966         Result = 1;
1967       break;
1968     }
1969
1970     // If we evaluated the result, return it now.
1971     if (Result != -1)
1972       return ConstantInt::get(ResultTy, Result);
1973
1974   } else {
1975     // Evaluate the relation between the two constants, per the predicate.
1976     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1977     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1978     default: llvm_unreachable("Unknown relational!");
1979     case ICmpInst::BAD_ICMP_PREDICATE:
1980       break;  // Couldn't determine anything about these constants.
1981     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1982       // If we know the constants are equal, we can decide the result of this
1983       // computation precisely.
1984       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1985       break;
1986     case ICmpInst::ICMP_ULT:
1987       switch (pred) {
1988       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1989         Result = 1; break;
1990       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1991         Result = 0; break;
1992       }
1993       break;
1994     case ICmpInst::ICMP_SLT:
1995       switch (pred) {
1996       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1997         Result = 1; break;
1998       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1999         Result = 0; break;
2000       }
2001       break;
2002     case ICmpInst::ICMP_UGT:
2003       switch (pred) {
2004       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
2005         Result = 1; break;
2006       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
2007         Result = 0; break;
2008       }
2009       break;
2010     case ICmpInst::ICMP_SGT:
2011       switch (pred) {
2012       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
2013         Result = 1; break;
2014       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
2015         Result = 0; break;
2016       }
2017       break;
2018     case ICmpInst::ICMP_ULE:
2019       if (pred == ICmpInst::ICMP_UGT) Result = 0;
2020       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
2021       break;
2022     case ICmpInst::ICMP_SLE:
2023       if (pred == ICmpInst::ICMP_SGT) Result = 0;
2024       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
2025       break;
2026     case ICmpInst::ICMP_UGE:
2027       if (pred == ICmpInst::ICMP_ULT) Result = 0;
2028       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
2029       break;
2030     case ICmpInst::ICMP_SGE:
2031       if (pred == ICmpInst::ICMP_SLT) Result = 0;
2032       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
2033       break;
2034     case ICmpInst::ICMP_NE:
2035       if (pred == ICmpInst::ICMP_EQ) Result = 0;
2036       if (pred == ICmpInst::ICMP_NE) Result = 1;
2037       break;
2038     }
2039
2040     // If we evaluated the result, return it now.
2041     if (Result != -1)
2042       return ConstantInt::get(ResultTy, Result);
2043
2044     // If the right hand side is a bitcast, try using its inverse to simplify
2045     // it by moving it to the left hand side.  We can't do this if it would turn
2046     // a vector compare into a scalar compare or visa versa.
2047     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
2048       Constant *CE2Op0 = CE2->getOperand(0);
2049       if (CE2->getOpcode() == Instruction::BitCast &&
2050           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
2051         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2052         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2053       }
2054     }
2055
2056     // If the left hand side is an extension, try eliminating it.
2057     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2058       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
2059           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
2060         Constant *CE1Op0 = CE1->getOperand(0);
2061         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2062         if (CE1Inverse == CE1Op0) {
2063           // Check whether we can safely truncate the right hand side.
2064           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2065           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2066             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2067           }
2068         }
2069       }
2070     }
2071
2072     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2073         (C1->isNullValue() && !C2->isNullValue())) {
2074       // If C2 is a constant expr and C1 isn't, flip them around and fold the
2075       // other way if possible.
2076       // Also, if C1 is null and C2 isn't, flip them around.
2077       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
2078       return ConstantExpr::getICmp(pred, C2, C1);
2079     }
2080   }
2081   return 0;
2082 }
2083
2084 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2085 /// is "inbounds".
2086 template<typename IndexTy>
2087 static bool isInBoundsIndices(IndexTy const *Idxs, size_t NumIdx) {
2088   // No indices means nothing that could be out of bounds.
2089   if (NumIdx == 0) return true;
2090
2091   // If the first index is zero, it's in bounds.
2092   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
2093
2094   // If the first index is one and all the rest are zero, it's in bounds,
2095   // by the one-past-the-end rule.
2096   if (!cast<ConstantInt>(Idxs[0])->isOne())
2097     return false;
2098   for (unsigned i = 1, e = NumIdx; i != e; ++i)
2099     if (!cast<Constant>(Idxs[i])->isNullValue())
2100       return false;
2101   return true;
2102 }
2103
2104 template<typename IndexTy>
2105 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
2106                                                bool inBounds,
2107                                                IndexTy const *Idxs,
2108                                                unsigned NumIdx) {
2109   Constant *Idx0 = cast<Constant>(Idxs[0]);
2110   if (NumIdx == 0 ||
2111       (NumIdx == 1 && Idx0->isNullValue()))
2112     return C;
2113
2114   if (isa<UndefValue>(C)) {
2115     const PointerType *Ptr = cast<PointerType>(C->getType());
2116     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs, Idxs+NumIdx);
2117     assert(Ty != 0 && "Invalid indices for GEP!");
2118     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2119   }
2120
2121   if (C->isNullValue()) {
2122     bool isNull = true;
2123     for (unsigned i = 0, e = NumIdx; i != e; ++i)
2124       if (!cast<Constant>(Idxs[i])->isNullValue()) {
2125         isNull = false;
2126         break;
2127       }
2128     if (isNull) {
2129       const PointerType *Ptr = cast<PointerType>(C->getType());
2130       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs,
2131                                                          Idxs+NumIdx);
2132       assert(Ty != 0 && "Invalid indices for GEP!");
2133       return ConstantPointerNull::get(PointerType::get(Ty,
2134                                                        Ptr->getAddressSpace()));
2135     }
2136   }
2137
2138   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2139     // Combine Indices - If the source pointer to this getelementptr instruction
2140     // is a getelementptr instruction, combine the indices of the two
2141     // getelementptr instructions into a single instruction.
2142     //
2143     if (CE->getOpcode() == Instruction::GetElementPtr) {
2144       const Type *LastTy = 0;
2145       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2146            I != E; ++I)
2147         LastTy = *I;
2148
2149       if ((LastTy && LastTy->isArrayTy()) || Idx0->isNullValue()) {
2150         SmallVector<Value*, 16> NewIndices;
2151         NewIndices.reserve(NumIdx + CE->getNumOperands());
2152         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2153           NewIndices.push_back(CE->getOperand(i));
2154
2155         // Add the last index of the source with the first index of the new GEP.
2156         // Make sure to handle the case when they are actually different types.
2157         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2158         // Otherwise it must be an array.
2159         if (!Idx0->isNullValue()) {
2160           const Type *IdxTy = Combined->getType();
2161           if (IdxTy != Idx0->getType()) {
2162             const Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2163             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2164             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2165             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2166           } else {
2167             Combined =
2168               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2169           }
2170         }
2171
2172         NewIndices.push_back(Combined);
2173         NewIndices.append(Idxs+1, Idxs+NumIdx);
2174         return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2175           ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2176                                                  &NewIndices[0],
2177                                                  NewIndices.size()) :
2178           ConstantExpr::getGetElementPtr(CE->getOperand(0),
2179                                          &NewIndices[0],
2180                                          NewIndices.size());
2181       }
2182     }
2183
2184     // Implement folding of:
2185     //    i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2186     //                        i64 0, i64 0)
2187     // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2188     //
2189     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
2190       if (const PointerType *SPT =
2191           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2192         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2193           if (const ArrayType *CAT =
2194         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
2195             if (CAT->getElementType() == SAT->getElementType())
2196               return inBounds ?
2197                 ConstantExpr::getInBoundsGetElementPtr(
2198                       (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2199                 ConstantExpr::getGetElementPtr(
2200                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
2201     }
2202   }
2203
2204   // Check to see if any array indices are not within the corresponding
2205   // notional array bounds. If so, try to determine if they can be factored
2206   // out into preceding dimensions.
2207   bool Unknown = false;
2208   SmallVector<Constant *, 8> NewIdxs;
2209   const Type *Ty = C->getType();
2210   const Type *Prev = 0;
2211   for (unsigned i = 0; i != NumIdx;
2212        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2213     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2214       if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2215         if (ATy->getNumElements() <= INT64_MAX &&
2216             ATy->getNumElements() != 0 &&
2217             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2218           if (isa<SequentialType>(Prev)) {
2219             // It's out of range, but we can factor it into the prior
2220             // dimension.
2221             NewIdxs.resize(NumIdx);
2222             ConstantInt *Factor = ConstantInt::get(CI->getType(),
2223                                                    ATy->getNumElements());
2224             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2225
2226             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2227             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2228
2229             // Before adding, extend both operands to i64 to avoid
2230             // overflow trouble.
2231             if (!PrevIdx->getType()->isIntegerTy(64))
2232               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2233                                            Type::getInt64Ty(Div->getContext()));
2234             if (!Div->getType()->isIntegerTy(64))
2235               Div = ConstantExpr::getSExt(Div,
2236                                           Type::getInt64Ty(Div->getContext()));
2237
2238             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2239           } else {
2240             // It's out of range, but the prior dimension is a struct
2241             // so we can't do anything about it.
2242             Unknown = true;
2243           }
2244         }
2245     } else {
2246       // We don't know if it's in range or not.
2247       Unknown = true;
2248     }
2249   }
2250
2251   // If we did any factoring, start over with the adjusted indices.
2252   if (!NewIdxs.empty()) {
2253     for (unsigned i = 0; i != NumIdx; ++i)
2254       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2255     return inBounds ?
2256       ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2257                                              NewIdxs.size()) :
2258       ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
2259   }
2260
2261   // If all indices are known integers and normalized, we can do a simple
2262   // check for the "inbounds" property.
2263   if (!Unknown && !inBounds &&
2264       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
2265     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
2266
2267   return 0;
2268 }
2269
2270 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2271                                           bool inBounds,
2272                                           Constant* const *Idxs,
2273                                           unsigned NumIdx) {
2274   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs, NumIdx);
2275 }
2276
2277 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2278                                           bool inBounds,
2279                                           Value* const *Idxs,
2280                                           unsigned NumIdx) {
2281   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs, NumIdx);
2282 }