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