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