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