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