]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/IR/ConstantFold.cpp
Debug info: Implement (rvalue) reference qualifiers for C++11 non-static
[opencl/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 //===----------------------------------------------------------------------===//
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;
37 //===----------------------------------------------------------------------===//
38 //                ConstantFold*Instruction Implementations
39 //===----------------------------------------------------------------------===//
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) {
46   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
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();
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   }
67   return ConstantVector::get(Result);
68 }
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");
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);
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());
95   // Let CastInst::isEliminableCastPair do the heavy lifting.
96   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
97                                         0, FakeIntPtrTy, 0);
98 }
100 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
101   Type *SrcTy = V->getType();
102   if (SrcTy == DestTy)
103     return V; // no-op cast
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         }
131         if (ElTy == DPTy->getElementType())
132           // This GEP is inbounds because all indices are zero.
133           return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
134       }
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);
147       // Handle ConstantVector and ConstantAggregateVector.
148       return BitCastConstantVector(V, DestPTy);
149     }
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   }
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));
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;
170     if (DestTy->isFloatingPointTy())
171       return ConstantFP::get(DestTy->getContext(),
172                              APFloat(DestTy->getFltSemantics(),
173                                      CI->getValue()));
175     // Otherwise, can't fold this (vector?)
176     return 0;
177   }
179   // Handle ConstantFP input: FP -> Integral.
180   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
181     return ConstantInt::get(FP->getContext(),
182                             FP->getValueAPF().bitcastToAPInt());
184   return 0;
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));
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   }
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   }
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     }
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);
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;
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;
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   }
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);
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   }
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);
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;
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;
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   }
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     }
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;
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;
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   }
522   if (V->isNullValue() && !DestTy->isX86_MMXTy())
523     return Constant::getNullValue(DestTy);
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   }
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   }
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   case Instruction::AddrSpaceCast:
693     return 0;
694   }
697 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
698                                               Constant *V1, Constant *V2) {
699   // Check for i1 and vector true/false conditions.
700   if (Cond->isNullValue()) return V2;
701   if (Cond->isAllOnesValue()) return V1;
703   // If the condition is a vector constant, fold the result elementwise.
704   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
705     SmallVector<Constant*, 16> Result;
706     Type *Ty = IntegerType::get(CondV->getContext(), 32);
707     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
708       ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
709       if (Cond == 0) break;
710       
711       Constant *V = Cond->isNullValue() ? V2 : V1;
712       Constant *Res = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
713       Result.push_back(Res);
714     }
715     
716     // If we were able to build the vector, return it.
717     if (Result.size() == V1->getType()->getVectorNumElements())
718       return ConstantVector::get(Result);
719   }
721   if (isa<UndefValue>(Cond)) {
722     if (isa<UndefValue>(V1)) return V1;
723     return V2;
724   }
725   if (isa<UndefValue>(V1)) return V2;
726   if (isa<UndefValue>(V2)) return V1;
727   if (V1 == V2) return V1;
729   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
730     if (TrueVal->getOpcode() == Instruction::Select)
731       if (TrueVal->getOperand(0) == Cond)
732         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
733   }
734   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
735     if (FalseVal->getOpcode() == Instruction::Select)
736       if (FalseVal->getOperand(0) == Cond)
737         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
738   }
740   return 0;
743 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
744                                                       Constant *Idx) {
745   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
746     return UndefValue::get(Val->getType()->getVectorElementType());
747   if (Val->isNullValue())  // ee(zero, x) -> zero
748     return Constant::getNullValue(Val->getType()->getVectorElementType());
749   // ee({w,x,y,z}, undef) -> undef
750   if (isa<UndefValue>(Idx))
751     return UndefValue::get(Val->getType()->getVectorElementType());
753   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
754     uint64_t Index = CIdx->getZExtValue();
755     // ee({w,x,y,z}, wrong_value) -> undef
756     if (Index >= Val->getType()->getVectorNumElements())
757       return UndefValue::get(Val->getType()->getVectorElementType());
758     return Val->getAggregateElement(Index);
759   }
760   return 0;
763 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
764                                                      Constant *Elt,
765                                                      Constant *Idx) {
766   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
767   if (!CIdx) return 0;
768   const APInt &IdxVal = CIdx->getValue();
769   
770   SmallVector<Constant*, 16> Result;
771   Type *Ty = IntegerType::get(Val->getContext(), 32);
772   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
773     if (i == IdxVal) {
774       Result.push_back(Elt);
775       continue;
776     }
777     
778     Constant *C =
779       ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
780     Result.push_back(C);
781   }
782   
783   return ConstantVector::get(Result);
786 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
787                                                      Constant *V2,
788                                                      Constant *Mask) {
789   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
790   Type *EltTy = V1->getType()->getVectorElementType();
792   // Undefined shuffle mask -> undefined value.
793   if (isa<UndefValue>(Mask))
794     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
796   // Don't break the bitcode reader hack.
797   if (isa<ConstantExpr>(Mask)) return 0;
798   
799   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
801   // Loop over the shuffle mask, evaluating each element.
802   SmallVector<Constant*, 32> Result;
803   for (unsigned i = 0; i != MaskNumElts; ++i) {
804     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
805     if (Elt == -1) {
806       Result.push_back(UndefValue::get(EltTy));
807       continue;
808     }
809     Constant *InElt;
810     if (unsigned(Elt) >= SrcNumElts*2)
811       InElt = UndefValue::get(EltTy);
812     else if (unsigned(Elt) >= SrcNumElts) {
813       Type *Ty = IntegerType::get(V2->getContext(), 32);
814       InElt =
815         ConstantExpr::getExtractElement(V2,
816                                         ConstantInt::get(Ty, Elt - SrcNumElts));
817     } else {
818       Type *Ty = IntegerType::get(V1->getContext(), 32);
819       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
820     }
821     Result.push_back(InElt);
822   }
824   return ConstantVector::get(Result);
827 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
828                                                     ArrayRef<unsigned> Idxs) {
829   // Base case: no indices, so return the entire value.
830   if (Idxs.empty())
831     return Agg;
833   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
834     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
836   return 0;
839 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
840                                                    Constant *Val,
841                                                    ArrayRef<unsigned> Idxs) {
842   // Base case: no indices, so replace the entire value.
843   if (Idxs.empty())
844     return Val;
846   unsigned NumElts;
847   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
848     NumElts = ST->getNumElements();
849   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
850     NumElts = AT->getNumElements();
851   else
852     NumElts = Agg->getType()->getVectorNumElements();
854   SmallVector<Constant*, 32> Result;
855   for (unsigned i = 0; i != NumElts; ++i) {
856     Constant *C = Agg->getAggregateElement(i);
857     if (C == 0) return 0;
858     
859     if (Idxs[0] == i)
860       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
861     
862     Result.push_back(C);
863   }
864   
865   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
866     return ConstantStruct::get(ST, Result);
867   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
868     return ConstantArray::get(AT, Result);
869   return ConstantVector::get(Result);
873 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
874                                               Constant *C1, Constant *C2) {
875   // Handle UndefValue up front.
876   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
877     switch (Opcode) {
878     case Instruction::Xor:
879       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
880         // Handle undef ^ undef -> 0 special case. This is a common
881         // idiom (misuse).
882         return Constant::getNullValue(C1->getType());
883       // Fallthrough
884     case Instruction::Add:
885     case Instruction::Sub:
886       return UndefValue::get(C1->getType());
887     case Instruction::And:
888       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
889         return C1;
890       return Constant::getNullValue(C1->getType());   // undef & X -> 0
891     case Instruction::Mul: {
892       ConstantInt *CI;
893       // X * undef -> undef   if X is odd or undef
894       if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
895           ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
896           (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
897         return UndefValue::get(C1->getType());
899       // X * undef -> 0       otherwise
900       return Constant::getNullValue(C1->getType());
901     }
902     case Instruction::UDiv:
903     case Instruction::SDiv:
904       // undef / 1 -> undef
905       if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
906         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
907           if (CI2->isOne())
908             return C1;
909       // FALL THROUGH
910     case Instruction::URem:
911     case Instruction::SRem:
912       if (!isa<UndefValue>(C2))                    // undef / X -> 0
913         return Constant::getNullValue(C1->getType());
914       return C2;                                   // X / undef -> undef
915     case Instruction::Or:                          // X | undef -> -1
916       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
917         return C1;
918       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
919     case Instruction::LShr:
920       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
921         return C1;                                  // undef lshr undef -> undef
922       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
923                                                     // undef lshr X -> 0
924     case Instruction::AShr:
925       if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
926         return Constant::getAllOnesValue(C1->getType());
927       else if (isa<UndefValue>(C1)) 
928         return C1;                                  // undef ashr undef -> undef
929       else
930         return C1;                                  // X ashr undef --> X
931     case Instruction::Shl:
932       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
933         return C1;                                  // undef shl undef -> undef
934       // undef << X -> 0   or   X << undef -> 0
935       return Constant::getNullValue(C1->getType());
936     }
937   }
939   // Handle simplifications when the RHS is a constant int.
940   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
941     switch (Opcode) {
942     case Instruction::Add:
943       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
944       break;
945     case Instruction::Sub:
946       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
947       break;
948     case Instruction::Mul:
949       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
950       if (CI2->equalsInt(1))
951         return C1;                                              // X * 1 == X
952       break;
953     case Instruction::UDiv:
954     case Instruction::SDiv:
955       if (CI2->equalsInt(1))
956         return C1;                                            // X / 1 == X
957       if (CI2->equalsInt(0))
958         return UndefValue::get(CI2->getType());               // X / 0 == undef
959       break;
960     case Instruction::URem:
961     case Instruction::SRem:
962       if (CI2->equalsInt(1))
963         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
964       if (CI2->equalsInt(0))
965         return UndefValue::get(CI2->getType());               // X % 0 == undef
966       break;
967     case Instruction::And:
968       if (CI2->isZero()) return C2;                           // X & 0 == 0
969       if (CI2->isAllOnesValue())
970         return C1;                                            // X & -1 == X
972       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
973         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
974         if (CE1->getOpcode() == Instruction::ZExt) {
975           unsigned DstWidth = CI2->getType()->getBitWidth();
976           unsigned SrcWidth =
977             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
978           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
979           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
980             return C1;
981         }
983         // If and'ing the address of a global with a constant, fold it.
984         if (CE1->getOpcode() == Instruction::PtrToInt && 
985             isa<GlobalValue>(CE1->getOperand(0))) {
986           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
988           // Functions are at least 4-byte aligned.
989           unsigned GVAlign = GV->getAlignment();
990           if (isa<Function>(GV))
991             GVAlign = std::max(GVAlign, 4U);
993           if (GVAlign > 1) {
994             unsigned DstWidth = CI2->getType()->getBitWidth();
995             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
996             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
998             // If checking bits we know are clear, return zero.
999             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1000               return Constant::getNullValue(CI2->getType());
1001           }
1002         }
1003       }
1004       break;
1005     case Instruction::Or:
1006       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1007       if (CI2->isAllOnesValue())
1008         return C2;                         // X | -1 == -1
1009       break;
1010     case Instruction::Xor:
1011       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1013       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1014         switch (CE1->getOpcode()) {
1015         default: break;
1016         case Instruction::ICmp:
1017         case Instruction::FCmp:
1018           // cmp pred ^ true -> cmp !pred
1019           assert(CI2->equalsInt(1));
1020           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1021           pred = CmpInst::getInversePredicate(pred);
1022           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1023                                           CE1->getOperand(1));
1024         }
1025       }
1026       break;
1027     case Instruction::AShr:
1028       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1029       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1030         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1031           return ConstantExpr::getLShr(C1, C2);
1032       break;
1033     }
1034   } else if (isa<ConstantInt>(C1)) {
1035     // If C1 is a ConstantInt and C2 is not, swap the operands.
1036     if (Instruction::isCommutative(Opcode))
1037       return ConstantExpr::get(Opcode, C2, C1);
1038   }
1040   // At this point we know neither constant is an UndefValue.
1041   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1042     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1043       const APInt &C1V = CI1->getValue();
1044       const APInt &C2V = CI2->getValue();
1045       switch (Opcode) {
1046       default:
1047         break;
1048       case Instruction::Add:     
1049         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1050       case Instruction::Sub:     
1051         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1052       case Instruction::Mul:     
1053         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1054       case Instruction::UDiv:
1055         assert(!CI2->isNullValue() && "Div by zero handled above");
1056         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1057       case Instruction::SDiv:
1058         assert(!CI2->isNullValue() && "Div by zero handled above");
1059         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1060           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1061         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1062       case Instruction::URem:
1063         assert(!CI2->isNullValue() && "Div by zero handled above");
1064         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1065       case Instruction::SRem:
1066         assert(!CI2->isNullValue() && "Div by zero handled above");
1067         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1068           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1069         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1070       case Instruction::And:
1071         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1072       case Instruction::Or:
1073         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1074       case Instruction::Xor:
1075         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1076       case Instruction::Shl: {
1077         uint32_t shiftAmt = C2V.getZExtValue();
1078         if (shiftAmt < C1V.getBitWidth())
1079           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1080         else
1081           return UndefValue::get(C1->getType()); // too big shift is undef
1082       }
1083       case Instruction::LShr: {
1084         uint32_t shiftAmt = C2V.getZExtValue();
1085         if (shiftAmt < C1V.getBitWidth())
1086           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1087         else
1088           return UndefValue::get(C1->getType()); // too big shift is undef
1089       }
1090       case Instruction::AShr: {
1091         uint32_t shiftAmt = C2V.getZExtValue();
1092         if (shiftAmt < C1V.getBitWidth())
1093           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1094         else
1095           return UndefValue::get(C1->getType()); // too big shift is undef
1096       }
1097       }
1098     }
1100     switch (Opcode) {
1101     case Instruction::SDiv:
1102     case Instruction::UDiv:
1103     case Instruction::URem:
1104     case Instruction::SRem:
1105     case Instruction::LShr:
1106     case Instruction::AShr:
1107     case Instruction::Shl:
1108       if (CI1->equalsInt(0)) return C1;
1109       break;
1110     default:
1111       break;
1112     }
1113   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1114     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1115       APFloat C1V = CFP1->getValueAPF();
1116       APFloat C2V = CFP2->getValueAPF();
1117       APFloat C3V = C1V;  // copy for modification
1118       switch (Opcode) {
1119       default:                   
1120         break;
1121       case Instruction::FAdd:
1122         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1123         return ConstantFP::get(C1->getContext(), C3V);
1124       case Instruction::FSub:
1125         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1126         return ConstantFP::get(C1->getContext(), C3V);
1127       case Instruction::FMul:
1128         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1129         return ConstantFP::get(C1->getContext(), C3V);
1130       case Instruction::FDiv:
1131         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1132         return ConstantFP::get(C1->getContext(), C3V);
1133       case Instruction::FRem:
1134         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1135         return ConstantFP::get(C1->getContext(), C3V);
1136       }
1137     }
1138   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1139     // Perform elementwise folding.
1140     SmallVector<Constant*, 16> Result;
1141     Type *Ty = IntegerType::get(VTy->getContext(), 32);
1142     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1143       Constant *LHS =
1144         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1145       Constant *RHS =
1146         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1147       
1148       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1149     }
1150     
1151     return ConstantVector::get(Result);
1152   }
1154   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1155     // There are many possible foldings we could do here.  We should probably
1156     // at least fold add of a pointer with an integer into the appropriate
1157     // getelementptr.  This will improve alias analysis a bit.
1159     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1160     // (a + (b + c)).
1161     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1162       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1163       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1164         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1165     }
1166   } else if (isa<ConstantExpr>(C2)) {
1167     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1168     // other way if possible.
1169     if (Instruction::isCommutative(Opcode))
1170       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1171   }
1173   // i1 can be simplified in many cases.
1174   if (C1->getType()->isIntegerTy(1)) {
1175     switch (Opcode) {
1176     case Instruction::Add:
1177     case Instruction::Sub:
1178       return ConstantExpr::getXor(C1, C2);
1179     case Instruction::Mul:
1180       return ConstantExpr::getAnd(C1, C2);
1181     case Instruction::Shl:
1182     case Instruction::LShr:
1183     case Instruction::AShr:
1184       // We can assume that C2 == 0.  If it were one the result would be
1185       // undefined because the shift value is as large as the bitwidth.
1186       return C1;
1187     case Instruction::SDiv:
1188     case Instruction::UDiv:
1189       // We can assume that C2 == 1.  If it were zero the result would be
1190       // undefined through division by zero.
1191       return C1;
1192     case Instruction::URem:
1193     case Instruction::SRem:
1194       // We can assume that C2 == 1.  If it were zero the result would be
1195       // undefined through division by zero.
1196       return ConstantInt::getFalse(C1->getContext());
1197     default:
1198       break;
1199     }
1200   }
1202   // We don't know how to fold this.
1203   return 0;
1206 /// isZeroSizedType - This type is zero sized if its an array or structure of
1207 /// zero sized types.  The only leaf zero sized type is an empty structure.
1208 static bool isMaybeZeroSizedType(Type *Ty) {
1209   if (StructType *STy = dyn_cast<StructType>(Ty)) {
1210     if (STy->isOpaque()) return true;  // Can't say.
1212     // If all of elements have zero size, this does too.
1213     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1214       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1215     return true;
1217   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1218     return isMaybeZeroSizedType(ATy->getElementType());
1219   }
1220   return false;
1223 /// IdxCompare - Compare the two constants as though they were getelementptr
1224 /// indices.  This allows coersion of the types to be the same thing.
1225 ///
1226 /// If the two constants are the "same" (after coersion), return 0.  If the
1227 /// first is less than the second, return -1, if the second is less than the
1228 /// first, return 1.  If the constants are not integral, return -2.
1229 ///
1230 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1231   if (C1 == C2) return 0;
1233   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1234   // anything with them.
1235   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1236     return -2; // don't know!
1238   // Ok, we have two differing integer indices.  Sign extend them to be the same
1239   // type.  Long is always big enough, so we use it.
1240   if (!C1->getType()->isIntegerTy(64))
1241     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1243   if (!C2->getType()->isIntegerTy(64))
1244     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1246   if (C1 == C2) return 0;  // They are equal
1248   // If the type being indexed over is really just a zero sized type, there is
1249   // no pointer difference being made here.
1250   if (isMaybeZeroSizedType(ElTy))
1251     return -2; // dunno.
1253   // If they are really different, now that they are the same type, then we
1254   // found a difference!
1255   if (cast<ConstantInt>(C1)->getSExtValue() < 
1256       cast<ConstantInt>(C2)->getSExtValue())
1257     return -1;
1258   else
1259     return 1;
1262 /// evaluateFCmpRelation - This function determines if there is anything we can
1263 /// decide about the two constants provided.  This doesn't need to handle simple
1264 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1265 /// If we can determine that the two constants have a particular relation to 
1266 /// each other, we should return the corresponding FCmpInst predicate, 
1267 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1268 /// ConstantFoldCompareInstruction.
1269 ///
1270 /// To simplify this code we canonicalize the relation so that the first
1271 /// operand is always the most "complex" of the two.  We consider ConstantFP
1272 /// to be the simplest, and ConstantExprs to be the most complex.
1273 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1274   assert(V1->getType() == V2->getType() &&
1275          "Cannot compare values of different types!");
1277   // Handle degenerate case quickly
1278   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1280   if (!isa<ConstantExpr>(V1)) {
1281     if (!isa<ConstantExpr>(V2)) {
1282       // We distilled thisUse the standard constant folder for a few cases
1283       ConstantInt *R = 0;
1284       R = dyn_cast<ConstantInt>(
1285                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1286       if (R && !R->isZero()) 
1287         return FCmpInst::FCMP_OEQ;
1288       R = dyn_cast<ConstantInt>(
1289                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1290       if (R && !R->isZero()) 
1291         return FCmpInst::FCMP_OLT;
1292       R = dyn_cast<ConstantInt>(
1293                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1294       if (R && !R->isZero()) 
1295         return FCmpInst::FCMP_OGT;
1297       // Nothing more we can do
1298       return FCmpInst::BAD_FCMP_PREDICATE;
1299     }
1301     // If the first operand is simple and second is ConstantExpr, swap operands.
1302     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1303     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1304       return FCmpInst::getSwappedPredicate(SwappedRelation);
1305   } else {
1306     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1307     // constantexpr or a simple constant.
1308     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1309     switch (CE1->getOpcode()) {
1310     case Instruction::FPTrunc:
1311     case Instruction::FPExt:
1312     case Instruction::UIToFP:
1313     case Instruction::SIToFP:
1314       // We might be able to do something with these but we don't right now.
1315       break;
1316     default:
1317       break;
1318     }
1319   }
1320   // There are MANY other foldings that we could perform here.  They will
1321   // probably be added on demand, as they seem needed.
1322   return FCmpInst::BAD_FCMP_PREDICATE;
1325 /// evaluateICmpRelation - This function determines if there is anything we can
1326 /// decide about the two constants provided.  This doesn't need to handle simple
1327 /// things like integer comparisons, but should instead handle ConstantExprs
1328 /// and GlobalValues.  If we can determine that the two constants have a
1329 /// particular relation to each other, we should return the corresponding ICmp
1330 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1331 ///
1332 /// To simplify this code we canonicalize the relation so that the first
1333 /// operand is always the most "complex" of the two.  We consider simple
1334 /// constants (like ConstantInt) to be the simplest, followed by
1335 /// GlobalValues, followed by ConstantExpr's (the most complex).
1336 ///
1337 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1338                                                 bool isSigned) {
1339   assert(V1->getType() == V2->getType() &&
1340          "Cannot compare different types of values!");
1341   if (V1 == V2) return ICmpInst::ICMP_EQ;
1343   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1344       !isa<BlockAddress>(V1)) {
1345     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1346         !isa<BlockAddress>(V2)) {
1347       // We distilled this down to a simple case, use the standard constant
1348       // folder.
1349       ConstantInt *R = 0;
1350       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1351       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1352       if (R && !R->isZero()) 
1353         return pred;
1354       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1355       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1356       if (R && !R->isZero())
1357         return pred;
1358       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1359       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1360       if (R && !R->isZero())
1361         return pred;
1363       // If we couldn't figure it out, bail.
1364       return ICmpInst::BAD_ICMP_PREDICATE;
1365     }
1367     // If the first operand is simple, swap operands.
1368     ICmpInst::Predicate SwappedRelation = 
1369       evaluateICmpRelation(V2, V1, isSigned);
1370     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1371       return ICmpInst::getSwappedPredicate(SwappedRelation);
1373   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1374     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1375       ICmpInst::Predicate SwappedRelation = 
1376         evaluateICmpRelation(V2, V1, isSigned);
1377       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1378         return ICmpInst::getSwappedPredicate(SwappedRelation);
1379       return ICmpInst::BAD_ICMP_PREDICATE;
1380     }
1382     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1383     // constant (which, since the types must match, means that it's a
1384     // ConstantPointerNull).
1385     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1386       // Don't try to decide equality of aliases.
1387       if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1388         if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1389           return ICmpInst::ICMP_NE;
1390     } else if (isa<BlockAddress>(V2)) {
1391       return ICmpInst::ICMP_NE; // Globals never equal labels.
1392     } else {
1393       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1394       // GlobalVals can never be null unless they have external weak linkage.
1395       // We don't try to evaluate aliases here.
1396       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1397         return ICmpInst::ICMP_NE;
1398     }
1399   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1400     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1401       ICmpInst::Predicate SwappedRelation = 
1402         evaluateICmpRelation(V2, V1, isSigned);
1403       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1404         return ICmpInst::getSwappedPredicate(SwappedRelation);
1405       return ICmpInst::BAD_ICMP_PREDICATE;
1406     }
1407     
1408     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1409     // constant (which, since the types must match, means that it is a
1410     // ConstantPointerNull).
1411     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1412       // Block address in another function can't equal this one, but block
1413       // addresses in the current function might be the same if blocks are
1414       // empty.
1415       if (BA2->getFunction() != BA->getFunction())
1416         return ICmpInst::ICMP_NE;
1417     } else {
1418       // Block addresses aren't null, don't equal the address of globals.
1419       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1420              "Canonicalization guarantee!");
1421       return ICmpInst::ICMP_NE;
1422     }
1423   } else {
1424     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1425     // constantexpr, a global, block address, or a simple constant.
1426     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1427     Constant *CE1Op0 = CE1->getOperand(0);
1429     switch (CE1->getOpcode()) {
1430     case Instruction::Trunc:
1431     case Instruction::FPTrunc:
1432     case Instruction::FPExt:
1433     case Instruction::FPToUI:
1434     case Instruction::FPToSI:
1435       break; // We can't evaluate floating point casts or truncations.
1437     case Instruction::UIToFP:
1438     case Instruction::SIToFP:
1439     case Instruction::BitCast:
1440     case Instruction::ZExt:
1441     case Instruction::SExt:
1442       // If the cast is not actually changing bits, and the second operand is a
1443       // null pointer, do the comparison with the pre-casted value.
1444       if (V2->isNullValue() &&
1445           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1446         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1447         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1448         return evaluateICmpRelation(CE1Op0,
1449                                     Constant::getNullValue(CE1Op0->getType()), 
1450                                     isSigned);
1451       }
1452       break;
1454     case Instruction::GetElementPtr:
1455       // Ok, since this is a getelementptr, we know that the constant has a
1456       // pointer type.  Check the various cases.
1457       if (isa<ConstantPointerNull>(V2)) {
1458         // If we are comparing a GEP to a null pointer, check to see if the base
1459         // of the GEP equals the null pointer.
1460         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1461           if (GV->hasExternalWeakLinkage())
1462             // Weak linkage GVals could be zero or not. We're comparing that
1463             // to null pointer so its greater-or-equal
1464             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1465           else 
1466             // If its not weak linkage, the GVal must have a non-zero address
1467             // so the result is greater-than
1468             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1469         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1470           // If we are indexing from a null pointer, check to see if we have any
1471           // non-zero indices.
1472           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1473             if (!CE1->getOperand(i)->isNullValue())
1474               // Offsetting from null, must not be equal.
1475               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1476           // Only zero indexes from null, must still be zero.
1477           return ICmpInst::ICMP_EQ;
1478         }
1479         // Otherwise, we can't really say if the first operand is null or not.
1480       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1481         if (isa<ConstantPointerNull>(CE1Op0)) {
1482           if (GV2->hasExternalWeakLinkage())
1483             // Weak linkage GVals could be zero or not. We're comparing it to
1484             // a null pointer, so its less-or-equal
1485             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1486           else
1487             // If its not weak linkage, the GVal must have a non-zero address
1488             // so the result is less-than
1489             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1490         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1491           if (GV == GV2) {
1492             // If this is a getelementptr of the same global, then it must be
1493             // different.  Because the types must match, the getelementptr could
1494             // only have at most one index, and because we fold getelementptr's
1495             // with a single zero index, it must be nonzero.
1496             assert(CE1->getNumOperands() == 2 &&
1497                    !CE1->getOperand(1)->isNullValue() &&
1498                    "Surprising getelementptr!");
1499             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1500           } else {
1501             // If they are different globals, we don't know what the value is.
1502             return ICmpInst::BAD_ICMP_PREDICATE;
1503           }
1504         }
1505       } else {
1506         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1507         Constant *CE2Op0 = CE2->getOperand(0);
1509         // There are MANY other foldings that we could perform here.  They will
1510         // probably be added on demand, as they seem needed.
1511         switch (CE2->getOpcode()) {
1512         default: break;
1513         case Instruction::GetElementPtr:
1514           // By far the most common case to handle is when the base pointers are
1515           // obviously to the same global.
1516           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1517             if (CE1Op0 != CE2Op0) // Don't know relative ordering.
1518               return ICmpInst::BAD_ICMP_PREDICATE;
1519             // Ok, we know that both getelementptr instructions are based on the
1520             // same global.  From this, we can precisely determine the relative
1521             // ordering of the resultant pointers.
1522             unsigned i = 1;
1524             // The logic below assumes that the result of the comparison
1525             // can be determined by finding the first index that differs.
1526             // This doesn't work if there is over-indexing in any
1527             // subsequent indices, so check for that case first.
1528             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1529                 !CE2->isGEPWithNoNotionalOverIndexing())
1530                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1532             // Compare all of the operands the GEP's have in common.
1533             gep_type_iterator GTI = gep_type_begin(CE1);
1534             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1535                  ++i, ++GTI)
1536               switch (IdxCompare(CE1->getOperand(i),
1537                                  CE2->getOperand(i), GTI.getIndexedType())) {
1538               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1539               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1540               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1541               }
1543             // Ok, we ran out of things they have in common.  If any leftovers
1544             // are non-zero then we have a difference, otherwise we are equal.
1545             for (; i < CE1->getNumOperands(); ++i)
1546               if (!CE1->getOperand(i)->isNullValue()) {
1547                 if (isa<ConstantInt>(CE1->getOperand(i)))
1548                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1549                 else
1550                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1551               }
1553             for (; i < CE2->getNumOperands(); ++i)
1554               if (!CE2->getOperand(i)->isNullValue()) {
1555                 if (isa<ConstantInt>(CE2->getOperand(i)))
1556                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1557                 else
1558                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1559               }
1560             return ICmpInst::ICMP_EQ;
1561           }
1562         }
1563       }
1564     default:
1565       break;
1566     }
1567   }
1569   return ICmpInst::BAD_ICMP_PREDICATE;
1572 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1573                                                Constant *C1, Constant *C2) {
1574   Type *ResultTy;
1575   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1576     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1577                                VT->getNumElements());
1578   else
1579     ResultTy = Type::getInt1Ty(C1->getContext());
1581   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1582   if (pred == FCmpInst::FCMP_FALSE)
1583     return Constant::getNullValue(ResultTy);
1585   if (pred == FCmpInst::FCMP_TRUE)
1586     return Constant::getAllOnesValue(ResultTy);
1588   // Handle some degenerate cases first
1589   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1590     // For EQ and NE, we can always pick a value for the undef to make the
1591     // predicate pass or fail, so we can return undef.
1592     // Also, if both operands are undef, we can return undef.
1593     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1594         (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1595       return UndefValue::get(ResultTy);
1596     // Otherwise, pick the same value as the non-undef operand, and fold
1597     // it to true or false.
1598     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1599   }
1601   // icmp eq/ne(null,GV) -> false/true
1602   if (C1->isNullValue()) {
1603     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1604       // Don't try to evaluate aliases.  External weak GV can be null.
1605       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1606         if (pred == ICmpInst::ICMP_EQ)
1607           return ConstantInt::getFalse(C1->getContext());
1608         else if (pred == ICmpInst::ICMP_NE)
1609           return ConstantInt::getTrue(C1->getContext());
1610       }
1611   // icmp eq/ne(GV,null) -> false/true
1612   } else if (C2->isNullValue()) {
1613     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1614       // Don't try to evaluate aliases.  External weak GV can be null.
1615       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1616         if (pred == ICmpInst::ICMP_EQ)
1617           return ConstantInt::getFalse(C1->getContext());
1618         else if (pred == ICmpInst::ICMP_NE)
1619           return ConstantInt::getTrue(C1->getContext());
1620       }
1621   }
1623   // If the comparison is a comparison between two i1's, simplify it.
1624   if (C1->getType()->isIntegerTy(1)) {
1625     switch(pred) {
1626     case ICmpInst::ICMP_EQ:
1627       if (isa<ConstantInt>(C2))
1628         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1629       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1630     case ICmpInst::ICMP_NE:
1631       return ConstantExpr::getXor(C1, C2);
1632     default:
1633       break;
1634     }
1635   }
1637   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1638     APInt V1 = cast<ConstantInt>(C1)->getValue();
1639     APInt V2 = cast<ConstantInt>(C2)->getValue();
1640     switch (pred) {
1641     default: llvm_unreachable("Invalid ICmp Predicate");
1642     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1643     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1644     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1645     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1646     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1647     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1648     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1649     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1650     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1651     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1652     }
1653   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1654     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1655     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1656     APFloat::cmpResult R = C1V.compare(C2V);
1657     switch (pred) {
1658     default: llvm_unreachable("Invalid FCmp Predicate");
1659     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1660     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1661     case FCmpInst::FCMP_UNO:
1662       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1663     case FCmpInst::FCMP_ORD:
1664       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1665     case FCmpInst::FCMP_UEQ:
1666       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1667                                         R==APFloat::cmpEqual);
1668     case FCmpInst::FCMP_OEQ:   
1669       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1670     case FCmpInst::FCMP_UNE:
1671       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1672     case FCmpInst::FCMP_ONE:   
1673       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1674                                         R==APFloat::cmpGreaterThan);
1675     case FCmpInst::FCMP_ULT: 
1676       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1677                                         R==APFloat::cmpLessThan);
1678     case FCmpInst::FCMP_OLT:   
1679       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1680     case FCmpInst::FCMP_UGT:
1681       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1682                                         R==APFloat::cmpGreaterThan);
1683     case FCmpInst::FCMP_OGT:
1684       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1685     case FCmpInst::FCMP_ULE:
1686       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1687     case FCmpInst::FCMP_OLE: 
1688       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1689                                         R==APFloat::cmpEqual);
1690     case FCmpInst::FCMP_UGE:
1691       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1692     case FCmpInst::FCMP_OGE: 
1693       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1694                                         R==APFloat::cmpEqual);
1695     }
1696   } else if (C1->getType()->isVectorTy()) {
1697     // If we can constant fold the comparison of each element, constant fold
1698     // the whole vector comparison.
1699     SmallVector<Constant*, 4> ResElts;
1700     Type *Ty = IntegerType::get(C1->getContext(), 32);
1701     // Compare the elements, producing an i1 result or constant expr.
1702     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1703       Constant *C1E =
1704         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1705       Constant *C2E =
1706         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1707       
1708       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1709     }
1710     
1711     return ConstantVector::get(ResElts);
1712   }
1714   if (C1->getType()->isFloatingPointTy()) {
1715     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1716     switch (evaluateFCmpRelation(C1, C2)) {
1717     default: llvm_unreachable("Unknown relation!");
1718     case FCmpInst::FCMP_UNO:
1719     case FCmpInst::FCMP_ORD:
1720     case FCmpInst::FCMP_UEQ:
1721     case FCmpInst::FCMP_UNE:
1722     case FCmpInst::FCMP_ULT:
1723     case FCmpInst::FCMP_UGT:
1724     case FCmpInst::FCMP_ULE:
1725     case FCmpInst::FCMP_UGE:
1726     case FCmpInst::FCMP_TRUE:
1727     case FCmpInst::FCMP_FALSE:
1728     case FCmpInst::BAD_FCMP_PREDICATE:
1729       break; // Couldn't determine anything about these constants.
1730     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1731       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1732                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1733                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1734       break;
1735     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1736       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1737                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1738                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1739       break;
1740     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1741       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1742                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1743                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1744       break;
1745     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1746       // We can only partially decide this relation.
1747       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1748         Result = 0;
1749       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1750         Result = 1;
1751       break;
1752     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1753       // We can only partially decide this relation.
1754       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1755         Result = 0;
1756       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1757         Result = 1;
1758       break;
1759     case FCmpInst::FCMP_ONE: // We know that C1 != C2
1760       // We can only partially decide this relation.
1761       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1762         Result = 0;
1763       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1764         Result = 1;
1765       break;
1766     }
1768     // If we evaluated the result, return it now.
1769     if (Result != -1)
1770       return ConstantInt::get(ResultTy, Result);
1772   } else {
1773     // Evaluate the relation between the two constants, per the predicate.
1774     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1775     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1776     default: llvm_unreachable("Unknown relational!");
1777     case ICmpInst::BAD_ICMP_PREDICATE:
1778       break;  // Couldn't determine anything about these constants.
1779     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1780       // If we know the constants are equal, we can decide the result of this
1781       // computation precisely.
1782       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1783       break;
1784     case ICmpInst::ICMP_ULT:
1785       switch (pred) {
1786       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1787         Result = 1; break;
1788       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1789         Result = 0; break;
1790       }
1791       break;
1792     case ICmpInst::ICMP_SLT:
1793       switch (pred) {
1794       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1795         Result = 1; break;
1796       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1797         Result = 0; break;
1798       }
1799       break;
1800     case ICmpInst::ICMP_UGT:
1801       switch (pred) {
1802       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1803         Result = 1; break;
1804       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1805         Result = 0; break;
1806       }
1807       break;
1808     case ICmpInst::ICMP_SGT:
1809       switch (pred) {
1810       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1811         Result = 1; break;
1812       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1813         Result = 0; break;
1814       }
1815       break;
1816     case ICmpInst::ICMP_ULE:
1817       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1818       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1819       break;
1820     case ICmpInst::ICMP_SLE:
1821       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1822       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1823       break;
1824     case ICmpInst::ICMP_UGE:
1825       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1826       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1827       break;
1828     case ICmpInst::ICMP_SGE:
1829       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1830       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1831       break;
1832     case ICmpInst::ICMP_NE:
1833       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1834       if (pred == ICmpInst::ICMP_NE) Result = 1;
1835       break;
1836     }
1838     // If we evaluated the result, return it now.
1839     if (Result != -1)
1840       return ConstantInt::get(ResultTy, Result);
1842     // If the right hand side is a bitcast, try using its inverse to simplify
1843     // it by moving it to the left hand side.  We can't do this if it would turn
1844     // a vector compare into a scalar compare or visa versa.
1845     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1846       Constant *CE2Op0 = CE2->getOperand(0);
1847       if (CE2->getOpcode() == Instruction::BitCast &&
1848           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1849         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1850         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1851       }
1852     }
1854     // If the left hand side is an extension, try eliminating it.
1855     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1856       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1857           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1858         Constant *CE1Op0 = CE1->getOperand(0);
1859         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1860         if (CE1Inverse == CE1Op0) {
1861           // Check whether we can safely truncate the right hand side.
1862           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1863           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
1864                                     C2->getType()) == C2)
1865             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1866         }
1867       }
1868     }
1870     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1871         (C1->isNullValue() && !C2->isNullValue())) {
1872       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1873       // other way if possible.
1874       // Also, if C1 is null and C2 isn't, flip them around.
1875       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1876       return ConstantExpr::getICmp(pred, C2, C1);
1877     }
1878   }
1879   return 0;
1882 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1883 /// is "inbounds".
1884 template<typename IndexTy>
1885 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1886   // No indices means nothing that could be out of bounds.
1887   if (Idxs.empty()) return true;
1889   // If the first index is zero, it's in bounds.
1890   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1892   // If the first index is one and all the rest are zero, it's in bounds,
1893   // by the one-past-the-end rule.
1894   if (!cast<ConstantInt>(Idxs[0])->isOne())
1895     return false;
1896   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1897     if (!cast<Constant>(Idxs[i])->isNullValue())
1898       return false;
1899   return true;
1902 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
1903 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
1904                                            const ConstantInt *CI) {
1905   if (const PointerType *PTy = dyn_cast<PointerType>(STy))
1906     // Only handle pointers to sized types, not pointers to functions.
1907     return PTy->getElementType()->isSized();
1909   uint64_t NumElements = 0;
1910   // Determine the number of elements in our sequential type.
1911   if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
1912     NumElements = ATy->getNumElements();
1913   else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
1914     NumElements = VTy->getNumElements();
1916   assert((isa<ArrayType>(STy) || NumElements > 0) &&
1917          "didn't expect non-array type to have zero elements!");
1919   // We cannot bounds check the index if it doesn't fit in an int64_t.
1920   if (CI->getValue().getActiveBits() > 64)
1921     return false;
1923   // A negative index or an index past the end of our sequential type is
1924   // considered out-of-range.
1925   int64_t IndexVal = CI->getSExtValue();
1926   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
1927     return false;
1929   // Otherwise, it is in-range.
1930   return true;
1933 template<typename IndexTy>
1934 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1935                                                bool inBounds,
1936                                                ArrayRef<IndexTy> Idxs) {
1937   if (Idxs.empty()) return C;
1938   Constant *Idx0 = cast<Constant>(Idxs[0]);
1939   if ((Idxs.size() == 1 && Idx0->isNullValue()))
1940     return C;
1942   if (isa<UndefValue>(C)) {
1943     PointerType *Ptr = cast<PointerType>(C->getType());
1944     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1945     assert(Ty != 0 && "Invalid indices for GEP!");
1946     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1947   }
1949   if (C->isNullValue()) {
1950     bool isNull = true;
1951     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1952       if (!cast<Constant>(Idxs[i])->isNullValue()) {
1953         isNull = false;
1954         break;
1955       }
1956     if (isNull) {
1957       PointerType *Ptr = cast<PointerType>(C->getType());
1958       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1959       assert(Ty != 0 && "Invalid indices for GEP!");
1960       return ConstantPointerNull::get(PointerType::get(Ty,
1961                                                        Ptr->getAddressSpace()));
1962     }
1963   }
1965   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1966     // Combine Indices - If the source pointer to this getelementptr instruction
1967     // is a getelementptr instruction, combine the indices of the two
1968     // getelementptr instructions into a single instruction.
1969     //
1970     if (CE->getOpcode() == Instruction::GetElementPtr) {
1971       Type *LastTy = 0;
1972       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1973            I != E; ++I)
1974         LastTy = *I;
1976       // We cannot combine indices if doing so would take us outside of an
1977       // array or vector.  Doing otherwise could trick us if we evaluated such a
1978       // GEP as part of a load.
1979       //
1980       // e.g. Consider if the original GEP was:
1981       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
1982       //                    i32 0, i32 0, i64 0)
1983       //
1984       // If we then tried to offset it by '8' to get to the third element,
1985       // an i8, we should *not* get:
1986       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
1987       //                    i32 0, i32 0, i64 8)
1988       //
1989       // This GEP tries to index array element '8  which runs out-of-bounds.
1990       // Subsequent evaluation would get confused and produce erroneous results.
1991       //
1992       // The following prohibits such a GEP from being formed by checking to see
1993       // if the index is in-range with respect to an array or vector.
1994       bool PerformFold = false;
1995       if (Idx0->isNullValue())
1996         PerformFold = true;
1997       else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
1998         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
1999           PerformFold = isIndexInRangeOfSequentialType(STy, CI);
2001       if (PerformFold) {
2002         SmallVector<Value*, 16> NewIndices;
2003         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2004         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2005           NewIndices.push_back(CE->getOperand(i));
2007         // Add the last index of the source with the first index of the new GEP.
2008         // Make sure to handle the case when they are actually different types.
2009         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2010         // Otherwise it must be an array.
2011         if (!Idx0->isNullValue()) {
2012           Type *IdxTy = Combined->getType();
2013           if (IdxTy != Idx0->getType()) {
2014             Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2015             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2016             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2017             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2018           } else {
2019             Combined =
2020               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2021           }
2022         }
2024         NewIndices.push_back(Combined);
2025         NewIndices.append(Idxs.begin() + 1, Idxs.end());
2026         return
2027           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
2028                                          inBounds &&
2029                                            cast<GEPOperator>(CE)->isInBounds());
2030       }
2031     }
2033     // Attempt to fold casts to the same type away.  For example, folding:
2034     //
2035     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2036     //                       i64 0, i64 0)
2037     // into:
2038     //
2039     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2040     //
2041     // Don't fold if the cast is changing address spaces.
2042     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2043       PointerType *SrcPtrTy =
2044         dyn_cast<PointerType>(CE->getOperand(0)->getType());
2045       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2046       if (SrcPtrTy && DstPtrTy) {
2047         ArrayType *SrcArrayTy =
2048           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2049         ArrayType *DstArrayTy =
2050           dyn_cast<ArrayType>(DstPtrTy->getElementType());
2051         if (SrcArrayTy && DstArrayTy
2052             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2053             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2054           return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
2055                                                 Idxs, inBounds);
2056       }
2057     }
2058   }
2060   // Check to see if any array indices are not within the corresponding
2061   // notional array or vector bounds. If so, try to determine if they can be
2062   // factored out into preceding dimensions.
2063   bool Unknown = false;
2064   SmallVector<Constant *, 8> NewIdxs;
2065   Type *Ty = C->getType();
2066   Type *Prev = 0;
2067   for (unsigned i = 0, e = Idxs.size(); i != e;
2068        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2069     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2070       if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
2071         if (CI->getSExtValue() > 0 &&
2072             !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
2073           if (isa<SequentialType>(Prev)) {
2074             // It's out of range, but we can factor it into the prior
2075             // dimension.
2076             NewIdxs.resize(Idxs.size());
2077             uint64_t NumElements = 0;
2078             if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2079               NumElements = ATy->getNumElements();
2080             else
2081               NumElements = cast<VectorType>(Ty)->getNumElements();
2083             ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
2084             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2086             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2087             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2089             // Before adding, extend both operands to i64 to avoid
2090             // overflow trouble.
2091             if (!PrevIdx->getType()->isIntegerTy(64))
2092               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2093                                            Type::getInt64Ty(Div->getContext()));
2094             if (!Div->getType()->isIntegerTy(64))
2095               Div = ConstantExpr::getSExt(Div,
2096                                           Type::getInt64Ty(Div->getContext()));
2098             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2099           } else {
2100             // It's out of range, but the prior dimension is a struct
2101             // so we can't do anything about it.
2102             Unknown = true;
2103           }
2104         }
2105     } else {
2106       // We don't know if it's in range or not.
2107       Unknown = true;
2108     }
2109   }
2111   // If we did any factoring, start over with the adjusted indices.
2112   if (!NewIdxs.empty()) {
2113     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2114       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2115     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2116   }
2118   // If all indices are known integers and normalized, we can do a simple
2119   // check for the "inbounds" property.
2120   if (!Unknown && !inBounds &&
2121       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2122     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2124   return 0;
2127 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2128                                           bool inBounds,
2129                                           ArrayRef<Constant *> Idxs) {
2130   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2133 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2134                                           bool inBounds,
2135                                           ArrayRef<Value *> Idxs) {
2136   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);