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