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