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