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